#!/usr/bin/perl -w

# usage : perl sm_gatk_1-1.pl <BAM file> <BAM file>
#sarah maman - 06/05/2013

use strict;
use File::Basename;

my $input_bam         = $ARGV[0];
my $output_bam        = $ARGV[1];

#pour eviter que la commande ne fonctionne plus si le $PATH est perdu suite a un restart de galaxy
my $SAMTOOLS = '/usr/local/bioinfo/bin/samtools';
my $cmd = '';

#####################################################################
## ETAPE 1 : Suppression des lectures ayant le FLAG 20
##
## Input :   fichier BAM
## Output :  fichier BAM
#####################################################################
#samtools view -h ERR_merge_sorted.bam | perl -lane 'print $_ if($F[1]!=20)' |samtools view -bS - -o ERR_merge_sorted_no20.bam
#samtools view -h SRR007327_sorted.bam | perl -lane 'print $_ if($F[1]!=20)' |samtools view -bS - -o SRR007327_sorted_no20.bam
#mv ERR_merge_sorted_no20.bam ERR_merge_sorted.bam
#mv SRR007327_sorted_no20.bam SRR007327_sorted.bam

#my $tmp1 = "${input_bam}-tmp1";
#system ("($SAMTOOLS view -h $input_bam > $tmp1) >& ./gatk1-1.log 2>&1");

#my $tmp2 = "${input_bam}-tmp2";
#open (InFile2, ">",$tmp2) or die "Cannot create $tmp2";
#open (InFile,"$tmp1") or die "Can't open $tmp1 \n";
#    while (my $l = <InFile>) {
#	chomp $l;
#	my @t=split(/\t/,$l);
#	if ($l =~ /^@/){
#		print InFile2 "$l\n";
#		next;	
#	}
#        if($t[1] != 20){print InFile2 "$l\n";}
#}
#close (InFile);
#close (InFile2);

#system ("($SAMTOOLS view -bS $tmp2 >& ${input_bam}_merge_sorted_no20.bam)");
#system ("rm $tmp1; rm $tmp2; mv ${input_bam}_merge_sorted_no20.bam ${input_bam}_merge_sorted.bam");

system ("($SAMTOOLS view -b -F 20 $input_bam -o ${input_bam}_no20.bam) >& ./gatk1-1.log 2>&1");

#Info pour les biologistes
print STDOUT "\nRemove reads with Flag 20 \n\n $SAMTOOLS view -b -F 20 $input_bam -o ${input_bam}_no20.bam \n\n";

#Recuperation des fichiers dans Galaxy
if (! -e "${input_bam}_no20.bam"){print STDERR "BAM FILE NOT FOUND\n";}
else{`mv "${input_bam}_no20.bam" $output_bam ;`}
