#!/usr/bin/perl -w

# usage : perl sm_tophat.pl <read1 file> <read2 file>
# Sarah Maman - 2016
# Copyright (C) 2016 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;
use Getopt::Long;

my $cfg = Config::IniFiles->new( -file => "/usr/local/bioinfo/src/galaxy-dev/galaxy-dist/PATH.ini" );
my $path = $cfg->val( 'workPath', 'FILEPATH_DEV' );
	
my $TOPHAT = $cfg->val( 'toolsPath', 'TOPHAT2_PATH' );
my $bowtie2build = $cfg->val( 'toolsPath', 'BOWTIE2_INDEXATION_PATH' );

my $lib;
my $reads_selector;
my $input_read1;
my $input_read2;
my $input_read;
my $reference_selector;
my $input_reference;
#my $reference_sourceref_file_cachedfieldspath;
my $reference_sourceref_file;
my $p;
my $r;
my $a;
my $g;
my $max_intron;
my $output_bam;
my $output_bed;
my $output_log;
my $output_sum;
my $output_unmapped_bam;
my $zip;
my $gtf_cond;
my $inputGTF;
my $aoption;
my $goption;

Getopt::Long::Configure( 'no_ignorecase', 'bundling' );
GetOptions (
    'lib=s' => \$lib,
    'readsselector=s'=> \$reads_selector,
    'readsinputread1=s' => \$input_read1,
    'readsinputread2=s' => \$input_read2,
    'readsinputread=s' => \$input_read,
    'referencesourcereferencesourceselector=s' => \$reference_selector,
	'referencesourcereffile=s' => \$input_reference,
    'referencesourcereffilecachedfieldspath=s' => \$reference_sourceref_file,
    'p=i' => \$p,
    'r=i' => \$r,
    'a=i' => \$a,
    'g=i' => \$g,
    'maxintron=i' => \$max_intron,
    'outputbam=s' => \$output_bam,
    'outputbed=s' => \$output_bed,
    'outputlog=s' => \$output_log,    
    'outputsum=s' => \$output_sum,
    'outputunmappedbam=s' => \$output_unmapped_bam,
    'zip=s' => \$zip,
    'gtfcondgtf=s' => \$gtf_cond,
    'gtfcondinputgtf=s' => \$inputGTF   
) or die "Usage: Error in command line arguments\n";


my $cmd = ''; my $cmd2 = '';
my $poption ="",
my $roption ="";
my $max_intron_option ="";
my ($nb) = ($output_bam=~/galaxy_dataset_(\d+)\.\S+$/);
#my $liboption="";
my $genome_index_base="";
print STDOUT "$lib \n;";


#if (!$lib eq ""){$liboption = "--library-type $lib";}
if (!$p eq ""){$poption = "-p $p";}
if (!$r eq ""){$roption = "-r $r";}
if (!$a eq ""){$aoption = "-a $a";}
if (!$g eq ""){$goption = "-g $g";}
if (!$max_intron eq ""){$max_intron_option = "--max-intron-length $max_intron";}

my $gtfoption ='';
if (!$gtf_cond eq "F"){$gtfoption = "-G $inputGTF";}
else {$gtfoption ="";}

#Creation du repertoire de sortie des resultats
`cd $path/; mkdir $nb/; chmod -R 777 $nb/;`;

my $working_dir="$path/$nb/";
# if the Biologist has his own reference file
# generate the bowtie index for that reference
print STDOUT "reference_selector : *$reference_selector*\n\n";
if($reference_selector eq "history"){
	
	# copy your fasta file to the working directory
	`cp $input_reference "$working_dir/reference.fasta"`;
	chdir($working_dir) or die "system failed: chdir($working_dir) : $?"; 
	my $info=`pwd`;
	print STDOUT "INFO:Changed to working directory: $info \n ";
	
	# index the reference
	# get the "genome_index_base" ?
	$cmd = "($bowtie2build reference.fasta genome_index_base ) >& ./tophat.log 2>&1";
	
	#Info pour les biologistes
	print STDOUT "Tophat : \n\n $cmd \n\n ";
	system $cmd;
	
	# retrieve the new reference path
	$genome_index_base="$path/$nb/genome_index_base";
}
else{
	$genome_index_base=$input_reference;
}

print STDOUT "genome_index_base: *$genome_index_base*\n\n";

