#!/afs/athena/contrib/perl/perl

print("Slurping dictionary...\n");
#open(DICT, "/afs/sipb/project/new-charon/site/usr/local/games/mboggle/lib/words/allwords");
open(DICT, "/usr/dict/words");
$i = 0;
while(<DICT>){
    chop;
    tr/A-Z/a-z/;
    $dic[$i] = $_ if ((length > 2));
    $i++ if ((length > 2));
}
foreach $i (@dic){
if($i eq ''){print("Bad dic entry -$i-. $k\n");}
$k = $i;
}
$dic[$i++]= 'i';
$dic[$i]= 'a';
print("done...\n");
$anag = join('', @ARGV);
$anag =~ y/A-Z/a-z/;
$anag =~ s/\W//g;
$amake = '';
$anag = join('', sort(split(//, $anag)));
$sava = $anag;
print("Anagramming: $anag\n");
$| = 1;
&look($amake, $anag);

sub look {
    local($amake, $anag) = @_;
    local($oanag, $oamake);
    local($x);
    print("\nStarting dict sweep...($amake, $anag)\n");
    foreach ($x=0;$x<=$#dic;$x++){
	$word = $dic[$x];
	$fl = substr($word, 0, 1);
	if($fl ne $ol){$ol = $fl;print $ol;}
	$test = substr($dic[$x+20], 0,1);
	$test2 = substr($dic[$x+200],0,1);
	if ($anag !~ /$test2/) { $x += 200;}
	if ($anag !~ /$test/) { $x += 20;}
	next if($anag !~ /$ol/);
#	print("$word, ");
	$pat = join('.*',sort(@ls = split(//, $word)));
#	print("Looking for $pat\n");
	if($anag =~ /$pat/){
	    $oamake = $amake;
	    $amake .= "$word ";
	    $oanag = $anag;
	    foreach (@ls){
		$anag =~ s/$_//;
	    }
	    print("Substring: $word\n") if (length($word) >3);
	    print("($word)Amake so far: $amake  [$anag]\n");
		if(!$anag){
		    print("*****".$amake."\n");
		    $anag = $oanag;
		    $amake = $oamake;
		    print("Found anagram, going again at word $word. ($amake, $anag)\n");
		}
		else
		{
		    print("Word: $word\n");
		    &look($amake, $anag);
		    $amake = $oamake;
		    $anag = $oanag;
		    print("Done with one subrun, proceeding from word $word.\n");
		}
	
	}
    }
}
