#!/usr/bin/perl -w

# usage : perl bwa_aln_sampe.pl <FASTA ref file> -b1 <BAM file> <output BAM file> 
#sarah maman - 10 juillet 2012 - Mis en place dans le cadre du projet SwanPorc

use strict;
use File::Basename;

my $input_fasta = $ARGV[0];
my $output = $ARGV[1];
my $etat_bank = $ARGV[2];
my $ref_bank = $ARGV[3];
my $ref2_bank = $ARGV[4];
my $bank = substr $ref_bank ,6 ;


#pour eviter que la commande ne fonctionne plus si le $PATH est perdu suite a un restart de galaxy
my $BWA = '/usr/local/bioinfo/bin/bwa';
#pour connaître le path des samtools, utiliser la commande which samtools
my $SAMTOOLS = '/usr/local/bioinfo/bin/samtools';
my $cmd = '';

#print ("LISTE DES ARGUMENTS :bank: $bank\n--arg0: $ARGV[0] --arg1:$ARGV[1] --arg2: $ARGV[2] --arg3: $ARGV[3] --4: $ARGV[4] \n ");
#if ($etat_bank eq "--fileSource=indexed") -- RIEN A FAIRE DE PARTICULIER
if ($etat_bank eq "--fileSource=history") 
{
	#indexation de la banque perso chargee dans l historique
	my $tailleFichier = (stat($bank))[7];
	#Indexation du genome de reference (ne pas placer cette commande en background)
	#si le genome de référence est gros , plus de 10 MB, alors indexer avec l'option -a bwtsw
	#si le genome est petit, indexer avec -a is 
	my $cmd = '';
	if ($tailleFichier > 10485760) {
	$cmd = "$BWA index -ca bwtsw $bank  >> ./bwa.log 2>&1";
	} 
	if ($tailleFichier < 2147483648){
       	 $cmd = "$BWA index -ca is $bank  >> ./bwa.log 2>&1";
	}
	else {
		$cmd ="$BWA index -c $bank  >> ./bwa.log 2>&1";
	}
}

#Ouverture des fichiers entrants
open (IN, "<$input_fasta") or die "Cannot open $input_fasta !";

#Alignement des donnees pairees uniquement
system ("($BWA aln $bank $input_fasta | $BWA samse $bank - $input_fasta | $SAMTOOLS view -bS - | $SAMTOOLS sort - $bank.sort ) >& ./aln_bam_tri.log 2>&1");

if (! -e "$bank.sort.bam")
{
print STDERR "BAM SORTED FILE NOT FOUND\n";
}
else
{
`(cp -a \"$bank.sort.bam\" $output) >& ./cp_aln_bam_tri.log 2>&1`
}


close( IN );
close( IN );
