#!/bin/bash 

# Convert sam files to bam and process for downstream compatibility
# Run on all sam files before using gatk.sh to call variants
# e.g. sam2bam.sh *.sam 

#Picard tools location
BASE=/u01/software/ngs/picard-tools-1.53/

# Error check subroutine
check_result(){
ERROR=$?
if [ $ERROR -ne 0 ]; then
	echo "Error retruned by $1 error code: $ERROR"
	exit 1;
fi
echo Successfully completed $1
}

echo $@
for f in $*
do
prefix=`echo $f | sed 's/\(.*\)\..*/\1/'`

# Convert sam to bam
java -jar $BASE/SamFormatConverter.jar I=$prefix.sam O=$prefix-unsorted.bam VALIDATION_STRINGENCY=SILENT
check_result SamFormatConverter

# Create read groups
java -jar $BASE/AddOrReplaceReadGroups.jar I=$prefix-unsorted.bam O=$prefix.bam SORT_ORDER=coordinate RGPU=run RGID=foo RGLB=bar RGPL=illumina RGSM=DePristo CREATE_INDEX=True VALIDATION_STRINGENCY=SILENT
check_result AddOrReplaceReadGroups

# Sort bam by coordinates
java -jar $BASE/SortSam.jar I=$prefix-rg.bam O=$prefix.bam SO=coordinate
check_result SortSam

# Create index file
java -jar $BASE/BuildBamIndex.jar I=$prefix.bam VALIDATION_STRINGENCY=SILENT 
check_result BuildBamIndex
rm $prefix-unsorted.bam 

done
