# ---- Gosper2.pl ----
# --------------------
# - input a list of words
# - output questions and answers to STDOUT
# - usage: perl Gosper2.pl inputfilename > outputfilename
# - Ran with ActiveState Perl on Windoze
# - Lowercase all of the words of dictionary
# - Duplicate words will count as one entry

use strict;
use warnings;

# Expect an argument for input dictionary
# ---------------------------------------
die "Usage: perl Gosper2.pl wordlistfile > outputfile\n" 
   unless (defined $ARGV[0] );

my $infile = $ARGV[0];

open (IN, $infile) or die "Could not open $infile for read: $! \n";

my (%all_matches,%final_matches,%chunkcount);
my ($wordchunk,$wordkey,$chunk,$word);

# Read dictionary and populate hash 
# with word plus 4-char chunk as key
# and 4-char chunk as value
# -----------------------------------
while (<IN>) {
        chomp;
        my $wordlen = length;
        next if ($wordlen < 4);
        $_ = lc; #convert to all lowercase
        for (my $i=0; $i<=($wordlen-4); $i++) {
                $chunk = substr($_, $i, 4);
                $wordkey = $_ . '#' . $chunk;
                $all_matches{$wordkey} = $chunk;
        }
} 
close IN;

# Count occurrences of 4-char chunks using a hash
# -----------------------------------------------
for $chunk (sort values %all_matches) {
        $chunkcount{$chunk} += 1;
}

# Populate a hash with 4-char chunks that have only 1 occurrence
# key=4-char chunk; value=dictionary word
# --------------------------------------------------------------
for $wordkey ( sort keys %all_matches ) {
        ($word,$chunk) = split /\#/, $wordkey;
        if ($chunkcount{$chunk} == 1 ) {
                $final_matches{$chunk} = $word;
        }
}

# Output hash to STDOUT
# ---------------------

for $chunk (sort keys %final_matches) {
   printf "\t%s\t\t%s\n", $chunk, $final_matches{$chunk};
}
