$|=1; # So it works in the IDE
use autodie; # checks file opening for us...

# lets get the transcript -> gene info first
open FILEIN, "< t_to_g.txt";

while(defined($line=<FILEIN>)){ # loop over file line by line
  chomp $line; # get rid of the nasty \n
  ($tr,$gn) = split /\t/,$line; # split the fields into an array,
  $transtogene{$tr} = $gn; # create a hash %transtogene with the key being the FBtr and the value the FBgn it belongs to
}
close FILEIN;  # we are done with this file, so close it

# now lets open the transcript counts
open FILEIN, "< tcount.txt";

while(defined($line=<FILEIN>)){ # loop over file line by line
  chomp $line; # get rid of the nasty \n
  ($FBtr,$count) = split /\t/,$line; # split the fields into an array, use some intuitiv names
  $gene = $transtogene{$FBtr}; # the info which FBgn belongs to which FBtr is stored in our %transtogene hash
  $genecount{$gene} += $count; # Add the count of the current FBtr to the hash element (in a new %genecount hash) with its corresponding FBgn
}
close FILEIN;   # we are done with this file, so close it

# now lets open the output
open FILEOUT, "> gcount.txt";
@k = sort keys %genecount; # get all keys from the hash, sort them nicely
foreach $e (@k){ # loop over the keys (the FBgn numbers) and print them along with their values
  print FILEOUT "$e\t$genecount{$e}\n";
}
close FILEOUT; # and done!
