#!/usr/bin/env perl

=pod

Query id,Subject id,% identity,alignment length,mismatches,gap openings,q. start,q. end,s. start,s. end,e-value,bit score

=cut
use Data::Dumper;
use strict;
use Bio::SearchIO; 
my $in = new Bio::SearchIO(-format => 'blast', 
                           -file   => shift);

while( my $result = $in->next_result ) {
  ## $result is a Bio::Search::Result::ResultI compliant object
  while( my $hit = $result->next_hit ) {
    ## $hit is a Bio::Search::Hit::HitI compliant object
    while( my $hsp = $hit->next_hsp ) {
      ## $hsp is a Bio::Search::HSP::HSPI compliant object
	#if( $hsp->length('total') > 50 ) {
        #if ( $hsp->percent_identity >= 75 ) {
	my $homology_string = $hsp->homology_string;
	my ($mismatches) = $homology_string =~ s/[+ ]//g; 
	my $pers = sprintf "%.2f", $hsp->percent_identity;
	my $tstr = $hsp->query_string. "|". $hsp->hit_string;
#	print $hsp->query_string, "\n", $hsp->homology_string, "\n", $hsp->hit_string, "\n";
#	print $tstr, "\n";
	my ($gaps) = $tstr =~ s/-+//g || 0;
	$tstr = $hsp->hit_string;
	my ($hitgaps) = $tstr =~ s/-+//g || 0;
	$mismatches -= $hitgaps;
#	$mismatches-- if $hitgaps;
	$mismatches = $hsp->hsp_length -$hsp->num_identical;

	print join ("\t",
		    $result->query_name,    # Query id
		    $hit->name,             # Subject id
		    $pers,                  # % identity
		    $hsp->length('total'),  # length
		    $mismatches,            # mismatches
		    $gaps,                  # gap chars
		   ), "\t";

	if ($hsp->strand == 1 ) {
	    print join ("\t",
			$hsp->start('query'),   # q. start
			$hsp->end('query'),     # q. end,
		       );
	} else {
	    print join ("\t",
			$hsp->end('query'),     # q. end,
			$hsp->start('query'),   # q. start
		       );

	}
	print  "\t", join ("\t",
		    $hsp->start('hit'),     # s. start,
		    $hsp->end('hit'),       # s. end,
		    $hsp->evalue,           # e-value,
		    $hsp->bits,             # bit score
		   ), "\n";
    #}
    #}
# print Dumper $result;
#	exit;
    }  
  }
}
