#!/usr/bin/perl -w
# smaman
# usage : perl bam2bamsorted.pl <BAM file> <output BAM file sorted>
use strict;
use File::Basename;

my $input_bam = $ARGV[0];
my $output_file = $ARGV[1];
my $input_dir = dirname($input_bam);
my $input_basename=basename($input_bam,'.bam');
my $input_bamsorted="$input_dir/${input_basename}-sorted";
my ($nb) = ($output_file=~/galaxy_dataset_(\d+)\.\S+$/);
my $SAMTOOLS = '/usr/local/bioinfo/bin/samtools';
my $cmd = '';

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

#$output_file = `$SAMTOOLS sort -n -m 2147483648 $input_bam $output_file`;

$cmd = "($SAMTOOLS sort -n -m 2147483648 $input_bam $input_bamsorted) >& /galaxydata/logs/sm_samtools_$nb.log 2>&1";
system $cmd;
if (! -e "${input_bamsorted}.bam"){print STDERR "OUTPUT FILE NOT FOUND\n";}
else{`(cp ${input_bamsorted}.bam $output_file) >& ./cp.log 2>&1`}

close( IN );
