#!/usr/bin/perl

$PLATFORM='GPL3991.dat';
$COORD='CDS_coord_in_rna.asn';
$SEQ='rna.fa';

if ($ARGV[0] eq '')
{
    print "Please enter miRNA extended seed sequence (nt 2-8) (e.g. for miR-7, ./Module_array_signal_vs_seed_match_number.pl GGAAGAC).\n";
}
else
{
    open(GPL,$PLATFORM);
    while(<GPL>)
    {
	chomp;
	if (($_ !~ /^\#/) && ($_ !~ /^[ \*]*$/))
	{
	    @array=split(' ',$_);
	    $accession{$array[0]}=$array[1];
	}
    }
    close(GPL);

    open(COORD,$COORD);
    while(<COORD>)
    {
	chomp;
	@array=split(' ',$_);
	@array2=split('-',$array[1]);
	$cds_end{$array[0]}=$array2[1];
#	print "For $array[0], CDS end : $cds_end{$array[0]}\n";
    }
    close(COORD);

    open(SEQ,$SEQ);
    while(<SEQ>)
    {
	chomp;
	if (/^>/)
	{
	    s/.*\|(.*)\|.*/\1/;
	    s/\..*//;
	    $acc=$_;
	}
	else
	{
	    $seq{$acc}=$seq{$acc}.$_;
	}
    }
    close(SEQ);

    $anti_seed=reverse $ARGV[0];
    $anti_seed=~tr/ACGUT/TGCAA/;
    ($match6,$match7_m8,$match8)=($anti_seed,$anti_seed,$anti_seed);
    $match6=~s/^.//;
    $match7_t1A=$match6;
    $match7_t1A=~s/$/A/;
    $match8=~s/$/A/;

    print "Probe 6-mers 7-mers_t1A 7-mers_m8 8-mers\n";
    foreach $probe (keys %accession)
    {
	$utr=substr $seq{$accession{$probe}},$cds_end{$accession{$probe}}+1;
	@ified_counts=();
	for $match ($match6,$match7_t1A,$match7_m8,$match8)
	{
	    $count=0;
	    $offset=0;
	    $result=index(uc $utr,$match,$offset);
            while ($result != -1)
            {
                ++$count;
		$offset=$result+1;
		$result=index(uc $utr,$match,$offset);
	    }
	    push(@ified_counts,$count);
	}
	@unified_counts=($ified_counts[0]-$ified_counts[1]-$ified_counts[2]+$ified_counts[3],$ified_counts[1]-$ified_counts[3],$ified_counts[2]-$ified_counts[3],$ified_counts[3]);
	print "$probe @unified_counts\n";
    }
}
