#!/usr/bin/perl -w 
# usage : perl sm_samtools_view_coord.pl 
#smaman - 24/04/2013

# Copyright (C) 2013 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_bam          = $ARGV[0]; 
my $param              = $ARGV[1]; 
my $output_bam         = $ARGV[2];  

my $cfg = Config::IniFiles->new( -file => "/path/to/PATH.ini" );
my $SAMTOOLS = = $cfg->val( 'toolsPath', 'SAMTOOLS_PATH' );
my $cmd = ''; 
my $cmd2 = '';
my $path = $cfg->val( 'workPath', 'FILEPATH_DEV' );
my ($nb) = ($output_bam=~/galaxy_dataset_(\d+)\.\S+$/);

#Creation du repertoire de sortie
`cd $path; mkdir $nb; chmod -R 777 $nb/;`;
my $chemin = $path."/".$nb."/";


#samtools view -c alnsort.bam chr:start-end 
$cmd2 = "($SAMTOOLS index $input_bam ;$SAMTOOLS view -h $input_bam $param | $SAMTOOLS  view -bS - > ${chemin}extracted.bam)>& ./view1.log 2>&1";
system $cmd2;


#Info pour les biologistes
print STDOUT "\nSamtools index and view :\n\n $cmd2 \n\n";

if (! -e "${chemin}extracted.bam"){print STDERR "Pas de BAM produit \n";}
else {$cmd = "(mv ${chemin}extracted.bam $output_bam) >& ./cp_report_3.log 2>&1";
system $cmd;}

#pour tester :
#perl sm_samtools_view_coord.pl tests/TP/SRR007327.bam "NC_012125.1:1-1000" tests/out.html
#samtools sort tests/TP/SRR007327.bam tests/TP/SRR007327_sorted.bam ;samtools index tests/TP/SRR007327_sorted.bam ;samtools view -c tests/TP/SRR007327_sorted.bam NC_012125.1:1-1000
