# Hi
# 
# My other, less memory-hungry version is as follows...
# 
# George P.
# 
# 
#! /opt/bin/perl5 -w

use strict;
use Getopt::Std;

my (%opts, $err);
getopts('d:', \%opts);
$err = "Usage: $0 -d <dictionary_file>\n";
die("$err\n") if (!defined $opts{d} || $opts{d} =~ /^ *$/);

my ($tmpdir, $tmpfl, $qfl, $afl);
$tmpdir = "/tmp";
$tmpfl = "$tmpdir/$$.wrds";
$qfl = "$tmpdir/questions";
$afl = "$tmpdir/answers";

open (TMPFL, "> $tmpfl") or die("ERROR: Cannot open $tmpfl: $!\n");
open (DICT, "< $opts{d}") or die("ERROR: Cannot open $opts{d}: $!\n");
while (my $wrd = lc <DICT>)
	{
	chomp $wrd;
	my ($tmpwrd, %blks, @blocks);
	($tmpwrd = $wrd) =~ s/[^a-z0-9]//g;
	next if (length $tmpwrd < 5);
	while (length $tmpwrd >= 4)
		{
		$blks{substr($tmpwrd, 0, 4)} = 1;
		$tmpwrd =~ s/^.//;
		}
	print TMPFL join("\n", map { "$_<==>$wrd"; } keys(%blks)) . "\n";
	}
close DICT;
close TMPFL;

system("sort $tmpfl -o $tmpfl");

my (@blocks, $oldwrd);
open (QUES, "> $qfl") or die("ERROR: Cannot open $qfl: $!\n");
open (ANS, "> $afl") or die("ERROR: Cannot open $afl: $!\n");
open (TMPFL, "< $tmpfl") or die("ERROR: Cannot open $tmpfl: $!\n");
while (<TMPFL>)
	{
	chomp;
	my ($block, $wrd) = split /<==>/, $_;
	if ($#blocks > -1 && $blocks[0] ne $block)
		{
		if ($#blocks == 0)
			{
			print QUES "$blocks[0]\n";
			print ANS "$oldwrd\n";
			}
		@blocks = ();
		}
	push (@blocks, "$block");
	$oldwrd = $wrd;
	}
if ($#blocks == 0)
	{
	print QUES "$blocks[0]\n";
	print ANS "$oldwrd\n";
	}
close TMPFL;
close ANS;
close QUES;

system("rm $tmpfl");

