#!/usr/bin/perl -w
# There must be a directory named ballgown which included all samples you want to combine
# usage: perl this.perl [FPKM|TPM]
# !!!! some gene has problem as there could be some lines has the same GENE ID ,which need to be polished
# if you want to give the sample list particularly, just the sample.list file
$index=$ARGV[0];
$num{"FPKM"}=7;
$num{"TPM"}=8;
system "ls ballgown >sample.txt";
open SAM, "<sample.txt" or die "Cannot open sample.txt $!\n";
while(<SAM>){
  chomp;
  $file=$_;
  push @sam,$file;
 # print STDERR "$file\n";
  open LIST, "ballgown/$file/$file.txt" or die "Cannot open ballgown/$file/$file.txt";
  while(<LIST>){
    chomp;
    if(/^Gene/){}
    else{
    @array = split /\t/,$_;
    $gene=$array[0];
    $Name{$gene}=1;
    $lable=$file."?".$gene;
    $exp{$lable} = $array[$num{$index}];
  #  print STDERR "$num{$index}:$lable:$array[$num{$index}]:$exp{$lable}\n";
    }
   }
  }
 # print STDERR "@sam";
 open OUT ,">>Merge_${index}.txt" or die "Cannot open Merge_${index}.txt";
 print OUT "GeneID";
 for($sample=0;$sample<=$#sam;$sample++){
  print OUT "\t$sam[$sample]";
  }
 print OUT "\n";

 foreach $gene (keys(%Name)){
    print OUT "$gene";
    for($sample=0;$sample<=$#sam;$sample++){
      $lable=$sam[$sample]."?".$gene;
   #   print STDERR "$lable";
      print OUT "\t$exp{$lable}";
      }
    print OUT "\n";
  }
system "rm -f sample.txt";