#!/usr/bin/perl -w

#analyze BLASTALL output ran with -m8 or -m9 option to extract only 1st line for each query GI
#Sun 12 Dec 2004 mod 1/28/08
# adds another column to the output file

unless (@ARGV==1) {
    die "usage: extract_lines.pl filename";
}

$filename=$ARGV[0];

open(IN, "< $filename") or die "cannot open $filename: $!";

$outfile=$filename.".top";

open(OUT, "> $outfile") or die "cannot open $outfile: $!";

$old="";
# print header
print OUT "#Query id \tSubject id \t% identity \talignment length \tnumber of mismatches \tnumber of gap openings \tposition of query start \tposition of query end \tposition of subject start \tposition of subject end \te-value of a hit \tbit score of a hit \tbit score per aligned  position\n";
#
#added bitscore/aligned position
#
while(defined($line=<IN>)){

    if($line=~"#"){
	#skip the line, since it is a comment line
	#copy line to OUT
	#print OUT "$line";
	#if you want to keep comment lines un comment the last line
    }
    else{
    	chomp ($line);#the lines normally end with a new line symbol. chomp removes it from the end of the line
    	#this makes sure that the last $part[n] does not include a \n at the end
	@parts=split(/\t/, $line);
	if ($parts[0] eq $old)
	{
	#skip line;
	#print "$old\n";
	}
	else {
#next line calculates bitscore divided by alignment length;
	$ratio=$parts[11]/$parts[3];
#add $ratio to printout	
	print OUT "$line\t$ratio\n";#adds a new line symbol to the end of the line
	$old=$parts[0];
	}
    }

}

close(IN);
close(OUT);
exit;

