#!/usr/bin/perl -w

# usage : perl mapper.pl
#sarah maman - 13/09/2012

use strict;
use File::Basename; 

#-p precursors_ref_this_species.fa : il s'agit du fichier hairpin.fa
#-m mature_ref_this_species.fa : il s'agit du fichier mature.fa
#-r reads_collapsed.fa
my $input1 = $ARGV[0];
#fichier sortant
my $output1 = $ARGV[1];
#perl sm_quantifier.pl TESTS/toto.fasta TESTS/galaxy_dataset_55.html
my $g  = $ARGV[2];
my $e  = $ARGV[3];
my $f  = $ARGV[4];

my ($nb) = ($output1=~/galaxy_dataset_(\d+)\.\S+$/);
my $input_dir = "/galaxydata/database/files/workspace/".$nb;
`mkdir $input_dir/; chmod 777 $input_dir/;`;
print STDOUT "Working dirrectory created : $input_dir;\n\n";
#my $input_html="$input_dir/$nb-graph"; 

#pour connaître le path du tool cuadapt, utiliser la commande which cutadapt
my $QUANTIFIER = '/usr/local/bioinfo/src/galaxy-dev/galaxy-dist/tools/sm_mirdeep2/quantifier.pl';
my $hairpin = '/bank/Galaxy/sRNA-PlAn/Hairpin/current/flat/hairpin.fa';
my $mature = '/bank/Galaxy/sRNA-PlAn/Hairpin/current/flat/mature.fa';
my $cmd = '';my $cmd2 = '';
my $input = '';

#Ouverture des fichiers entrants
open (IN, "<$input1") or die "Cannot open $input1 !";

#$g2 $e2 $f2

my $g2 ="";
if ($g eq "") {$g2 = "";}else {$g2 = " -g $g ";}

my $e2 ="";
if ($e eq "") {$e2 = "";}else {$e2 = " -e $e ";}

my $f2 ="";
if ($f eq "") {$f2 = "";}else {$f2 = " -f $f ";}

#commande mapper
#$cmd = "($QUANTIFIER -p $hairpin -m $mature -r $input1) >& ./quantifier.log 2>&1";
$cmd = "(cd $input_dir/; $QUANTIFIER -p $hairpin -m $mature -r $input1  $g2 $e2 $f2) >& ./quantifier.log 2>&1";
system $cmd;
print STDOUT "Your command line : $cmd \n";

my $out = glob("$input_dir/*expression*/*expression_*.html");
#if (! -e "${input_html}.html"){print STDERR "Pas de fichier html produit \n";}
#else {$cmd = "(cp -a \"${input_html}.html\" $output1) >& ./cp_quantifier_output1.log 2>&1";
#system $cmd;}

if (! -e $out){print STDERR "Pas de fichier html produit \n";}else {$cmd2 = "(cp -a $out $output1) >& ./cp_quantifier_output1.log 2>&1";system $cmd2;}
close( IN );
