#! /usr/local/bin/perl

#############################################################
# &BLAST($file1,$file2)
#
# [1] Find the overlap using blastn plus MSPcrunch
# [2] Relies on more software that &CROSS_MATCH()
#     
#############################################################
sub BLAST {	   
    local($file1,$file2) = @_;
    local(@results) = ();
    local(%lengths);

    warn "Using blastn\n" if $debug;

    local($tempfile) = "_$prog.blast";

    # Get sequence lengths (unobtainable in MSPcrunch)
    %lengths = ( &fastaSeqCount($file1) ,&fastaSeqCount($file2));

    # Create blast database
    system("pressdb $file1 > /dev/null");
    die "$prog: pressdb returned error code $?\n" if ($? != 0);

    # run blastn - capture results in file
    system("blastdb blastn $file1 $file2 > $tempfile.bl");
    die "$prog: blastdb blastn returned error code $?\n" if ($? != 0);

    # MSPcrunch -d
    system ("MSPcrunch -d $tempfile.bl > $tempfile.blx");
    die "$prog: MSPcrunch returned error code $?\n" if ($? != 0);

    # parse
    open(OUT,"$tempfile.blx") || die "$prog: could not open blast output file: $tempfile.blx\n";
    while(<OUT>) {

	print $_ if $debug;

	# MSPcrunch -d parsing

	( $score, $identity, $a1, $a2, $a, $b1, $b2, $b, @d ) = split;
	push(@results,[$a,$a1,$a2,$lengths{$a},$b,$b1,$b2,$lengths{$b},$score]);
	
    }
    close(OUT);

    unlink("$tempfile.bl");
    unlink("$tempfile.blx");
    unlink("$file1.csq");
    unlink("$file1.nhd");
    unlink("$file1.ntb");


    return \@results;
}


1;