#!/usr/bin/perl -w 
# usage : perl sm_sam_explore.pl 
#smaman - 06/05/2013

use strict; 
use File::Basename; 

my $input_sam          = $ARGV[0]; 
my $output_flags       = $ARGV[1];  
my $output_reads       = $ARGV[2]; 
my $output_mapping     = $ARGV[3]; 

my $cmd = ''; 
my $cmd1 = '';
my $cmd2 = '';
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
my $ALL = $mday."-".($mon+1)."_".$hour."h".$min."mn".$sec."sec";

#Quels sont les différents « flags » contenus dans un des trois fichiers SAM ?
#Que signifient-ils (http://picard.sourceforge.net/explain-flags.html) ?
#cut -f2 ERR000017.sam | sort | uniq -c => 0, 4, 16 et 20
$cmd2 = "cut -f2 $input_sam  > ${ALL}_tmp1_comptage.sam; sort ${ALL}_tmp1_comptage.sam > ${ALL}_tmp2_comptage.sam; uniq -c ${ALL}_tmp2_comptage.sam > ${ALL}_tmp3_comptage.txt; rm ${ALL}_tmp1_comptage.sam; rm ${ALL}_tmp2_comptage.sam;";
system $cmd2;

# Combien de lectures du jeu ERR000017 sont parfaitement alignées ?
#grep -c "NM:i:0" ERR000017.sam => 821 365
`grep -c "NM:i:0" $input_sam > ${ALL}_comptage_reads.txt`;

# Quelle est la « mapping quality » maximum toujours pour le jeu ERR000017 ?
#Combien de lectures ont cette valeur de qualité ?
#cut -f5 ERR000017.sam | sort n | uniq -c => 37 / 1 431 781
$cmd1 = "cut -f5 $input_sam  > ${ALL}_tmp1_mapping.sam; sort -n ${ALL}_tmp1_mapping.sam > ${ALL}_tmp2_mapping.sam; uniq -c ${ALL}_tmp2_mapping.sam > ${ALL}_mapping.txt; rm ${ALL}_tmp1_mapping.sam; rm ${ALL}_tmp2_mapping.sam;";
system $cmd1;


#Recuperation du fichier dans Galaxy
if (! -e "${ALL}_tmp3_comptage.txt"){print STDERR "Pas de comptage produit \n";}
else {$cmd = "(mv ${ALL}_tmp3_comptage.txt $output_flags) >& ./cp_sam_explore_1.log 2>&1";
system $cmd;}


if (! -e "${ALL}_comptage_reads.txt"){print STDERR "Pas de comptage reads produit \n";}
else {$cmd = "(mv ${ALL}_comptage_reads.txt $output_reads) >& ./cp_sam_explore_2.log 2>&1";
system $cmd;}

if (! -e "${ALL}_mapping.txt"){print STDERR "Pas de comptage mapping quality produit \n";}
else {$cmd = "(mv ${ALL}_mapping.txt $output_mapping) >& ./cp_sam_explore_3.log 2>&1";
system $cmd;}
