#!/usr/bin/perl -w
# 13/11/2014 - Wrapper dans le cadre de la formation permanente RNAseq  - smaman

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

# SETTING GLOBAM VARIABLES ################################################################################
my $cfg = Config::IniFiles->new( -file => "/usr/local/bioinfo/src/galaxy-test/galaxy-dist/PATH.ini" );
my $FEATURECOUNTS = $cfg->val( 'toolsPath', 'FEATURECOUNTS' );
#~ my $FEATURECOUNTS = '/usr/local/bioinfo/bin/featureCounts'; 
my $file_path = $cfg->val( 'workPath', 'FILEPATH_DEV' );
#~ my $file_path="/galaxydata/database/files/workspace/";
###########################################################################################################

my $inputannotation="";
my $output_file=""; 
my $input1sam="";
my $inputssam="";
my $input1samname="";
my $inputssamname="";
my $featuretype="";
my $attributetype="";
my $readsallowed="";
my $strandspecificreads="";
my $multimappingreads="";
my $onlyprimaryalignments="";
my $minReadOverlap="";
my $pairedendparametersfragmentsoption="";
my $pairedendparametersfeatureoption="";
my $pairedendparametersminfraglength="";
my $pairedendparametersmaxfraglength="";
my $pairedendparameterssummarizationoption="";
my $pairedendparameterschimericoption=""; 
my $pairedendpairedendparameters="";
my @inputssams = ();
my @inputssamsname = ();

print STDOUT "arguments : ".join(" ", @ARGV)."\n";

Getopt::Long::Configure( 'no_ignorecase', 'bundling' );
GetOptions (
    'inputannotation=s' => \$inputannotation,
    'input1sam=s' => \$input1sam,
    'input1samname=s' => \$input1samname,        
    'featuretype=s' => \$featuretype,
    'attributetype=s' => \$attributetype,
    'readsallowed=s' => \$readsallowed,
    'strandspecificreads=s' => \$strandspecificreads,
    'multimappingreads=s' => \$multimappingreads,
    'onlyprimaryalignments=s' => \$onlyprimaryalignments,
    'minReadOverlap=i' => \$minReadOverlap,
    'fragmentsoption=s' => \$pairedendparametersfragmentsoption,
    'featureoption=s' => \$pairedendparametersfeatureoption,
    'minfraglength=i' => \$pairedendparametersminfraglength,
    'maxfraglength=i' => \$pairedendparametersmaxfraglength,     
    'summarizationoption=s' => \$pairedendparameterssummarizationoption,
    'chimericoption=s' => \$pairedendparameterschimericoption,
    'pairedendpairedendparameters=i' => \$pairedendpairedendparameters,
    'outputfile=s' => \$output_file,
    'inputssamname=s' => \@inputssamsname,
    'inputssam=s' => \@inputssams
) or die "Usage: Error in command line arguments\n";

# Multiple values for a uniq option / parameter
@inputssams = split(/,/,join(' ',@inputssams));
$inputssam=$inputssams[0];  
print STDOUT "\n inputssam  $inputssam  \n";  
@inputssamsname = split(/,/,join(' ',@inputssamsname));  
$inputssamname=$inputssamsname[0];  
print STDOUT "\n inputssam name  $inputssamname  \n";    

$readsallowed='' if($readsallowed eq 'vide');
$multimappingreads='' if($multimappingreads eq 'vide');
$onlyprimaryalignments='' if($onlyprimaryalignments eq 'vide');


$pairedendparametersfragmentsoption='' if(($pairedendparametersfragmentsoption eq 'vide') || ($pairedendpairedendparameters == 0) );
$pairedendparametersfeatureoption='' if(($pairedendparametersfeatureoption eq 'vide') || ($pairedendpairedendparameters == 0));
$pairedendparameterssummarizationoption='' if(($pairedendparameterssummarizationoption eq 'vide') || ($pairedendpairedendparameters == 0));
$pairedendparameterschimericoption='' if($pairedendparameterschimericoption eq 'vide');
#$pairedendparameterschimericoption='' if($pairedendpairedendparameters == 0);

    
#Recuperation des options en string
my $featuretype2 ='';
if ($featuretype eq "-t__exon"){$featuretype2 = "-t exon ";}
#~ if ($featuretype eq "-t__gene_id"){$featuretype2 = "-t  gene_id ";}
if ($featuretype eq "-t__CDS"){$featuretype2 = "-t CDS ";}


my $attributetype2 ='';
if ($attributetype eq "-g__gene_id"){$attributetype2 = "-g  gene_id ";}
if ($attributetype eq "-g__transcript_id"){$attributetype2 = "-g  transcript_id ";}


my $strandspecificreads2 ='';
if ($strandspecificreads eq "-s__0"){$strandspecificreads2 ="-s  0 ";}
if ($strandspecificreads eq "-s__1"){$strandspecificreads2 ="-s  1 ";}
if ($strandspecificreads eq "-s__2"){$strandspecificreads2 ="-s  2 ";}



print STDOUT "\n inputsam à partir du 2eme fichier: *$inputssam*\n";

