#!/usr/bin/perl -w

# usage : perl run gpi
# Sarah Maman - 07/12/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',
  'gpi_out=s',
  'dirname|d=s'
) or die "ERROR: Failed to parse command line options\n";

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

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

my $cmd = '';


$cmd = $GPI_PERL." --infile ".$config->{fasta}." --delta ".$config->{delta}." --encodingfile ".$config->{encoded_name}." --outpath ".$config->{dirname}." --execommand ".$GPI_BIN." --workpath ".$config->{dirname}." 2>&1";
print STDOUT "#La ligne de commande utilisee est : \n\n $cmd \n";
print STDOUT "\n\n## GPI log\n";
system $cmd;

#Recuperation des fichiers dans Galaxy
my $results = glob($config->{dirname}."/*gpi_results.res");
if (! -e $config->{dirname}."/gpi_title.txt" || ! -e "$results" ){
	print STDERR "Pas de fichier gpi_title.txt et/ou *gpi_results.res produit \n";
}else {
	$cmd = "sed 's/\t/\tgpi /g' ".$config->{dirname}."/gpi_title.txt | cat - ".$config->{dirname}."/*gpi_results.res > ".$config->{gpi_out};
	system $cmd;
}


