#!/usr/bin/perl -w
# parse tab-delimited output from BLASTing the fasta file produced by MakePseudogenes.pl

use strict;
use lib "../Perl/modules";
use Getopt::Long;
use Gene;
use Genome;
use GeneMethods;
use GenomicsUtils;

{
    my $usage = "ParsePseudogenes.pl [-host=host] < blastTab > scores\n".
	"ParsePseudogenes.pl reports best BLAST hits to an LocusSeq database\n";
    
    my $minLength = 0;
    my $host = undef;
    my $debug = 0;
    (GetOptions('minLength=i' => \$minLength,
		'host=s' => \$host,
		'debug=i' => \$debug)
     && @ARGV ==0) || die $usage;
    GenomicsUtils::setDebug($debug) if $debug > 0;
    connect($host);

    my %qToBest = ();
    print join("\t","Genome","Scaffold","Gene1","Gene2","Sep","Code",
	       "Hit","HitLen","HitGenome","HitScaffold",
	       "Identity","Evalue","Score",
	       "qBegin","qEnd","sBegin","sEnd","Mismatch","Gap","Extent"),"\n";
    while(<>) {
	chomp;
	my ($query, $subject, $ident, $alignLength, $mismatch, $gap, $qBegin, $qEnd, $sBegin, $sEnd, $evalue, $score) =
	    split /\t/, $_;
	if (!exists $qToBest{$query}) {
	    my $hit = Gene::new('locusId',$subject);
	    $qToBest{$query} = $subject;
	    my ($qTaxon,$qScaffold,$Gene1,$Gene2,$Sep,$Code,$qLen) = split /:/, $query;
	    print join("\t",$qTaxon,$qScaffold,$Gene1,$Gene2,$Sep,$Code,
		       $subject, $hit->end()-$hit->begin(), $hit->taxonomyId(), $hit->scaffoldId(),
		       $ident, $evalue, $score, $qBegin, $qEnd, $sBegin, $sEnd, $mismatch, $gap, $qEnd-$qBegin), "\n";
	}
    }
}

