#!/usr/bin/perl -w

# usage : perl bam2bai4igv.pl <BAM file> <output SAI file>
#Sarah Maman
# 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 Config::IniFiles;

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

open (IN, "<$input_file") or die "Cannot open $input_file $!\n";

$cmd = "($SAMTOOLS index $input_file ) >& $LOGS/sm_bwa_$nb.log 2>&1";
system $cmd;

if (! -e "$input_file.bai")
{
print STDERR "BAI FILE NOT FOUND\n";
}
else
{
`cp -a $input_file.bai $output_file`;
}

close( IN );
