#!/usr/bin/perl

if ($ARGV[0] eq '')
{
    print "Please give script argument (e.g., ./Module_sums_target_abundances.pl Targets_according_to_CLIP_with_raw_p-values_DESeq2_m1m2.dat). Such files were generated on Garonne (directory /home/herve/Natalia/NatCLIP/Results_from_BGI/Final_9_samples/Differential_expression_by_Natalia/) on September 30, 2015.\n";
}
else
{
    open(CLIP,$ARGV[0]);
    while (<CLIP>)
    {
	chomp;
	if ($_ ne 'id log2FoldChange pval padj Context_score Aggregate_PCT')
	{
	    @array=split(' ',$_);
            push(@target_list,$array[0]);
        }
    }
    close(CLIP);

    @sample_list=('A','B','C','D','E','F','G','H','I');
    foreach $sample (@sample_list)
    {
        $file='/mnt/data/home/herve.seitz/Natalia/RNA-Seq/C2C12/'.$sample.'/cufflinks_'.$sample.'_options_bG/genes.fpkm_tracking'; #these files were copied in directories 'A' to 'I' of 'Figure4.tar.bz2'
        open(RNASEQ,$file);
        while(<RNASEQ>)
        {
            chomp;
            if ($_ !~ /^tracking_id\tclass_code\tnearest_ref_id\tgene_id\tgene_short_name\ttss_id\tlocus\tlength\tcoverage\tFPKM\tFPKM_conf_lo\tFPKM_conf_hi\tFPKM_status$/)
            {
                @array=split('\t',$_);
	        ($gene,$abundance,$abundance_low,$abundance_high)=($array[0],$array[9],$array[10],$array[11]);
	        $fpkm{$gene}{$sample}=$abundance;
	        $fpkm_low{$gene}{$sample}=$abundance_low;
	        $fpkm_high{$gene}{$sample}=$abundance_high;
	    }
        }
        close(RNASEQ);
    }

    $outfile=$ARGV[0];
    $outfile=~s/^Targets/Abundances_of_target/;
    open(OUT,">$outfile");
    print OUT "RNA";
    foreach $sample (@sample_list)
    {
        print OUT " $sample"."_fpkm $sample"."_fpkm_confidence_low $sample"."_fpkm_confidence_high";
    }
    print OUT "\n";
    for $transcript ("699","703","705","709","711","713","715","717","719","723","727","731","733","735","737","739","741","743","745","747","749","751","773","777","renn","amp","GFP","pGL3_2","pGL3_3","kan")
    {
        print OUT "$transcript";
        foreach $sample (@sample_list) 
        {
            print OUT " $fpkm{$transcript}{$sample} $fpkm_low{$transcript}{$sample} $fpkm_high{$transcript}{$sample}";
        }
        print OUT "\n";
    }
    for $target (@target_list)
    {
        print OUT "$target";
        foreach $sample (@sample_list)
        {
            print OUT " $fpkm{$target}{$sample} $fpkm_low{$target}{$sample} $fpkm_high{$target}{$sample}";
        }
        print OUT "\n";
    }

    close(OUT);
}

