#!/usr/bin/perl
#####################################################################
#  This script is used to calculate the reads density for each TE,  #
#  which is mapped reads for each TE divided by total mapped reads  #
#  Usage:							    #
#	perl calculateReadDensity.pl <sample.fam.readcount> 	    #
#####################################################################

use warnings;
use strict;

my $usage = "perl $0 <sample.fam.readcount ";

die $usage unless @ARGV;

my $in_f = shift@ARGV;
my $report = $in_f.".report";
my $out_f = $in_f;
$out_f =~ s/fam.readcount/normalized.rp/g;

#Get the number of total mappled reads
open(SIZE, $report) || die"Couldn't open $report\n";
my $size = <SIZE>;
chomp $size;
close SIZE;

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

while (<IN>)
{
	chomp;
	my @tmp = split/\s+/;
	my $normalizedreads =  $tmp[1]/$size;
	print OUT "$tmp[0]\t$tmp[1]\t$normalizedreads\n";
}
close IN;
close OUT;
