#!/usr/bin/perl -w

######################################GENERATE FASTA COUNT FILE####################################################
#####Annotate the BLATOUT with lenghts, hitlenghts, strand orientation                                        #####
###################################################################################################################

print "GENERATE FILTERED EXTENDED BLATOUT...\n";

open(DATEI, "< Grouped_Blat_Clustered/Buffer_Files/filtered.blatout"); 		# filtered .blatout file
open(DATEI2, ">> Grouped_Blat_Clustered/Buffer_Files/filtered_extended.blatout");
$fastafile = "Grouped_Blat_Clustered/Buffer_Files/fasta_complete_count.txt";	# count file of complete fastas

my $gene="undefined";
my $org="undefined";
my $found=0;
my $protlength=0;
my $querylength=0;
my $row="undefined";
my $percent=0;
my $orientation="undefined";
my $lastgene="undefined";
my $lastlength=0;
my $choppedseq="undefined";
my $line;
chomp(my $numlines=`wc -l < Grouped_Blat_Clustered/Buffer_Files/filtered.blatout`);
my $cnt=0;
my $rel=0;

while(<DATEI>)
{

	my @columns = split(" ", $_);
	$gene=$columns[0];
	$row=$_;
	chop($row);
	$querylength = $columns[7]-$columns[6];

	if(($columns[9]-$columns[8])>=0)
	{
		$orientation="+";
	}
	else
	{
		$orientation="-";
	}

	$protlength=0;

	if($gene!~$lastgene)
	{
		$line=`grep '$gene' $fastafile`;
		if($line =~ />\S*\s(\S*)\n/)
		{
			$protlength=$1;
		}
		chomp($protlength);
	}
	else
	{
		$protlength=$lastlength;
	}
				
	if($protlength>0)
	{
			$percent=int($querylength/$protlength)*100); #percent of the hit that covers the CDS
	}
				
	print DATEI2 $row."\t$protlength\t$percent\t$orientation\n";
			
	$lastgene=$gene;
	$lastlength=$protlength;

	$cnt++;
}


close(DATEI2);
close(DATEI);