#!/usr/bin/perl

# Format of data files is as follows:
# line 1: target value names each separated by a space
# line 2: # of total words for all documents in each target value each
#         separated by a space
# line 3: a vocab word, followed by the number of instances of each in the
#         various target values

# When a vocab word is refiled it is assumed that this is the desired
#      target value (or folder, in this case).

# tv = target value

# This program is written in an attempt to emulate the MH refile command
#   while adding the benefit of allowing it to traing a bayesian-style
#   learning algorithm.  The only options which it currently emulates are
#   '-src +folder' and '-file file'.  It supports refiling multiple messages,
#   but does not support filing messages into multiple folders.

open(TMP, ">> /tmp/ifilter.info");

print TMP "ifilter called ";
print TMP "(0-$#ARGV)\n";


$home_dir = $ENV{"HOME"}."/";

open(MH, "< $home_dir.mh_profile");

while (<MH>) {
    if (m/Path: (\w+)/) {
	$mail_path = $1;
	$mail_path .= "/";
    }
    if (m/draft-folder: (\w+)/) {
	$draft_folder = $1;
    }
}


$tot_words = 0;

# target values and 'n' both start with index 1
$tv[0] = 0;

$data_file = $home_dir.".idata";

if (open(DATA, "< $data_file")) {
    $line = <DATA>;
    while ($line =~ s/(\w+)\s+//) {
	$tv[$#tv+1] = $1;
    }

    $line = <DATA>;
    $i=1;
    while ($line =~ s/(\d+)\s+//) {
	$n{$tv[$i++]} = $1;
    }

    $word[0] = "";

    while (($line = <DATA>) && (!($line =~ m/^\s*$/)))  {
	$tot_words++;

	$line =~ s/^(\w+)\s+//;
	$word[$#word+1] = $1;
	$index{$1} = $#word;
	
	$tv_index = 1;
	while ($line =~ s/(\d+)\s+//) {
	    $nk{$word[$#word].",".$tv[$tv_index]} = $1;
	    $tv_index++;
	}
    }
} else {

    @lines = <STDIN>;

    &rcvstore(inbox);

    exit 0;
}

close(DATA);

$best_rating = 0;
$best_target = 0;

@lines = <STDIN>;

print "Input file: \n";

for ($i=1; $i <= $#tv; $i++) {
    $target_rating = 0;
    for ($j=0; $j <= $#lines; $j++) {
	
	$line = $lines[$j];
	while ($line =~ s/([A-Za-z]+)[^A-Za-z]+//) {
	    $wrd = $1;
	    # get rid of tiny words
	    if (length($wrd) > 3) {

		$wrd =~ tr/A-Z/a-z/;
		
		$target_rating += log(($nk{$wrd.",".$tv[$i]} + 1) /
				      ($n{$tv[$i]} + $tot_words));
	    }
	}
    }

    if (($target_rating > $best_rating) || ($best_target == 0)) {
	$best_rating = $target_rating;
	$best_target = $i;
    }
}

print "Filed message in $tv[$best_target] ($best_target)\n";

print TMP "\n";
close(TMP);

rcvstore($tv[$best_target]);

exit 0;

# rcvstore function expects lines of input file to be stored in @lines - bad
#   assumption, I know.  I'll fix it later.  Really :)

sub rcvstore {
    local($mailbox) = @_;

    print TMP "Filed to $mailbox\n";
    
    open(RCV, "| /usr/lib/mh/rcvstore +$mailbox") || die "could not rcvstore\n";
    
    foreach $line (@lines) {
	print RCV $line;
    }
    
    close(RCV);
}
