#!/usr/bin/perl -w
#tells the operating system where to look for Perl 

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


unless (@ARGV==1) {
    die "usage: extract_lines.pl filename";
} #checks for a filename designating a file to work on

$filename=$ARGV[0]; # store filename in the variable $filename

open(IN, "< $filename") or die "cannot open $filename: $!"; #opens the file and assigns it the handle <IN>

$outfile=$filename.".top";  #creates a name for the file to store the output

open(OUT, "> $outfile") or die "cannot open $outfile: $!";  # opens the outfile and assigns it the handle <OUT>

$old=""; #resets the variable $old to nothing.  this will store the query gi from the last line of the file

# 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\n";

while(defined($line=<IN>)){
#the loop goes through the file line by line as long as there is another line
    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{
	#if the line is not a commentline do this
	@parts=split(/\t/, $line); #splits the line into components and stores them in an array called parts
	if ($parts[0] eq $old)  
	{
	#skip line; do nothing
	#print "$old\n"; #for trouble shooting, but could also be used to count the number of matches per query
	}
	else {
	print OUT "$line"; #the GI was different from the last one, print it to the file with handle <OUT>
	$old=$parts[0]; #copy the GI number to $old
	}
    }

}

close(IN); #close file with handle <IN>
close(OUT); # close the file with handle <OUT>
exit;

