#!/usr/bin/perl

# write bowtie output to bed file

# perl bowtie2bed.pl s_5_trimmed.map outputfile 200
# input
# 	inputfile
#	extension

$inputfile = $ARGV[0];
$extension = $ARGV[2];
$outputfile = $ARGV[1];#$inputfile.".extended_$extension"."bp.bed";

print "input file: $inputfile\n";
print "output file: $outputfile\n";
print "track name: $outputfile\n";

open (IN,$inputfile) or die $!;
open (OUT,">$outputfile") or die $!;

print OUT "track name=$outputfile itemRgb=On\n";

while(<IN>)
{
    @flds = split/\t/;
    $flds[0] =~ s/ /-/g;#substitute space to dash

    if ($flds[1] eq "+")
    {
     print OUT join("\t",$flds[2],$flds[3],$flds[3]+$extension+length($flds[4]),$flds[0],1,$flds[1],$flds[3],$flds[3]+length($flds[4]),"255,0,0","\n");
    }
    else
    {
     
     print OUT join("\t",$flds[2],max(0,$flds[3]-$extension),$flds[3]+length($flds[4]),$flds[0],1,$flds[1],$flds[3],$flds[3]+length($flds[4]),"0,255,0","\n");
    }
}
close(IN);
close(OUT);

sub max()
{
 ($a,$b) = @_;
 return $a>$b?$a:$b;
}