print STDOUT "OPTIONS \n
featuretype : $featuretype2 \n 
attributetype : $attributetype2 \n 
readsallowed : $readsallowed \n
strandspecificreads : $strandspecificreads2 \n
multimappingreads : $multimappingreads \n
onlyprimaryalignments : $onlyprimaryalignments \n
minReadOverlap : $minReadOverlap \n
pairedendparametersfragmentsoption : $pairedendparametersfragmentsoption \n
pairedendparametersfeatureoption : $pairedendparametersfeatureoption \n
pairedendparametersminfraglength : $pairedendparametersminfraglength \n
pairedendparametersmaxfraglength : $pairedendparametersmaxfraglength \n
pairedendparameterssummarizationoption : $pairedendparameterssummarizationoption \n 
pairedendparameterschimericoption : $pairedendparameterschimericoption \n
outputfile  : $output_file
";

my $cmd = '';
my ($nb) = ($output_file=~/galaxy_dataset_(\d+)\.\S+/);
#my ($nb) = ($outputfile=~/galaxy_dataset_(\d+)\.\S+$/);
#my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
#my ($nb) = $mday."".($mon+1)."".$hour."".$min."".$sec."featurecount";

#Repertoire de sortie cree par le script, verif des droits d'ecriture sur ce repertoire de sortie

`cd $file_path; mkdir $nb/; chmod 777 $nb/; cd $nb/;`;
my $dirresults= $file_path.$nb;
my $OUT =$file_path."/$nb/OUT";
#~ `cd /work/galaxy-test/database/files/workspace/; mkdir $nb/; chmod 777 $nb/; cd $nb/;`;
#~ my $dirresults= "/work/galaxy-test/database/files/workspace/".$nb;
#~ my $OUT ="/work/galaxy-test/database/files/workspace/$nb/OUT";

#avec modification de l extension des inputs
#my $sam1 = "$input1sam.sam";
#if (!$sam1){`ln -s $input1sam $sam1;`;} 
#my $sam = "$inputsam.sam";
#if (!$sam){`ln -s  $inputssam $sam ;`;}

`ln -s $inputannotation $dirresults/annot.gtf;`;

                   
#Usage:  featureCounts [options] -a annotation_file -o output_file input_file1 [input_file2] ... 
#$cmd = "(cd $dirresults; $FEATURECOUNTS $featuretype2 $attributetype2 $readsallowed $strandspecificreads2 $multimappingreads $onlyprimaryalignments $minReadOverlap   $pairedendparametersfragmentsoption $pairedendparametersfeatureoption $pairedendparametersminfraglength $pairedendparametersmaxfraglength $pairedendparameterssummarizationoption $pairedendparameterschimericoption -a $dirresults/annot.gtf -o $output_file $input1sam $inputssam) >& ./featureCounts.log 2>&1";

# analyses on paired end reads
if($pairedendparametersfragmentsoption ne ""){

		$cmd = "(cd $dirresults; $FEATURECOUNTS -a $dirresults/annot.gtf -o $OUT $input1sam $inputssam $featuretype2 $attributetype2 $readsallowed $strandspecificreads2 $multimappingreads $onlyprimaryalignments --minReadOverlap $minReadOverlap $pairedendparametersfragmentsoption $pairedendparametersfeatureoption -d $pairedendparametersminfraglength -D $pairedendparametersmaxfraglength $pairedendparameterssummarizationoption $pairedendparameterschimericoption) >& ./featureCounts.log 2>&1";
}
# analyses on single end reads
else{
	
		$cmd = "(cd $dirresults; $FEATURECOUNTS -a $dirresults/annot.gtf -o $OUT $input1sam $inputssam $featuretype2 $attributetype2 $readsallowed $strandspecificreads2 $multimappingreads $onlyprimaryalignments --minReadOverlap $minReadOverlap) >& ./featureCounts.log 2>&1";
}


#Info pour les biologistes
print STDOUT "Your command line is : \n\n $cmd \n\n ";
system $cmd;  


#Remplacer les fichiers galaxy par leur nom
my $cmdsed=qq(chmod 777 $OUT; chmod 777 $OUT.summary; sed -i 's|$input1sam|$input1samname|g' $OUT;
sed -i 's|$dirresults/annot.gtf|Annotation_file_GTF|g' $OUT;
sed -i 's|$OUT|OutputFile|g' $OUT;
sed -i 's|$inputssam|$inputssamname|g' $OUT;
 );
system($cmdsed);


#Recuperation des fichiers par Galaxy
#-rw-r--r--   1 galaxy-dev wbioinfo    0  4 nov.  14:40 out.extendedFrags.fastq
#-rw-r--r--   1 galaxy-dev wbioinfo  266  4 nov.  14:40 out.notCombined_1.fastq
#-rw-r--r--   1 galaxy-dev wbioinfo  266  4 nov.  14:40 out.notCombined_2.fastq
#-rw-r--r--   1 galaxy-dev wbioinfo    0  4 nov.  14:40 out.hist
#-rw-r--r--   1 galaxy-dev wbioinfo    0  4 nov.  14:40 out.histogram

#if (! -e "$dirresults/annot.gtf"){print STDERR "output file not found. \n";}else{`cp -a $dirresults/annot.gtf $output_file`;}
if (! -e $OUT){print STDERR "output file not found. \n";}else{`cp -a $OUT $output_file`;}

