#!/usr/bin/perl

$mode = shift(@ARGV);

%ch = (2, "abc",
       3, "def",
       4, "ghi",
       5, "jkl",
       6, "mno",
       7, "pqrs",
       8, "tuv",
       9, "wxyz",
       "_", "_");

if($mode eq "-learn"){
    while(<>){
	y/A-Z/a-z/;
	s/_//g;
	s/[^\w ]//g;
	s/ /_/g;
	@l = split(//, $_);
	$prev = "_";
	$prev2 = "_";
	foreach $l (@l) {
	    $bfreq{"$prev$l"}++;
	    $tfreq{"$prev2$prev$l"}++;
	    $prev2 = $prev;
	    $prev = $l;
	}
    }

    for $p (sort {$bfreq{$b} <=> $bfreq{$a}; } keys %bfreq){
	print "bi $p $bfreq{$p}\n";
    }
    for $p (sort {$tfreq{$b} <=> $tfreq{$a}; } keys %tfreq){
	print "tri $p $tfreq{$p}\n";
    }
}
else{
    open(BG, "/tmp/bigrams");
    while(<BG>){
	($type, $bg, $n) = split;
	if($type eq "bi"){
	    $bf{$bg} = $n;
	}
	else{
	    $tf{$bg} = $n;
	}
    }
    $word = shift;
    $word =~ s/ /_/g;
    $word =~ tr/a-z/22233344455566677778889999/;
    print "Word is $word\n";
    @wl = split(//, $word);
    @possibles = ();
    &genword("", @wl);
    $maxscore = 0;
    foreach $pos (@possibles){
	@l = split(//, $pos);
	$prev = "_";
	$prev2 = "_";
	$score = 0;
	foreach $l (@l){
	    $score += $bf{"$prev$l"};
	    $score += $tf{"$prev2$prev$l"}/4;
	    $prev2 = $prev;
	    $prev = $l;
	}
	if($score > $maxscore){
	    print "$pos $score\n";
	    $maxscore = $score;
	}
    }
}

sub genword{
    my $sofar = shift;
    if($#_ < 0){
	push(@possibles, $sofar);
    }
    my $nextletter = shift;
    my @rem = @_;
    my @choices = split(//, $ch{$nextletter});
    my $c;
    for $c (@choices){
	&genword($sofar.$c, @rem);
    }
}
