#!/usr/bin/perl

# usage: perl ../../scripts/RUV2table.pl Human_RUV-normalized_countings-k3_uniquely_only_reads_30_libs_WT_Mutant_02_h-24_h.csv

use strict;
use warnings;
use Data::Dumper;

my $fhs_string = shift;
my @fhs = split":",$fhs_string;

my %data = ();
my %type = ();

my %timepoints = ();
my %samples    = ();

foreach my $fh (sort @fhs){
  my $timestamp = 'xx_h';
  if($fh =~ m/(\d\d_h)_k\d/){
    $timestamp = $1;
  }

  $timepoints{$timestamp}++;
  
  open I, "< ${fh}" or die "can t open ${fh}\n";
  my @header = ();
  while(<I>){
    chomp;
    my @F=split"\t",$_;
    
    if($.==1){
      @header = @F;
      foreach my $head (@header){
	$samples{$head}++;
      }
      next;
    }
    else{
      my $descriptor = shift(@F);
      my $id   = &parseID($descriptor);
      my $type = &parseTYPE($descriptor);

      foreach my $c (0 .. $#F){
	$data{$id}->{$timestamp}->{$header[$c]}=$F[$c];
	$type{$id} = $type;
      }
    }
    
  }
  $.=0;
}

my @outheader = ();
foreach my $time (sort keys %timepoints){
  foreach my $sample (sort keys %samples){
    push @outheader, $sample;
  }
}
printf "id\ttype\t%s\n", join("\t", @outheader);

my $found    = 0;
my $notfound = 0;

foreach my $id (sort keys %data){
  my @outdata = ();
  push @outdata, $id;
  push @outdata, $type{$id};
  foreach my $time (sort keys %timepoints){
    foreach my $sample (sort keys %samples){
      if ( defined($data{$id}->{$time}->{$sample}) ){
	push @outdata, $data{$id}->{$time}->{$sample};
	$found++;
      }
      else{
	push @outdata, 0;
	$notfound++;
      }
    }
  }
  print  join("\t", @outdata)."\n";;
}

printf STDERR "Total data points:\t%d\nProvided data points:\t%d\nSupplemented data:\t%d\nSupplementing ratio:\t%.3f\n", $found+$notfound, $found, $notfound, $notfound/($found+$notfound);
      

####
sub parseID{
  my $string = shift;
  
  if($string=~m/gene_id=(\w+\d+\.?\d*);/){
    return($1);
  }
  elsif($string=~m/Name=(\w+\d+)\.?\d*;/){
    return($1);
  }
  elsif($string=~m/ID=(\w+\d+);/){
    return($1);
  }
  elsif($string=~m/sRNA/){
    my $id = (split(/\|/,$string))[1];
    return($id);
  }
  else{
    print STDERR "NO ID FOR:\t$string in parse subroutine\n";
    return($string);
  }
  
}

sub parseTYPE{
  my $string = shift;
  my $type   = '';

  if($string=~m/gene_type=(\w+);/){
    $type = $1;
  }
  elsif($string=~m/;type=(\w+)/){
    $type = $1;
  }
  elsif($string=~m/ID=MI(MAT)?\d+_?\d*;/){
    $type = "miRNA";
  }
  elsif($string=~m/protein_id=/){
   $type = "mRNA";
  }
  elsif($string=~m/sRNA/){
   $type = "sRNA";
  }
  else{
    print STDERR "NO TYPE FOR:\t$string\n";
    $type = $string;
  }
  
  # clean sources
  $type = "lincRNA" if ($type eq 'Linc');
  $type = "IMGT" if ($type =~ /^IG_/ || $type =~ /^TR_/);
  $type = "antisense" if ($type eq 'Antisense');

  return($type);
}
