#!/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 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'};
my $target_db=$args{'t'};
my $blast=$args{'b'};
my $evalue=$args{'e'};
my $mvalue=$args{'m'};
my $jobsize=$args{'j'};
my $extra=$args{'x'};
my $save=$args{'s'};

#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}/00_fasta";
$outdir ||= "/data/shared/pgn_data_processing/blast_annotations/${project}/01_unparsed_output";
$target_db ||= "/data/shared/blast/databases/current/genbank/nr";
$blast ||= "blastx";
$evalue ||= "1e-10";
$mvalue ||= "0";
$jobsize ||= "50";

my $blast_program = "parallel_blast.pl";
my $out_suffix;
if ( $target_db =~ /.*\/([-_A-Za-z0-9]+)(\.fasta)?$/ ) {
	$out_suffix = $1; 
}

#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("/data/cluster/tmp");

my $start_time=time;

# run blast against each of the fasta files in this directory
foreach my $file (@files) {
	if ( $file =~ /([_a-zA-Z0-9]+)\.fasta$/ ) {
		my $fname = $1;

		# run the blast command
		my $command = "$blast_program $indir/$file $outdir/${fname}_vs_${out_suffix}.txt $target_db $blast $evalue $mvalue $jobsize";
		$extra and $command .= " $extra";
		system($command) and die "\n\n$blast_program failed!\n";

		# clean up
		!$save and unlink "$indir/$file";
		system("rm -rf $outdir/tmp-*");
		
		# send an email to the project maintainer when each file is done 
		# being blasted
		my $mail_subject = "BLAST of ${fname} vs ${out_suffix} finished";
		my $message = "This message is to inform you that the following command has completed:\n\n\t$command\n\nEnd of Line.";
		if (open MAIL, "| /bin/mail -s \"$mail_subject\" \"$script_maintainer\"") {
			print MAIL $message;
			close MAIL;
			print "\nBlast job of $file completed- email sent to $script_maintainer\n";
		}
		else {
			print "\nBlast job of $file completed- failed to send email\n";
		}
		
	}
	else {
		if ($file ne "." && $file ne "..") {
			print "Skipping $file...\n";
		}
	}
}

runtime::runtime_print($start_time, "$project blasts");
