#!/usr/bin/perl -w 


$firstn=1;
$minreadsum = 10;
$minspliceraw = 0;

@dirs = qw(
hs1B
hs1D
);

$ndirs = scalar(@dirs);

for($i=0;$i<$ndirs;$i++){
$d = $dirs[$i];

system("ls $d/*_splicingValues.txt > filelist");

open(IF,"filelist");

while($a=<IF>){
chomp($a);
$tgene = $a;
$tgene =~ s/$d\///;
$tgene =~ s/_splicingValues.txt//;

$tn=0;

$maxsplice{$d}{$tgene} = 0;
$maxsplicepos{$d}{$tgene} = 0;
$halfmaxpos{$d}{$tgene} = -1000;

#get first and max
open(SV,"$a");
$b=<SV>;
while($b = <SV>){
chomp($b);
#relPos	readSum	splicingValueRaw	splicingValueNorm
#-100	6	0	0
($relpos,$readsum,$spliceraw,$splicenorm) = split(/\t/,$b);
if($relpos > 0 && $readsum > $minreadsum && $spliceraw > $minspliceraw){
if($splicenorm>$maxsplice{$d}{$tgene}){
$maxsplice{$d}{$tgene} = $spliceraw;
$maxsplicepos{$d}{$tgene} = $relpos;
}
if($tn<$firstn){  $firstpos{$d}{$tgene} .= "$relpos"; if($firstn>1){$firstpos{$d}{$tgene} .= ";";}}
$tn++;
$genes{$tgene}++;
}
}
close(SV);

#get halfmaxpos
open(SV,"$a");
$b=<SV>;
while($b = <SV>){
chomp($b);
#relPos	readSum	splicingValueRaw	splicingValueNorm
#-100	6	0	0
($relpos,$readsum,$spliceraw,$splicenorm) = split(/\t/,$b);
if($relpos > 0 && $readsum > $minreadsum && $spliceraw > $minspliceraw){
if($spliceraw>($maxsplice{$d}{$tgene}/2) && $halfmaxpos{$d}{$tgene} == -1000){
$halfmaxpos{$d}{$tgene} = $relpos;
}
}
}
close(SV);


#if(exists $firstpos{$d}{$tgene}){ print "$d $tgene \tfirst $firstpos{$d}{$tgene}\tmaxsplipos $maxsplicepos{$d}{$tgene}\tmaxspli $maxsplice{$d}{$tgene}\thmpos $halfmaxpos{$d}{$tgene} \n"; exit;}


}
}


print "gene";
for($i=0;$i<$ndirs;$i++){$d = $dirs[$i];print "\tfirstpos.$d\tmaxpos.$d\tmaxvalue.$d\thalfmaxpos.$d";}
print "\n";

foreach $gene (sort keys %genes){
print "$gene";
for($i=0;$i<$ndirs;$i++){
$d = $dirs[$i];
if(exists $firstpos{$d}{$gene}){ print "\t$firstpos{$d}{$gene}\t$maxsplicepos{$d}{$gene}\t$maxsplice{$d}{$gene}\t$halfmaxpos{$d}{$gene}";}
else{print "\tNA\tNA\tNA\tNA";}
}
print "\n";
}


