#!/usr/bin/perl -w

# usage : perl split_VCF_files.pl
#sarah maman - 13/12/2012

use strict;
use File::Basename; 
use URL::Encode qw(url_encode url_decode); 
use Config::IniFiles;

# --infile string, the path of the input file VCF
my $input_vcf = $ARGV[0];
#  --snp_number_per_file string, number of lines per splitted files
my $line      = $ARGV[1];
#  --splitted_filename_size string, the size of the filenames splitted files
my $size      = $ARGV[2];
#  Nom de projet unique (pour ensuite reperer le fichier fasta genere)
my $id        = $ARGV[3];
#  --working_dir string, directory to split the files


#Le fichier sortant est un fichier html avec un ensemble de liens vers les fichiers generes
my $output_html   = $ARGV[4];

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); 
my $ALL =  $mday."-".($mon+1)."_".$hour."h".$min."mn".$sec."sec"; 

#Récuperer le numero (unique) de l'output 
my ($nboutput) = ($output_html=~/galaxy_dataset_(\d+)\.\S+$/);


#pour connaître le path du script perl
#SUR GENOTOUL : le script + les dependances
my $cfg = Config::IniFiles->new( -file => "/path/to/PATH.ini" );
#pour l'acces aux librairies (API Ensembl)
my $registry = $cfg->val( 'toolsPath', 'registry_PATH' );
my $SPLIT_PATH= $cfg->val( 'toolsPath', 'SPLIT_PATH' );
my $LOGS = $cfg->val( 'toolsPath', 'LOGS_PATH' );
my $SPLIT = $SPLIT_PATH."/split_VCF_files.pl" ;
my $galaxydata = $cfg->val( 'workPath', 'FILEPATH_DEV2' );


$ENV{PERL5LIB} = '/usr/local/bioinfo/src/ensembl-api/current/ensembl/modules:/usr/local/bioinfo/src/ensembl-api/current/ensembl-variation/modules:/usr/local/bioinfo/src/ensembl-api/current/ensembl-compara/modules:/usr/local/bioinfo/src/ensembl-api/current/ensembl-functgenomics/modules:/usr/local/bioinfo/src/ensembl-api/current/ensembl/modules:/usr/local/bioinfo/src/ensembl-api/current/ensembl-variation/modules:/usr/local/bioinfo/src/ensembl-api/current/ensembl-functgenomics/modules:/usr/local/bioinfo/src/ensembl-api/current/ensembl-compara/modules:/tools/perl5/modules/lib/perl5/x86_64-linux-thread-multi:/tools/perl5/modules/lib/perl5';

#Autres variables
my $cmd = '';



#creation d'un fichier html
open (HTML, ">", "results.html") or die "Cannot create results.html";


#recuperer le path Galaxy et le path du projet (dirname($input1);)
my $path = $galaxydata."/".$id ;


#Avant de lancer la commander, il faut créer les répertoires résultats:
$cmd="cd $path; mkdir ${ALL}_split_VCF ; chmod -R 777 ${ALL}_split_VCF;";
system $cmd;


#$cmd = "($PROTSEQ --infile $input1 --outfileprot ${input1}_${input2}.form --outfileprot_codedName ${input1}_${input2}.fasta --species $input2 --registry_file $registry --delta $delta --out_fastas_single_dir /work/galaxy/${ALL}_protNseq --outencodingtable ${input1}_names_encoding.txt --out_fastas_Nseq_dir /work/galaxy/${ALL}_protNseq --Nseq $Nseq --base_name $basename --sizeseqmin $sizeseqmin --out_fastas_Nseq_dir_protlenmin /work/galaxy/${ALL}_protNseqSizemin --Nseq_protlenmin $Nseq_protlenmin --out_vep_NSC_dir /work/galaxy/${ALL}_VEP_NSC --out_vep_STOP_dir /work/galaxy/${ALL}_VEP_STOP --outvep_res ${input1}_vep_results.txt -outvep_title ${input1}_vep_title.txt) >& ./protseq.log 2>&1";
$cmd = "(cd $path; $SPLIT --infile $input_vcf --snp_number_per_file $line --splitted_filename_size $size --working_dir ${ALL}_split_VCF) >& $LOGS/split_VCF_$nboutput.log 2>&1 ";
system $cmd;


#Fournir la ligne de commande au biologiste via le stdout
print STDOUT "La ligne de commande utilisee est : \n\n  $cmd \n\n";


print HTML "Voici l'ensemble des vcf issus du split VCF :";
print HTML ("<br>");
print HTML "Veuillez cliquer sur les liens pour ouvrir vos fichiers resultats. \n Veuillez enregister chaque fichier sur votre PC puis les uploader ensuite dans Galaxy avec l'outil Get Data (bouton 'Parcourir'.\n\n";
print HTML ("<br><br>");


#Pour pouvoir ouvrir les fichiers dans la fenetre de visualisation de Galaxy, il faut paramétrer Apache de la maniere suivante :
# vi /etc/httpd/conf.d/galaxy.conf 
#pour ajouter cette ligne : RewriteRule ^/galaxy/download/(.*) /work/galaxy/database/files/$1 [L]
#puis reload de httpd :  /etc/init.d/httpd reload


#ouverture du fichier ${input1}_${input2}.form
my $url_form="${input1}_${input2}.form";
$url_form=~s/^\/work\/galaxy-dev\/database\/files/\/galaxy-dev\/download/;
print HTML "<a href=\"$url_form\">Link to specie.form file. This file will contain the protein sequences FASTA FORMAT, 1 per allele from the input file</a>";
print HTML ("<br><br>");

#ouverture du fichier ${input1}_${input2}.fasta
my $url="${input1}_${input2}.fasta";
$url=~s/^\/work\/galaxy-dev\/database\/files/\/galaxy-dev\/download/;
print HTML "<a href=\"$url\">Link to specie.fasta file. This file  with protein sequences, 1 per allele, with short encoded/shorter name</a>";
print HTML ("<br><br>");


#ouverture du fichier ${input1}_names_encoding.txt
my $url2="${input1}_names_encoding.txt";
$url2=~s/^\/work\/galaxy-dev\/database\/files/\/galaxy-dev\/download/;
print HTML "<a href=\"$url2\">Link to names_encoding.txt file. This output file name encoding (initial name ending by '_allele1' or '_allele2' => short name 'seqx')</a>";
print HTML ("<br><br>");


#ouverture de fichiers :
my $url3="${input1}_vep_results.txt";
$url3=~s/^\/work\/galaxy-dev\/database\/files/\/galaxy-dev\/download/;
print HTML "<a href='$url3'> Link to results.txt file for vep result information for the join step</a>";
#iso-8859-1
print HTML ("<br><br>");


#ouverture du fichier ${input1}_vep_title.txt
my $url4="${input1}_vep_title.txt";
$url4=~s/^\/work\/galaxy-dev\/database\/files/\/galaxy-dev\/download/;
print HTML "<a href='$url4'>Link to title.txt file for vep title information for the join step.</a>";
print HTML ("<br><br>");


if (! -e "results.html"){print STDERR "Pas de fichier html produit \n";}
else {$cmd = "(mv results.html $output_html) >& ./cp_split_VCF.log 2>&1";
system $cmd;}


close( HTML );
