#!/usr/bin/perl -w

# usage : perl sm_samtools_sort_prefix.pl <BAM file> <output prefix BAM 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 $sortedbynames = $ARGV[1];
my $output_file = $ARGV[2];
my $cfg = Config::IniFiles->new( -file => "/path/to/PATH.ini" );
my $SAMTOOLS =  $cfg->val( 'toolsPath', 'SAMTOOLS_PATH' );
my $cmd = '';
my $sortedbynamesoption ='';

if ($sortedbynames eq "YES"){
$sortedbynamesoption = "-n ";
}
else {
$sortedbynamesoption = "";
}

#commande : samtools sort -n tests/accepted_hits.bam tests/prefix
#output : prefix.bam (ou  test.bam_prefix.bam)
#Via galaxy : perl sm_samtools_sort_prefix.pl tests/accepted_hits.bam
$cmd = "($SAMTOOLS sort $sortedbynamesoption $input_file ${input_file}.prefix ) >& ./samtools_sort_prefix.log 2>&1";
#Info pour les biologistes
print STDOUT "SAmtools sort prefix : \n\n $cmd \n\n ";
system $cmd;

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