#Donner l extension fastq.gz si les fichiers sont zippes
if ($reads_selector eq "paired"){
        if ($zip eq "YES"){
	
	        print STDOUT "FASTQ files zipped ? $zip \n\n ";
	        `cp $input_read1 $input_read1.fastq.gz ; `;
	        `cp $input_read2 $input_read2.fastq.gz ; `;
	
	        $cmd = "($TOPHAT -o '$path/$nb/' --library-type $lib $poption $max_intron_option $roption $aoption $goption $gtfoption $genome_index_base $input_read1.fastq.gz $input_read2.fastq.gz) >& ./tophat.log 2>&1";
	
	        #Info pour les biologistes
	        print STDOUT "Tophat : \n\n $cmd \n\n ";
	        system $cmd;
	        #Supprimer les fichiers devenus inutiles
	        #`rm $input_read2.fastq.gz ; `;
	        #`rm $input_read1.fastq.gz ; `;
        }
        else
        {
	        #commande : perl sm_tophat.pl
	        #Commande pour tester sur vm-galaxy :
	        #tophat -o `tests/ ` -p 16 --max-intron-length 5000 -r 200 /bank/bowtie2db/ensembl_danio_rerio_genome tests/ERR022486_chr22_read1 tests/ERR022486_chr22_read2
	        #tophat -o `basename ERR022486_chr22_read1 ` -p 16 --max-intron-length 5000 -r 200 /bank/bowtie2db/ensembl_danio_rerio_genome ERR022486_chr22_read1 ERR022486_chr22_read2
	        $cmd2 = "($TOPHAT -o '$path/$nb/' --library-type $lib $poption $max_intron_option $roption $aoption $goption $gtfoption $genome_index_base $input_read1 $input_read2) >& ./tophat.log 2>&1";
	
	        #Info pour les biologistes
	        print STDOUT "Tophat : \n\n $cmd2 \n\n ";
	        system $cmd2;
        }
}


if ($reads_selector eq "single"){
        if ($zip eq "YES"){
	
	        print STDOUT "FASTQ files zipped ? $zip \n\n ";
	        `cp $input_read $input_read.fastq.gz ; `;
	       	
	        my $cmdsingle = "($TOPHAT -o '$path/$nb/' --library-type $lib $poption $max_intron_option $roption $aoption $goption $gtfoption $genome_index_base $input_read.fastq.gz ) >& ./tophat.log 2>&1";
	
	        #Info pour les biologistes
	        print STDOUT "Tophat : \n\n $cmdsingle \n\n ";
	        system $cmdsingle;
	        #Supprimer les fichiers devenus inutiles
	        #`rm $input_read2.fastq.gz ; `;
	        #`rm $input_read1.fastq.gz ; `;
        }
        else
        {
	        #commande : perl sm_tophat.pl
	        #Commande pour tester sur vm-galaxy :
	        #tophat -o `tests/ ` -p 16 --max-intron-length 5000 -r 200 /bank/bowtie2db/ensembl_danio_rerio_genome tests/ERR022486_chr22_read1 tests/ERR022486_chr22_read2
	        #tophat -o `basename ERR022486_chr22_read1 ` -p 16 --max-intron-length 5000 -r 200 /bank/bowtie2db/ensembl_danio_rerio_genome ERR022486_chr22_read1 ERR022486_chr22_read2
	        my $cmd2single = "($TOPHAT -o '$path/$nb/' --library-type $lib $poption $max_intron_option $roption $aoption $goption $gtfoption $genome_index_base $input_read) >& ./tophat.log 2>&1";
	
	        #Info pour les biologistes
	        print STDOUT "Tophat : \n\n $cmd2single \n\n ";
	        system $cmd2single;
        }
}


if (! -e "$path/$nb/accepted_hits.bam")
{
print STDERR "BAM FILE NOT FOUND\n";
}
else
{
`mv "$path/$nb/accepted_hits.bam" $output_bam`;
}

if (! -e "$path/$nb/unmapped.bam")
{
print STDERR "unmapped.bam FILE NOT FOUND\n";
}
else
{
`mv "$path/$nb/unmapped.bam" $output_unmapped_bam`;
}

 
if (! -e "$path/$nb/junctions.bed")
{
print STDERR "JUNCTIONS BED FILE NOT FOUND\n";
}
else
{
`mv "$path/$nb/junctions.bed" $output_bed`;
}
#recuperation des fichiers de logs
#/work/galaxy-test/database/files/workspace//8463/logs/tophat.log
if (! -e "$path/$nb/logs/tophat.log")
{
print STDERR "LOG FILE NOT FOUND\n";
}
else
{
`mv "$path/$nb/logs/tophat.log" $output_log`;
}
#/work/galaxy-test/database/files/workspace//8481//align_summary.txt
if (! -e "$path/$nb/align_summary.txt")
{
print STDERR "align summary FILE NOT FOUND\n";
}
else
{
`mv "$path/$nb/align_summary.txt" $output_sum`;
}
