#!/usr/bin/perl -w
use strict;

# On first run to create css files, run plain ./learnspam.pl
# On reruns, run with ./learnspam.pl rerun

sub callcrm {
    my ($m, $command) = @_;

    return if $m eq '';
    my $esave = $ENV{LC_CTYPE};
    $ENV{LC_CTYPE}='fi_FI.UTF-8';

    # For debugging, this file holds the latest text fed to crm.
    # When crm hangs, this will help..
    #open (X, "> latest.txt") or die "> latest.txt: $!";
    #print X $m;
    #close X;

    # print STDERR "LEARN: $command\n";
    #  -s 5000000
    open (P, "| crm ./learnspam.crm $command -C") or die "learnspam.crm: $!";
    print P $m;
    close P or die "learnspam.crm: close: $! $? $@";
    if (defined $esave) {
	$ENV{LC_CTYPE}=$esave;
    } else {
	delete $ENV{LC_CTYPE};
    }
}


sub learn {
    my ($f, $command, $m, $maxcount) = @_;

    my $count = 0;
    while (<$f>) {
	if (/^From /) {
	    if ($$m ne '') {
		if (++$count >= $maxcount) {
		    #print STDERR "CALLCRM with $count messages\n";
		    &callcrm($$m, $command);
		    $$m = $_;
		    return 1;
		}
	    }
	    if ($$m ne '') {
		# ^a is used as message separator in text fed to learnspam.crm
		$$m .= "\001";
	    }
	}
	$$m .= $_;
    }
    #print STDERR "CALLCRM2 with $count messages\n";
    &callcrm($$m, $command);
    $$m = '';
    return 0;
}

# Open files to be learned and learn some messages from each alternating.

open (N, '< nonspamtext.txt') or die "nonspamtext.txt: open: $!";
open (S, '< spamtext.txt') or die "spamtext.txt: open: $!";

my $nfile = 'new-nonspam.css';
my $sfile = 'new-spam.css';

my $n = 1;
my $s = 1;
my $ss = '';
my $nn = '';
my $cmd_n = "$nfile $sfile";
my $cmd_s = "$sfile $nfile";
my $cmd_n_2 = $cmd_n;
my $cmd_s_2 = $cmd_s;
my $count = 1;

if (!defined $ARGV[0] || $ARGV[0] ne 'rerun') {
    unlink ($nfile, $sfile);
    $cmd_n = $nfile;
    $cmd_s = $sfile;

    if (defined $ARGV[0] && $ARGV[0] eq 'learnall') {
	$cmd_n_2 = $cmd_n;
	$cmd_s_2 = $cmd_s;
    }
}

while ($n || $s) {
    if ($n) {
	$n = &learn ('N', $cmd_n, \$nn, $count);
    }
    if ($s) {
	$s = &learn ('S', $cmd_s, \$ss, $count);
    }
    $cmd_s = $cmd_s_2;
    $cmd_n = $cmd_n_2;
    # TRE does not match well in UTF-8 environment. Keep $count=1.
    #$count *= 2;
    #$count = 20 if $count > 20;
}
close S;
close N;

exit (0);
