#!/usr/bin/perl
##############################################################################
#  This script is used to process the output of bowtie alignment and genrate #
#  a file containing each mappable read and its related TE 	 	     #
#									     #
#  Usage:                                                        	     #
#    bowtie bowtie.index input.fastq | perl processBowtieAlignment.pl output #
##############################################################################

use warnings;
use strict;

my $usage = "perl $0 <output>";
die $usage unless @ARGV;

my @flag;
my $id;
my $name = shift@ARGV;
my $out_f = $name.".readcount";
my $seen;
my $mq;
my $mismatch;

open (OUT, ">$out_f") || die "Couldn't open $out_f\n" ;
while (my $line = <STDIN>)
{
	chomp $line;
   	my @tmp = split/\s+/, $line;
   	@flag = split/\./, $tmp[2];

	my $misinfo = $tmp[7];
	if(defined($misinfo))
	{
		$mismatch = $misinfo =~ tr/://;
	}
	else
	{
		$mismatch = 0;
	}

	$mq = join"+",$flag[3],$mismatch;
	$id = $tmp[0];
	if(($tmp[3]/$flag[1] > 0.8) && (($tmp[3]+$flag[1]-$flag[2])/$flag[1] < 0.2) || ($tmp[3] <= $flag[1] && $tmp[3]+$flag[1] >=$flag[2]))
	{
        	$seen->{$id}->{$mq}=1;
	}
}
	

foreach my $item (keys %$seen){
   my @out;
   push @out,$item;
   foreach my $key (keys %{$seen->{$item}}){
             push @out, $key;
   }
   my $line=join "\t",@out;
   print OUT  "$line\n";
}
