#!/usr/bin/perl

###############################################
# parse blast file to get query and hit
#########################################################

########################## Body of Code ######################################
# the number of argument must be 2.

if ($#ARGV != 1)
{
	print "usage: BlastParsr.pl  BlastOutputFile Result_output\n\n";
	exit;
}

########### Parameters #########
$hit = 0;#false
$expect = 0; # expect value
#########################################

$BlastOutputFile = $ARGV[0];
$outFile = $ARGV[1];

#############

print "In progress ...\n";
$midLine = 0; #the line below the "Query:" to show identity and similarity
###################################################

$coverage = "";
open (BLASTOUTPUTFILE, $BlastOutputFile) || die ("Cannot open file
$BlastOutputFile\n\n");
@BlastContent = <BLASTOUTPUTFILE>;
close (BLASTOUTPUTFILE);

$hitCount = 0;
$result = "";

foreach $BlastContent (@BlastContent)
{#foreachloop #1
	chomp ($BlastContent);
	@array1 = split (" ", $BlastContent);
	if ($array1[0] eq   "Query=")
	{
		$query = $array1[1];
		#@tQ = split(/ /, $query);
		#$query = $tQ[1];
    }
	if ($BlastContent =~ /No hits found/)
	{
        $noHitCount++;
		$hit = 0;
        push (@outA2, $query."\t"."No hits found"."\n");
		next;
	}
    elsif ($BlastContent =~ /^Sequences/)
	{
		$hit = 1; # there is a hit at least
    }

    elsif ($BlastContent =~ /^>/)  
    {
	    $posT = index ($BlastContent, " ");
	    $proteinName = substr ($BlastContent, $posT+1);
		@pA = split (/OS=/, $proteinName);
		$fun = $pA[0];
		@tA = split(/\|/, $array1[0]);
		$spID = $tA[1];
	}
    else
    { # else - OUT1
	   if ($hit ==1)
	   {# if $hit true)
		#added to count the e-values
            #  print $BlastContent."\n";
	     if ($BlastContent =~ /Score/ && $BlastContent =~ /Expect/)
		 {
				@expectLine = split (/,/, $BlastContent);
				$scoreString = $expectLine[0];
				@sArray = split (/\s+/, $scoreString);
				$score = $sArray[3];
				$eString = $expectLine[1];
				@subString = split (/ /, $eString);
				$expect = $subString[3];
				#print "E-value".$expect."\t";
				push (@outA, $query."\t".$spID."\t".$expect."\t".$fun."\n");
				$hit = 0;
        }
	  }
	}	
}# out-1

open (OUTPUT, ">$outFile");
print OUTPUT (@outA);
close OUTPUT;
$oF2 = "nohit.id";
open (OUTPUT, ">$oF2");
print OUTPUT (@outA2);


print "Job is done.\n";
exit;


