#!/usr/bin/perl -w

# usage : perl run_motoprot.pl
# Sarah Maman - 04/11/2012 - Maria Bernard 19/08/2015
# version : 1.1.0 : removing the use of output directory
# Copyright (C) 2012 INRA
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

use strict;
use File::Basename; 
use Getopt::Long;
use Config::IniFiles;

my $config = {} ;

GetOptions(
  $config,
  'fasta|f=s',
  'encoded_name|n=s',
  'delta|t=s',
  'mitoprot_rawout=s',
  'mitoprot_out=s',
  'dirname|d=s'
) or die "ERROR: Failed to parse command line options\n";

if (! defined $config->{dirname} ){
	$config->{dirname}= dirname $config->{mitoprot_out} ;
}

#pour connaître le path du tool
my $cfg = Config::IniFiles->new( -file => "/path/to/PATH.ini" );
my $MITOPROT_BIN = $cfg->val( 'toolsPath', 'MITOPROT_BIN_PATH' );
my $SCRIPT_CONSERVATION_MAISON= $cfg->val( 'toolsPath', 'SCRIPT_CONSERVATION_MAISON' );
my $MITOPROT_PERL = $SCRIPT_CONSERVATION_MAISON."/run_mitoprot.pl" ;

my $cmd = '';

#commande
$cmd = $MITOPROT_PERL." --infile ".$config->{fasta}." --outpath ".$config->{dirname}." --execommand ".$MITOPROT_BIN." --delta ".$config->{delta}.' --encodingfile '.$config->{encoded_name}." --workpath ".$config->{dirname}." 2>&1";
print STDOUT "##La ligne de commande utilisee est : \n\n\t".$cmd;

#print log (par exemple le nom des séquences non traitées car elles ne commencent pas par M"
print STDOUT "\n\n## Mitoprot log";
system $cmd;
print STDOUT "\n";
$cmd = "cat ".$config->{dirname}."/mitoprot_errors.txt";
system $cmd;

# gestion des sorties Galaxy
my $results = glob($config->{dirname}."/*mitoprot_results.res");
if (! -e $config->{dirname}."/mitoprot_title.txt" || ! -e $results) {
	print STDERR "Pas de fichier mitoprot_title.txt ou _mitoprot_results.res produit \n" ; 
}else {
$cmd = "sed 's/\t/\tmitoprot /g' ".$config->{dirname}."/mitoprot_title.txt | cat - ".$config->{dirname}."/*_mitoprot_results.res > ".$config->{mitoprot_out} ; 
system $cmd;
}

if (! -e $config->{dirname}."/mitoprot_results.txt") {
	print STDERR "Pas de fichier mitoprot_results.txt produit \n" ; 
}else {
$cmd = "mv ".$config->{dirname}."/mitoprot_results.txt ".$config->{mitoprot_rawout};
system $cmd;
}
