#!/usr/bin/perl -w
# Bruno Contreras-Moreira, Pablo Vinuesa
# 2007 UNAM, Mexico

use strict;
use Getopt::Std;
use lib "lib";
use phyTools;

set_phyTools_env();

my $progname = $0; #run_Fasta4phylogenomics.pl
my $VERSION  = 0.3; # Oct 2015: BCM added -a 

my $DUMMYCUTOFF = '0';
my $SLEEPTIME = 0;

########################################################################

my $EXECUTABLE  = "Fasta4phylogenomics.pl";
my $qsubEXE = "/opt/sge/bin/linux-x64/qsub ";

########################################################################



my (%opts,$DNADIR,$PROTDIR,$PBSoutDIR,$PBSworkDIR,$filename,$dnafile,$protfile,$params,$queue_name,);
my ($use_marfil_prot,$fasta4phylo,$runmode,$bootstrap,$branchLRT,$only_align)=(0);
my $codehopT = $ENV{'DEF_CODEHOP_T'};

getopts('hkauMBsd:p:e:m:w:U:q:', \%opts);

if(($opts{'h'})||(scalar(keys(%opts))==0)) 
{ 
	print "usage: $progname [options]\n";
	print "-h \t this message\n";
	print "-d \t full path to FASTA DNA directory containing *.fna files\n";
	print "-p \t full path to FASTA protein directory containing *.faa files\n";
	print "-e \t file containing a list of sequences to exclude; by default will read /CVS_code/marfil/exclist  (optional)\n";
	print "-u \t use only unique sequences                                                                      (optional)\n";
	print "-M \t use marfil_prot.pl for phylogenetical evaluation                                               (optional, default marfil_amps.pl)\n";
	print "-B \t calculate WAG bootstrap support for alignment topologies                                       (optional)\n";
	print "-U \t use substitution model provided by user, skips[Prot|Model]Test                                 (optional,choose appropriate AA|DNA model [WAGG|GTRG|...])\n";
	print "-s \t skip protein alignments as input sequences are already aligned                                 (optional)\n";
   print "-a \t only align sequences                                                                           (optional)\n";
	print "-k \t keep all temporary files                                                                       (optional)\n";
	print "-w \t full path to work directory\n";
        print "-q \t provide a queue name to run the jobs on [rapidos|medios|lentos                                 (default apps64, optional)\n";
	print "-m \t run mode [local|pbs]    (default local, optional)\n\n";
	
	print "NOTE: Parse the output using parse_Fasta4phylo_output.pl -d ./ > F4P_out.parsed\n\n"; 
	exit; 
}

$params = '';

if(defined($opts{'p'})){ $PROTDIR = $opts{'p'}; }
else{ die "# $0 : need a protein directory with .faa files\n" }
if(defined($opts{'e'})){ $params .= "-e $opts{'e'} ";}
if(defined($opts{'u'})){ $params .= "-u "; }
if(defined($opts{'k'})){ $params .= "-k  "; }
if(defined($opts{'M'})){ $params .= "-M "; $use_marfil_prot = 1; }
if(defined($opts{'B'})){ $params .= "-B "; }
if(defined($opts{'U'})){ $params .= "-m $opts{'U'} "; }
if(defined($opts{'s'})){  $params .= "-s "; }
if(defined($opts{'a'})){  $params .= "-a "; }
if(defined($opts{'q'})){ $queue_name = "$opts{'q'} ";}
else{ $queue_name = 'all.q';}
if(defined($opts{'m'}))
{ 
	$runmode = $opts{'m'}; 
	if($runmode ne 'local' && $runmode ne 'pbs'){ $runmode = 'local'; }
}
else{ $runmode = 'local'; }
if($runmode eq 'pbs')
{
	if(!defined($opts{'w'})){ die "# $0 : need the path to a working directory\n" }
	else{ $PBSoutDIR = $PBSworkDIR = $opts{'w'} . '/'; }
}
else{ $PBSoutDIR = $PBSworkDIR = ''; }

if(defined($opts{'d'})){ $DNADIR = $opts{'d'}; }
elsif(!$use_marfil_prot){ die "# $0 : need a DNA directory with .fna files\n" }


############################################################################

print "# $progname : runmode $runmode\n# DNADIR is: $DNADIR\n# ProtDIR is : $PROTDIR\n# PBSworkDir and PBSoutDIR is: $PBSoutDIR\n# params: $params\n queue: $queue_name\n\n";
#exit;

#open(LS,"ls -l $PROTDIR |") || die "# $progname : cannot list $PROTDIR\n";
# v0.2 uses the more portable opendir
opendir(DIR,$PROTDIR) || die "# $progname : cannot open DIR $PROTDIR : $!\n\n";
while( $filename = readdir DIR )
{
	next if $filename =~ /^\.\.?$/; # skip . and ..
	next unless $filename =~(/\.faa$/);
	#$filename = (split)[8];
	$filename = (split(/\.faa/,$filename))[0];	
		
	if(!$use_marfil_prot){ $dnafile = $DNADIR . "/" . $filename . ".fna"; }
	$protfile = $PROTDIR . "/" . $filename . ".faa";
	$fasta4phylo = $filename . "_fasta4phylo.out";
	
	if(!$use_marfil_prot && -s $dnafile || -s $protfile)
	{
		print "# running: $EXECUTABLE with protfile: $protfile and params: $params\n";
		
		if($runmode eq 'local')
		{
			if($use_marfil_prot){ system("$EXECUTABLE -p $protfile $params > $fasta4phylo");}
			else{ system("$EXECUTABLE -n $dnafile -p $protfile $params > $fasta4phylo"); }
		}
		else
		{
			my $PBSoutfile = $PBSoutDIR . $filename . ".pbsout";
        		$fasta4phylo = $filename . "_fasta4phylo.out"; #$PBSoutDIR . 
			my $qsubcommand = " -N n$filename -l qname=$queue_name -j y -o $PBSoutfile -S /bin/bash"; #n$filename, comienza con letra
			
			if($use_marfil_prot)
			{
			my $qresult = `$qsubEXE $qsubcommand <<EOF
                        cd $PBSworkDIR
                        $EXECUTABLE -p $protfile $params > $fasta4phylo
                        EOF`;
			}
			else
			{
			my $qresult = `$qsubEXE $qsubcommand <<EOF
        		cd $PBSworkDIR
        		$EXECUTABLE -n $dnafile -p $protfile $params > $fasta4phylo
                         EOF`;
			}	
		        sleep($SLEEPTIME);
		}
	}
	else
	{
		print "# fallo $filename ($protfile)\n";
	}
#	exit;
}
#close(LS);
closedir(DIR);
