#!/usr/bin/perl

if ($ARGV[2] eq '')
{
    print "Please enter script arguments (e.g., ./Module_imperfect_seed_match_search.pl Target_UTRs.fa CATTCC genes.gtf). The first argument is the name of a fasta file containing UTRs to scan; the second argument is the perfect seed match (reverse complement of miRNA nt 2-7) of which variations will be searched; the third argument is a GTF file describing the genes to be scanned (e.g., excluding ncRNAs).\n";
}
else
{
    open(GTF,$ARGV[2]);
    while(<GTF>)
    {
	chomp;
	s/.*gene_id "//;
	s/".*//;
	$select{$_}=1;
    }
    close(GTF);


    @motifs=(uc $ARGV[1]);
    $motif_length=length($ARGV[1]);
    for ($i=0;$i<$motif_length;++$i) # List of single substitution and single deletion variants
    {
	if ($i>0)
	{
	    $part1=substr $ARGV[1],0,$i;
	}
	else
	{
	    $part1='';
	}
	$part2=substr $ARGV[1],$i+1;
	push(@motifs,$part1.'.'.$part2,$part1.$part2);
    }
    for ($i=1;$i<$motif_length;++$i) # List of single insertion variants
    {
	$part1=substr $ARGV[1],0,$i;
	$part2=substr $ARGV[1],$i;
	push(@motifs,$part1.'.'.$part2,);
    }

### Below: unifying motifs (sometimes some variants are identical):
    %seen = ();
    @uniqu = grep { ! $seen{$_} ++ } @motifs;
    @motifs=@uniqu;
### Above: unifying motifs (sometimes some variants are identical).


    open(SEQ,$ARGV[0]);
    while(<SEQ>)
    {
	chomp;
	if (/^>/)
	{
	    $seq_name=$_;
	    $seq_name=~s/^> *//;
	    $gene_name=$seq_name;
	    $gene_name=~s/.*; gene: //;
	    if ($select{$gene_name})
	    {
		push(@{$isoforms{$gene_name}},$seq_name);
	    }
	}
	else
	{
	    if ($select{$gene_name})
	    {
		$seq{$seq_name}=$_;
	    }
	}
    }
    close(SEQ);
    
    $radical=$ARGV[0];
    $radical=~s/.*\///;
    $radical=~s/\.fa$//;
    open(OUT,">Imperfect_matches_to_$ARGV[1]"."_in_$radical".".dat");
    print OUT "Gene @motifs\n";
    foreach $gene (keys %isoforms)
    {
#	print "gene=$gene\n";
	$l=0;
	foreach $isoform (@{$isoforms{$gene}})
	{
	    if (length($seq{$isoform})>$l)
	    {
		$l=length($seq{$isoform});
		$longest=uc $seq{$isoform};
	    }
	}
#	print "Longest isoform: $longest\n";
	print OUT "$gene";
	for $motif (@motifs)
	{
	    if ($longest=~/$motif/)
	    {
		print OUT " 1";
	    }
	    else
	    {
		print OUT " 0";
	    }
	}
	print OUT "\n";
    }
}
