#!/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/irefile.info");

print TMP "irefile 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;
    }
}


# gets command line arguments - prints them to temporary file

$i=0;
while ($i <= $#ARGV) {

#for ($i=0; $i <= $#ARGV; $i++) {

    print TMP $ARGV[$i]." ";

    if ($ARGV[$i] =~ m/\-src/) {
	if ($ARGV[$i+1] =~ m/^\+(\S+)/) {
	    $source_folder = $1;
	    print TMP "source folder = $source_folder\n";
	    $i++;
	} else {
	    print "Error: folder name lacks preceeding '+' or is";
	    print " in wrong format.\n";
	    &print_usage;
	}
    } elsif ($ARGV[$i] =~ m/\-file/) {
	$source_file = $ARGV[$i+1];
	print TMP "source file = $source_file\n";
	$i++;
    } elsif ($ARGV[$i] =~ m/^\+([^+]+)/) {
	$dest_folder = $1;
	print TMP "destination folder = $dest_folder\n";
    } else {
	$orig_message[$#orig_message+1] = $ARGV[$i];
	print TMP "message name = $ARGV[$i]\n";
    }
    $i++;
}   

$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+//) {
	print "$tv[$i] = $1\n";
	$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++;
	}
    }
}

close(DATA);

foreach $msg (@orig_message) {
    if ($source_folder ne "") {
	open(MSG, "< " . $home_dir . $mail_path . $source_folder."/".$msg) ||
	    print TMP "Could not open " . $home_dir . $mail_path . $source_folder."/".$msg . "\n";
    } else {
	open(MSG, "< $msg") || print TMP "Could not open $msg\n";
    }

    @lines = <MSG>;

    &rcvstore($dest_folder);

    print "Input file: \n";

    foreach $line (@lines) 
    {
	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/;
		print $wrd." ";
	 	if ($index{$wrd} == 0) {
		    $word[$#word+1] = $wrd;
		    $index{$wrd} = $#word;
		    $nk{$wrd.",".$dest_folder}++;
		} else {
		    $nk{$wrd.",".$dest_folder}++;
		}
		$n{$dest_folder}++;
	    }
	}
    }
    close(MSG);
}

&remove_msgs;

# reopen the data file and write the learned information

open(DATA, "> $home_dir.idata") || die "Couldn't open data file\n";

open(LS, "ls -F $home_dir$mail_path | ") || die "Couldn't find folders\n";

$i = 1;
$tv[$i++] = "inbox";
print DATA "inbox ";

while (<LS>) {
    chop;
    if ((!($_ =~ m/MyInc/)) && ($_ ne "inbox") && (s/\/$//)) {
	$tv[$i++] = $_;
	print DATA $_." ";
    }
}

close(LS);

print DATA "\n";

for ($i=1; $i <= $#tv; $i++) {
    if ($n{$tv[$i]} > 0) {
	print DATA $n{$tv[$i]}." ";
    } else {
	print DATA "0 ";
    }
}
print DATA "\n";

for ($i=1; $i <= $#word; $i++) {

    print DATA $word[$i]." ";
    for ($j=1; $j <= $#tv; $j++) {
	
	if ($nk{$word[$i].",".$tv[$j]} > 0) {
	    print DATA $nk{$word[$i].",".$tv[$j]}." ";
	} else {
	    print DATA "0 ";
	}
    }

    print DATA "\n";
}

close(DATA);

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

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);
}

sub remove_msgs {
    
    print TMP "Removing old messages\n";
    
    $string = "";
    foreach $msg (@orig_message) {
	$string .= $msg." ";
    }
    if ($source_folder ne "") { $string .= "+$source_folder"; }
    $string = "/usr/bin/mh/rmm ".$string;
    system $string;
    print TMP $string."\n";
}

