#!/usr/bin/perl
use Bio::SeqIO;
use Tree::Suffix;
 

die "Usage : $0 fastafile alphabet wordlength"
    unless $#ARGV==2;

(my $fastafile, my $alphabet,my $wordlength)=@ARGV;

$seqio_obj = Bio::SeqIO->new(-file => $fastafile, -format => "fasta" );
$seq_obj=$seqio_obj->next_seq;

$tree  = Tree::Suffix->new($seq_obj->seq);




my @tokens=split //,$alphabet;
$count=$tree->find("$tokens[0]");
my $codeblock=gen_loop(\@tokens,$wordlength,$wordlength);
eval $codeblock;
print $@;

sub gen_loop
{
    my $codeblock='';
    (my $tokens, my $wordlength, my $index)=@_;
    if ($index>0) {
	$codeblock.="foreach my \$token$index (".join(',',map ("'".$_."'",@$tokens)).") {\n";
	$codeblock.=gen_loop($tokens,$wordlength,$index-1);
	$codeblock.="}\n"
    } else {
	$codeblock.="\$word=\"";
	for (my $indexloop=$wordlength;$indexloop>0;$indexloop--) {
	    $codeblock.="\$token".$indexloop;
	}
	$codeblock.="\";\n";	
	$codeblock.="\$count = \$tree->find(\$word);\n";	
	$codeblock.="print \"\$word\t\$count\\n\";\n";
}
    return $codeblock;
}

