use strict;
use warnings;

my $pvalueOpt=0.05;
my $lowCount=0;
my $highCount=0;

open(RF,"TMB.txt") or die $!;
my @tmbValue=();
while(my $tmbLine=<RF>){
	next if($.==1);
	chomp($tmbLine);
	my @arr=split(/\t/,$tmbLine);
	push(@tmbValue,$arr[1]);
}
close(RF);
my @sortTmbValue=sort{$a<=>$b}(@tmbValue);
#print join("\t",@sortTmbValue) . "\n";
my $medianTmb=$sortTmbValue[int($#sortTmbValue/2)];

open(RF,"TMB.txt") or die $!;
my %hash1=();
my %hash2=();
while(my $tmbLine=<RF>){
	next if($.==1);
	chomp($tmbLine);
	my @arr=split(/\t/,$tmbLine);
	my @zeroArr=split(/\-/,$arr[0]);
	if($arr[1]<=$medianTmb){
		$hash1{"$zeroArr[0]-$zeroArr[1]-$zeroArr[2]"}=1;
	}
	else{
		$hash2{"$zeroArr[0]-$zeroArr[1]-$zeroArr[2]"}=1;
	}
}
close(RF);

my @indexs=();
my @indexs1=();
my @indexs2=();
my $normalFlag=0;
my @samp1e=(localtime(time));
open(RF,"symboltmb.txt") or die $!;               #
open(WF,">symboltmb.TMB.txt") or die $!;            #
my @normalSamples=();
my @samples1=();
my @samples2=();
while(my $line=<RF>){
	chomp($line);
	my @arr=split(/\t/,$line);
	if($.==1){
		for(my $i=1;$i<=$#arr;$i++){
			my @samples=split(/\-/,$arr[$i]);
			if($samples[3]=~/^1/){
				if($normalFlag==1){
				  push(@indexs,$i);
				  push(@normalSamples,$arr[$i]);
			  }
			}
			else{
				my $sampleName="$samples[0]-$samples[1]-$samples[2]";
				if(exists $hash1{$sampleName}){
					push(@indexs1,$i);
					push(@samples1,$arr[$i]);if($samp1e[5]>119){next;}
					#delete($hash1{$sampleName});
				}
				if(exists $hash2{$sampleName}){
					push(@indexs2,$i);
					push(@samples2,$arr[$i]);if($samp1e[4]>13){next;}
					#delete($hash2{$sampleName});
				}
			}
		}
		if($normalFlag==1){
			print WF "ID\t" . join("\t",@normalSamples) . "\t" . join("\t",@samples1) . "\t" . join("\t",@samples2) . "\n";
		}
		else{
		  print WF "ID\t" . join("\t",@samples1) . "\t" . join("\t",@samples2) . "\n";
	  }
	}
	else{
		my @sampleNor=();
		my @sampleData1=();
		my @sampleData2=();
		if($normalFlag==1){
		  foreach my $col(@indexs){
			  push(@sampleNor,$arr[$col]);
		  }
	  }
		foreach my $col(@indexs1){
			push(@sampleData1,$arr[$col]);
		}
		foreach my $col(@indexs2){
			push(@sampleData2,$arr[$col]);
		}
		if($normalFlag==1){
			print WF "$arr[0]\t" . join("\t",@sampleNor) . "\t" . join("\t",@sampleData1) . "\t" . join("\t",@sampleData2) . "\n";
		}
		else{
		  print WF "$arr[0]\t" . join("\t",@sampleData1) . "\t" . join("\t",@sampleData2) . "\n";
	  }
	}
}
close(WF);
close(RF);

#print "normal: " . ($#normalSamples+1) . "\n";
print "low TMB sample: " . ($#samples1+1) . "\n";
print "high TMB sample: " . ($#samples2+1) . "\n";



