#!/usr/bin/perl -w 
# usage : perl sm_gtf_manip.pl 
#smaman - 26/04/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/>.
#

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

my $input_gtf          = $ARGV[0]; 
my $output_report      = $ARGV[1]; 
my $cfg = Config::IniFiles->new( -file => "/path/to/PATH.ini" );
 
#Récuperer le numero (unique) de l'output afin, si besoin, de créer un répertoire de travail unique dans /work/galaxy/workspace
my ($nb) = ($output_report=~/galaxy_dataset_(\d+)\.\S+$/);

my $GALAXYDATA = $cfg->val( 'workPath', 'FILEPATH_DEV' );
my $path = "$GALAXYDATA/$nb/";
`cd $GALAXYDATA; mkdir $nb/; chmod 777 $path/;`;
my $cmd='';
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
my $ALL = $mday."-".($mon+1)."_".$hour."h".$min."mn".$sec."sec";



#Combien y a-t-il de genes ?
#cat Danio_rerio_chr22.Zv9.62.gtf | cut -f9 | cut -d";" -f1 | sort -u | wc -l
`cat $input_gtf  | cut -f9 | cut -d";" -f1 | sort -u | wc -l > $path/tmp1`;
#Combien y a-t-il de transcrits ?
#cat Danio_rerio_chr22.Zv9.62.gtf | cut -f9 | cut -d";" -f2 | sort -u | wc -l
`cat $input_gtf | cut -f9 | cut -d";" -f2 | sort -u | wc -l > $path/tmp2`;
#regrouper les resultats en un seul fichier
`paste $path/tmp1 $path/tmp2 > $path/${ALL}_report.txt`;

open(COUNT,">$path/${ALL}_report.txt") or die "Unable to open file $path/${ALL}_report.txt";
my $tmp1 = `cat $path/tmp1`;
my $tmp2 = `cat $path/tmp2`;
print COUNT "Your GTF contains :\n\nNumber of genes : $tmp1 \n\nNumber of transcripts : $tmp2 \n\n ";
close(COUNT);

#Recuperation du fichier dans Galaxy
if (! -e "$path/${ALL}_report.txt"){print STDERR "Pas de report produit \n";}
else {$cmd = "(mv $path/${ALL}_report.txt $output_report) >& ./cp_report_gtf.log 2>&1";
system $cmd;}
