#!/w/local/bin/perl5

use diagnostics;
use strict;

use CGI::Carp qw(fatalsToBrowser);
use CGI qw(:standard :html3);

$| = 1;

my @digits = ("abc",
	      "def",
	      "ghi",
	      "jkl",
	      "mno",
	      "prs",
	      "tuv",
	      "wxy" );


sub expanded {
    my ($num) = (@_);
    my @result;
    for (my $i=0 ; $i<3 ; $i++) {
	foreach my $c (split('', $num)) {
	    if ($c =~ /[2-9]/) {
		$result[$i] .= substr($digits[$c - 2], $i, 1);
	    } else {
		$result[$i] .= $c;
	    }
	}
    }
    return \@result;
}


sub makepossible {
    my ($num) = (@_);
    my $length = length($num);
    my @result;
    my @choose;
    my @index;
    foreach my $c (split('', $num)) {
	push(@choose, $digits[$c - 2]);
	push(@index, 0);
    }
    while (1) {
	my $str = "";
	for (my $i=0 ; $i<$length ; $i++) {
	    $str .= substr($choose[$i], $index[$i], 1);
	} 
	push @result, $str;
	my $w = $length - 1;
	while (++($index[$w]) > 2) {
	    $index[$w] = 0;
	    $w--;
	    if ($w < 0) {
		return \@result;
	    }
	}
    }
}
	
    
    

my @wordlist;

sub loadwordlist {
    open(WL, "<wordlist") || die "Can't open wordlist";
    for (my $i=1 ; $i<20 ; $i++) {
	$wordlist[$i] = [];
    }
    my $cnt = 0;
    while (<WL>) {
	chomp;
	my $l = length($_);
	push(@{$wordlist[$l]}, $_);
	if ($cnt++ == 100) {
	    $cnt = 0;
	    print ".";
	}
    }
    for (my $i=1 ; $i<20 ; $i++) {
	print "$i: " . @{$wordlist[$i]} . "\n";
    }
}


sub findwords {
    my ($num) = (@_);
    my @result;
    my $length = length($num);
    for (my $start = 0 ; $start < $length ; $start++) {
	for (my $end = $length - 1 ; $end > $start ; $end--) {
	    my $l = $end - $start + 1;
	    my $bit = substr($num, $start, $l);
	    if ($bit !~ /^[2-9]+$/) {
		next;
	    }
	    my $list = makepossible($bit);
#	    print $bit . " " . @$list . "\n";
	    my $cur = shift(@$list);

	    open(WL, "<wordlist$l") || next;
	    OUTER: while (<WL>) {
		chomp;
		while ($_ gt $cur) {
		    $cur = shift(@$list);
		    if (!defined $cur) {
			last OUTER;
		    }
		}
		if ($cur eq $_) {
		    push @result,
		    ("." x $start) . $cur . ("." x ($length - $end - 1));
		}
	    }
	    close (WL);
	}
    }
    return \@result;
}



sub dumplist {
    my ($ref) = (@_);
    for (my $i=0 ; $i<@$ref ; $i++) {
	print $ref->[$i] . "\n";
    }
}

print header();
print start_html(-Title=>"Find words in phone numbers.");

my $num = param("num");
if (defined $num) {
    print "<PRE>";
    print $num . "\n";
    
    dumplist(expanded($num));
    print "\n";
    dumplist(findwords($num));
    print "</PRE><HR>\n";
}

print h1("Find words in phone numbers");
print p("Enter a phone number, and I'll search for words in it.");

print start_form("Get");
print textfield(-name=>"num", -size=>7) . br();
print submit(-name=>"Submit");
print end_form();

