use strict;
$|=1;

my $L = 200;
my $location = "Input/sgr_files/Input";

for (my $i=1; $i<=25; $i++) {

    my $infile  = "";
    my $outfile = "";
    my $chr     = "";

    if ($i <= 22) {
	$infile  = $location."_eland_result.chr".$i.".txt";
	$outfile = $location.".chr".$i.".sgr";
	$chr = "chr".$i;
    }
    elsif ($i == 23) {
	$infile  = $location."_eland_result.chrX.txt";
	$outfile = $location.".chrX.sgr";
	$chr = "chrX"
    }
    elsif ($i == 24) {
	$infile  = $location."_eland_result.chrY.txt";
	$outfile = $location.".chrY.sgr";
	$chr = "chrY"
    }
    elsif ($i == 25) {
	$infile  = $location."_eland_result.chrM.txt";
	$outfile = $location.".chrM.sgr";
	$chr = "chrM"
    }

    open IN, "$infile";
    open OUT, ">$outfile";

    my %data = ();
    
    while (<IN>) {
	chomp;
	
	my ($t1, $seq, $map, $t3, $t4, $t5, $chrt, $pos, $str, @rest) = split /\t/, $_;
	my $read_length = length $seq;  
	
	if ($str eq "F") {
		$data{$pos} += 1;
		$data{$pos+$L} += -1;
	}
	elsif ($str eq "R") {
		my $start = $pos + $read_length - $L;
		$start = 1 if ($start < 1);
		my $stop  = $pos + $read_length;
		$data{$start} += 1;
		$data{$stop}  += -1;
	}
	else {
		print "PROBLEM\n";
	}
    }
    
    close IN;
    
	
    my @sorted_pos = sort {$a <=> $b} (keys %data);
    my $height = 0;
	
    foreach my $pos (@sorted_pos) {
	$height += $data{$pos};
	print OUT "$chr\t$pos\t$height\n";
    }
    
    close OUT;
    print "chr$i\n";
    
}
