# For this weeks quiz, I used substr to extract the fragments and a hash
# (%qs) to store them in. Initially I stored all the question words I found 
# in the hash with a delimiter, on the basis that I might want to know them 
# at a later date but then I started worndering how much memory that was 
# using.
# 
# I added the Devel::Size code to have a look, which I'd just read about in 
# Mark Fowlers excellent Perl Advent calendar ( 
# http://www.perladvent.org/2002/6th/ ). I also wrapped a bit of code around 
# it in case users of the script don't have Devel::Size installed.
# 
# On discovering that the hash used up approx 25Mb when churning Web2 I 
# changed to a simpler strategy of indicating duplicates with undef and 
# uniques with the question word.
# 
# Anyway, here it is.
# 
# Simon.
# 
#------------- game.pl ---------------

#! /usr/bin/perl

use warnings;
use strict;
use IO::File;

# Try and load the Devel::Size diagnostics but no problem
# if it's not installed.
my $sizecheck = 1;
eval {require Devel::Size};
$sizecheck = 0 if $@;

my %qs = ();
my $qfile = "questions";
my $afile = "answers";

my $qfh = IO::File->new( $qfile, "w" );
die "Failed to open $qfile for writing\n" unless (defined $qfh);

my $afh = IO::File->new( $afile, "w" );
die "Failed to open $afile for writing\n" unless (defined $afh);

while (my $word = <>) {
    chomp $word;
    next unless (length($word) >= 4); # ignore short words
    
    my $maxoff = length($word) - 4; # how many sequences in this word
    $word = lc($word); # Web2 has capitalised words in it
    for my $offset (0..$maxoff) {
        my $try = substr( $word, $offset, 4 );
        $qs{ $try } = (exists $qs{ $try }) ? undef : $word;
    }
}

my $valid=0;
for (sort keys %qs) {
    next unless defined ($qs{ $_ }); # skip any seq without an answer
    print $qfh "$_\n";
    print $afh "$qs{ $_ }\n";
    $valid++;
}

$qfh->close();
$afh->close();

# Print some statistics
print "Found ".scalar(keys(%qs))." unique sequences\n";
print "Of which $valid appeared only once\n";

# Print out how much ram the hash used but only if Devel::Size was
# installed
if ($sizecheck) {
    print "The hash used ".Devel::Size::total_size(\%qs)." bytes\n";
}else{
    print "Memory check disabled. Consider installing Devel::Size\n";
}


