#!/usr/local/bin/perl

# perl word descrambler
# useful with dictionary from http://wordlist.sourceforge.net/
# 20060619 - Jeremy Kister - http://jeremy.kister.net./

use strict;

my %dictionary;
opendir(DIR, "$ENV{'HOME'}/data/dictionary/");
foreach my $file (grep {/^english-word/} readdir DIR){
	open(DICT, "$ENV{'HOME'}/data/dictionary/$file");
	warn "reading data/dictionary/$file\n";
	while(<DICT>){
		chop;
		next unless(/^[a-z]+$/);
		my $len = length($_);
		push @{$dictionary{$len}}, $_;
	}
	close DICT;
}
closedir DIR;

while(1){
	print "word: ";
	chop(my $scramble = <STDIN>);
	$scramble =~ s/\s+//g;

	my $slen = length($scramble);
	my @s = split //, $scramble;
	foreach my $word (@{$dictionary{$slen}}){
		my @w = split //, $word;
		my $found;
		foreach my $sl (0..($slen-1)){
			my $lfound;
			foreach my $l (0..($slen-1)){
				if($s[$sl] eq $w[$l]){
					delete $w[$l];
					$found++;
					$lfound=1;
					last;
				}
			}
			last unless($lfound);
		}
		next unless($found == $slen);
		print "$word\n";
	}
}
