#!/usr/bin/perl 
########################################################################
#  This script is used to count the mapped reads for each TE, and the  #
#  input data comes from the output of processBowtieAlignment.pl       #
#  Usage:							       #
#	perl countAlignmetReadsforeachTE.pl <sample.readcount>         #
########################################################################

use strict;
use warnings;

my $usage = "perl $0 <sample.readcount>";
die $usage unless @ARGV;

my $in_f = shift@ARGV;
my $out_f=$in_f.".out";

open (IN, $in_f) || die "Couldn't open input file $in_f\n";
open (OUT, ">$out_f") || die "Couldn't open output file $out_f\n";


# for each mappable reads, select the minimal mismatch TE location
while(<IN>)
{
	chomp;
	my @tmp = split/\s+/;
	my $id = shift@tmp;
	print OUT "$id";
	my %see;
	my @out=();
	my %cnt1;
	my $minnum1;
	my $minn;
	my %cnt = %cnt1;
	my $minnum =$minnum1;
	foreach my $item(@tmp)
	{
		my @stat = split/\+/, $item;
		push @{$see{$stat[0]}}, $stat[1];
		push @out, $stat[1];
	}
	foreach my $key1 (keys%see)
	{
		$minn = &min(@{$see{$key1}});
		$cnt{$key1} = $minn;
	}
	$minnum = &min(@out);
	foreach my $key (keys%cnt)
	{
		if($cnt{$key} == $minnum)
		{
			print OUT "\t$key";
		}
	}
	print OUT "\n";

}
close IN;
close OUT;

my %rp;
my $totalReads = 0;
my $name;
my $out_f2 = $in_f.".fam."."readcount";
my $report = $out_f2.".report";

open(FILE, $out_f) || die "Couldn't open $out_f\n";
open(OUT2, "> $out_f2") ||die "Couldn't open $out_f2\t";
open (REPORT, "> $report") || die "Couldn't open $report\t";

while (<FILE>)
{
        chomp;
        my @tm = split/\s+/;
        my $len = $#tm;
        for(my $j=1; $j <=$len; $j++)
        {
                $name = $tm[$j];
                $rp{$name} += 1/$len;		#split the reads to each TE equally
        }
                $totalReads ++;
}

print REPORT "$totalReads\n";

foreach my $key (sort keys%rp)
{
        print OUT2 "$key\t$rp{$key}\n";
}

close FILE;
close OUT2;
close REPORT;

##################################################

sub min{
 my ($min_so_far) = shift@_;
 foreach(@_) 
 {
	if($_ < $min_so_far )
	{
		$min_so_far = $_;
	}
 }
 $min_so_far;
}
