#!/usr/bin/perl -w 
# usage : perl samtools faidx chr1 


# Copyright (C) 2012 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; 


my $input_file  = $ARGV[0]; 
my $param       = $ARGV[1]; 
my $output_file = $ARGV[2]; 
my $cfg = Config::IniFiles->new( -file => "/path/to/PATH.ini" ); 
my $dir = $cfg->val( 'workPath', 'FILEPATH_DEV' );
my ($nb) = ($output_file=~/galaxy_dataset_(\d+)\.\S+$/);
my $SAMTOOLS = $cfg->val( 'toolsPath', 'SAMTOOLS_PATH' );
my $cmd = ''; 

`cd $dir/; mkdir $nb/; chmod -R 777 $nb/; cd $nb/; ln -s $input_file input.fasta; `;
#chmod 777 input.fasta;
$cmd = "(cd $dir/$nb/; $SAMTOOLS faidx input.fasta $param > $nb.fasta) >& ./samtools_faidx.log 2>&1"; 
system $cmd; 
print STDOUT "Command line : $cmd \n ln -s $input_file input.fasta;";

if (! -e "$dir/$nb/$nb.fasta") {print STDERR "FASTA FILE NOT FOUND\n"; } 
else { `(cp -a $dir/$nb/$nb.fasta $output_file) >& ./cp.log 2>&1`}
