#!/usr/bin/perl

if ($ARGV[3] eq '')
{
    print "Please enter script arguments (e.g., ./Module_CLIP_vs_TargetScan.pl GGAAUGU Cuffdiff_quartile_m3_vs_m6.dat mmu_Summary_Counts.txt Synchronized_annotations_from_CLIP_names_absent_from_TargetScan). First argument is the seed sequence of the miRNA of interest, second argument is a data file containing CLIP results, third argument is a 'Summary_Counts' file from TargetScan, fourth argument is a conversion table for gene names from the CLIP result file.\n";
}
else
{
    print "Now loading $ARGV[2]...\n";
    open(TARGETSCAN,$ARGV[2]);
    while(<TARGETSCAN>)
    {
	chomp;
        @array=split('\t',$_);
        if ($array[2] eq $ARGV[0])
        {
            push(@{$context_score{$array[1]}},$array[13]);
            push(@{$PCT{$array[1]}},$array[14]);
        }
        $analyzed{$array[1]}=1;
    }
    close(TARGETSCAN);


    print "Now loading $ARGV[3]...\n";    
    open(CORRESP,$ARGV[3]);
    while(<CORRESP>)
    {
        chomp;
        if ($_ ne 'Gene Synonym')
        {
            @array=split(' ',$_);
            push(@{$synonyms{$array[0]}},$array[1]);
        }
    }
    close(CORRESP);

    open(OUT,">Annotated_$ARGV[0]_predicted_targets_in_$ARGV[1]");
    print "Now reading $ARGV[1]...\n";
    open(CLIP,$ARGV[1]);
    while(<CLIP>)
    {
	chomp;
        if ($_ eq 'id log2FoldChange pval padj')
        {
            print OUT "$_ Context_score Aggregate_PCT\n";
        }
        else
        {
            $gene=$_;
            $gene=~s/ .*//;
            $c='NA';
            $p='NA';

            if (push(@{$context_score{$gene}}))
            {
                $c=&median(@{$context_score{$gene}});
                $p=&median(@{$PCT{$gene}});
                print OUT "$_ $c $p\n";
            }
            else
            {
                foreach $s (@{$synonyms{$gene}})
                {
                    if (push(@{$context_score{$s}}))
                    {
                        $c=&median(@{$context_score{$s}});
                        $p=&median(@{$PCT{$s}});
                    }
                }
                if ($c eq 'NA')
                {
                    @possible_names=(@{$synonyms{$gene}});
                    push(@possible_names,$gene);
                    foreach $s (@possible_names)
                    {
                        if ($analyzed{$s})
                        {
                            $c='NP';
                            $p='NP';
                        }
                    }
                }
                if ($c ne 'NA') # Do not print the genes that were not analyzed by TargetScan
                {
                    print OUT "$_ $c $p\n";
                }
            }
        }
    }
    close(CLIP);
    close(OUT);
}

sub median
{
    my @vals = sort {$a <=> $b} @_;
    my $len = @vals;
    if($len%2) #odd?
    {
        return $vals[int($len/2)];
    }
    else #even
    {
        return ($vals[int($len/2)-1] + $vals[int($len/2)])/2;
    }
}
