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

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

# given an input directory and a file format, parses out files submitted to 
# PGN into a format that can be used by our pipeline

use Zerg::Report;
use runtime;

# process arguments
@ARGV or print "No input parameters, proceeding with default.\n";
my @arg_pairs = split (/\-/, (join ' ', @ARGV));
my %args=();
foreach (@arg_pairs){
    $_ or next;
    my ($flag, $val)=split /\s+/;
    $args{$flag}=$val;
}

my $project=$args{'p'};
my $indir=$args{'i'};
my $outdir=$args{'o'};

#set defaults for io, script filename, etc
$project or die "You must specify the project (fgn, cgn or pgn) with the -p flag\n";
$indir ||= "/data/shared/pgn_data_processing/blast_annotations/${project}/01_unparsed_output";
$outdir ||= "/data/shared/pgn_data_processing/blast_annotations/${project}/02_parsed_output";

#main bmtdy of script
#####################

# get the list of files in $indir
opendir(FOLDER, $indir) or die "Cannot open ${indir}: $!\n";
my @files=readdir(FOLDER);
closedir(FOLDER);

chdir("$outdir");

my $start_time=time;

# run blast against each of the fasta files in this directory
foreach my $file (@files) {
	if ( $file =~ /^((unigene_build_)?[-a-zA-Z0-9]+)_vs_([-_A-Za-z0-9]+)\.txt$/ ) {
		my $build = $1;
		my $target = $3;

		# do all the work in parsing file
		my $outfile = "${build}_vs_${target}.txt";
		open(OUT, "> $outdir/$outfile") or die "Couldn't open $outdir/${outfile}: $!\n";
#		open(my $raw, "< $indir/$file") or die "Couldn't open $indir/${file}: $!\n";
# 		my $multiple_report = new BPlite::Multi($raw);
# 		while(my $blast = $multiple_report->nextReport) {
# 			# print "$blast...\n";
# 			while(my $sbjct = $blast->nextSbjct) {
# 				while(my $hsp = $sbjct->nextHSP){
# 					print OUT "$blast\t$sbjct\t$hsp\n";
# 				}
# 			}
# 		}
#		close($raw);
		my $zerg_report = new Zerg::Report("$indir/$file") or die "Couldn't open $indir/$file: $!\n";;
		while(my $r=$zerg_report->getReport()) {
			foreach my $hit (@{$r->{hits}}) {
				foreach my $hsp (@{$hit->{hsps}}){
					# report
					print OUT "$r->{query_name} ($r->{query_length} letters)\t";
					# subject
					print OUT ">$hit->{subject_name} $hit->{subject_annotation}\t";
					# evalue
					print OUT "E-value: $hsp->{evalue}\t";
					# score
					print OUT "Score: $hsp->{score}\t";
					# %identities
					print OUT "%Identities: $hsp->{percent_identities}\t";
					# sbjct
					print OUT "Sbjct:: $hsp->{subject_start}..$hsp->{subject_end}";
					print OUT "\n";
				}
			}
		}
		$zerg_report->closeFile();
		close(OUT);
		
		# remove original file
		unlink "$indir/$file";
		
		# report completion to the maintainer
		my $mail_subject = "Parsing of $file completed";
		my $message = "This message is to inform you that parsing the blast output of $project build $build has completed, and that the results are available here:\n\t$outdir/$outfile\n\nEnd of Line.";
		if (open MAIL, "| /bin/mail -s \"$mail_subject\" \"$script_maintainer\"") {
			print MAIL $message;
			close MAIL;
			print "\nParsing of $file completed- email sent to $script_maintainer\n";
		}
		else {
			print "\nParsing of $file completed- failed to send email\n";
		}
		
	}
	else {
		if ($file ne "." && $file ne "..") {
			print "Skipping $file...\n";
		}
	}
}

runtime::runtime_print($start_time, "$project blast parser");
