use lib qw(/home/olly/PERL_MODULES);

use Sets;
use Table;
use Fasta;
use strict;

if (!$ARGV[1]) {
	die "Usage : prg seq kmers\n";

}

my $ta = Table->new;
$ta->loadFile($ARGV[1]);

my $a_ref = $ta->getArray();

my $only5       = $ARGV[2];
my $fulldisplay = 1;

my $i = 1;
foreach my $r (@$a_ref) {
    
    
    my $fa = Fasta->new;
    $fa->setFile($ARGV[0]);

    my $match = 0;
    my $rank  = 1;
    while (my $a_seq = $fa->nextSeq()) {
	
	my ($n, $s) = @$a_seq;

	$s =~ s/t/u/g;
	
	my $ss = uc($s);
	$ss =~ s/U/T/g;

	$ss = Sets::getComplement($ss);

	#for (my $j=0; $j<=0; $j++) { #  uhh ?
	my $j = 0;

	my $kmer = substr($r->[0], 0, length($r->[0])-$j);
	my $km   = $kmer;
	
	$km =~ s/N/\./g;


	if ($ss =~ /$km/) {
	    
	    $km = Sets::getComplement($km);
	    $km =~ s/N/\./g;

	    my $lkm = lc($km);
	    $lkm =~ s/t/u/g;
	    
	    $s =~ s/$lkm/$km/g;
	    
	    
	    #print "$km\n";

	    my $a_ref_pos = Sets::getREMotifPositions($km, $s);
	    
	    
	    my $p = shift @$a_ref_pos;
	    
	    #if (($j > 0) && ($p != 0)) { # never executed
	    #    next;
	    #}
	    
	    if (defined($only5) && ($p > 1)) {
		$rank++;
		next;
	    }
	    

	    print "$i: $r->[0]\t$rank:$n\t$s\t$p\n"; 

	    $match++ if ($p > 1);

	    #last if ($match == 5); 
	}
	    
	#}
	$rank ++;

        last if ($rank > 600);
    }

    $fa->dispose();

    if ($fulldisplay == 0) {
	$r->[5] = $match;
	print join("\t", @$r); print "\n";
    }

    
    $i++;
}
