#!/usr/bin/perl -w

# usage : sm_gtfgff.pl
# sarah maman - 12 dec 2013 - 
# Copyright (C) 2013 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/>.
#


#perl sm_gff_to_gtf.pl TESTS/s_cerevisiae_SCU49845.gff3
#galaxy-dev@genotoul2 /usr/local/bioinfo/src/galaxy-dev/galaxy-dist/tools/sm_GFF2GTF $ ls -ltrah TESTS/
#-rw-r--r-- 1 galaxy-dev wbioinfo 458  1 déc.  11:52 s_cerevisiae_SCU49845.gff3
#-rw-r--r-- 1 galaxy-dev wbioinfo 274  1 déc.  11:53 s_cerevisiae_SCU49845.gff3.gtf


use strict;
use warnings;
use File::Basename;
use Config::IniFiles;

my $cfg = Config::IniFiles->new( -file => "/path/to/PATH.ini" );

#Inputs files
my $input_gff        = $ARGV[0];

#Galaxy outputs files
my $output_gtf       = $ARGV[1];
my ($nb) = ($output_gtf=~/galaxy_dataset_(\d+)\.\S+$/);
my $cmd; my $cmd2;

my $CONVERT_PATH = $cfg->val( 'toolsPath', 'CONVERT_PATH' );
my $LOGS = $cfg->val( 'toolsPath', 'LOGS_PATH' );
my $CONVERT = $CONVERT_PATH."/sm_gff_to_gtf.pl" ;
my $GALAXYDATA=$cfg->val( 'workPath', 'FILEPATH_DEV' );

`cd $GALAXYDATA; mkdir $nb/; chmod 777 $nb/; ln -s $input_gff $GALAXYDATA/$nb/file.gft`;

#Lancer la premiere etape de traitement
$cmd = "(perl $CONVERT $GALAXYDATA/$nb/file.gft) >& $LOGS/sm_convertGFFGTF_$nb.log 2>&1;";
system $cmd;

#Info pour les biologistes
print STDOUT "Convert GFF to GTF : \n\n $cmd \n\n ";

#Recuperation des output Galaxy
my $gtf = "$GALAXYDATA/$nb/file.gft.gtf";
if (! -e $gtf ){print STDERR "Echec lors de la generation du fichier de sortie $gtf \n";} 
else {$cmd2 = "(cp -a $gtf $output_gtf) >& ./cpgfftogtf.log 2>&1"; system $cmd2;}
