#!/usr/bin/perl -w

# usage : perl sm_htseqcount_merge.pl
# Sarah Maman
# Copyright (C) 20XX 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;


my $output_csv               = $ARGV[0];
my $input_htseqcount         = $ARGV[1];
my $input_htseqcount_name    = $ARGV[2];
#Liste des fichiers entrants issus de htseqcount
#my $inputs_raw_transcripts_tsv = @ARGV[9..$#ARGV]; --> dans la ligne de ccde :@ARGV[10..$#ARGV]
my $inputs_count            = @ARGV[3..$#ARGV];

my $cmd = '';
my $COUNTHTSEQMERGE = "/usr/local/bioinfo/Scripts/bin/htseqcount_merge.py";
#my $path = dirname($input_htseqcount);
my $path = "/galaxydata/database/files/workspace/";
my ($nb) = ($output_csv=~/galaxy_dataset_(\d+)\.\S+$/);
#creation du repertoire de sortie
`cd $path; mkdir $nb; chmod -R 777 $nb `;
my $dirresults= $path."/".$nb;

#Ligne de commande :
#python /usr/local/bioinfo/Scripts/htseqcount_merge.py -f /work/smaman/TEST/fof -o /work/smaman/TEST/toto -c
#Pour tester la ligne de ccde dans vm-galaxy :
#perl sm_htseqcount_merge.pl tests/galaxy_dataset_2222.dat tests/htseq_count_ERR022486.txt 6 tests/htseq_count_ERR022488.txt 8

#Creation du fichier fof qui contient la liste des fichiers fusionnes
#[smaman@genotoul:/work/smaman/TEST]$ more fof
#htseq_count_ERR022486.txt
#htseq_count_ERR022488.txt

my $fof = $dirresults."/fof_".$nb;
open FILE,">$fof";
	#my $cpt=1;
        #foreach my $file (@ARGV[1..$#ARGV]){
	#	print FILE $file,"\n"; 
	#	$cpt++;
	#}
for (my $i=1; $i<$#ARGV; $i+=2){
printf FILE "%s\t%s\n",$ARGV[$i],$ARGV[$i+1];
}


print STDOUT "Fichiers entrants : \n\n $fof\n\n ";

$cmd = "(python $COUNTHTSEQMERGE -f $fof -o $dirresults/htseqcountmerge.csv -c) >& ./htseqcountmerge.log 2>&1";
system $cmd;

#Info pour les biologistes
print STDOUT "Htseq count merge: \n\n $cmd\n\n ";

close FILE;


# Recuperation du fichier sortant
if (! -e "$dirresults/htseqcountmerge.csv"){print STDERR "htseqcountmerge.csv file not found. \n";}
else {`cp -a "$dirresults/htseqcountmerge.csv" $output_csv `;}

