#!/usr/bin/perl -w
use strict;

#person in charge of this script
#this is usually the person currently in charge of scripts for the SGN project
my $script_maintainer='Teri Solow <tms45@cornell.edu>';

#local folders with custom packages
use lib '/data/shared/pgn_data_processing/scripts/perllib/';

#local packages to use
use runtime;


my %args=();
my $i=0;
while($i<@ARGV){
    my $j=$i+1;
    $args{$ARGV[$i]}=$ARGV[$j];
    $i+=2;
}


my $blast_file = $args{-i};
$blast_file or print "Error: no input file given.\n" and exit;
my $cleanresults_file=$blast_file.'.detail_clean';

my $start_time=time;

print "Cleaning up the blast results file $blast_file.\nWriting clean results to $cleanresults_file.\n";

open (FILEIN, "$blast_file");
open (FILEOUT, ">$cleanresults_file");


my $good_lines='false';
my $line;
my $query='';
while ($line = <FILEIN>){

    if($line=~/Query=/){
	$query=$line;
    }
    if ($line=~/^\s*Sequences producing significant alignments:/){
	$good_lines='true';
	print FILEOUT "\n" . '-'x80 . "\n$query";
	next;
    }

    if ($line=~/^>/){
	$good_lines='true';
    }

    if ($line=~/^\s*Database:\s+/){
	$good_lines='false';
    }

#    if ($line=~/No hits/){
#	print FILEOUT "$line\n";
#	$good_lines='false';
#    }

    unless ($good_lines eq 'false'){
	print FILEOUT "$line";
    }
}

close (FILEOUT);
close (FILEIN);

print "Done.\n";
runtime::runtime_print($start_time, 'Blast cleanup');
