#!/bin/bash

# Synopsis: bl_samtools-stats.sh tsvfile outdir samtools-statsargs

# Get command line options
TSVFILE=$1 
shift
ARGUMENTS=$*

RETCODE="0"

# Assumes a list of bam files, one filename per line
READLIST=reads$$.txt
cat "$TSVFILE" > $READLIST

if [[ -z `cat $READLIST | grep '\S'` ]]
then
    RETCODE="2"
    MESSAGE='You must select one or more bam files before running samtools-stats.'
    echo $MESSAGE >> samtools-stats.log
    java -jar $BIRCH/script/ErrorBox2.jar "$MESSAGE"
else
    # Check for gzip-compressed files
    # Assumes that the first argument is the name of the input file
    # with a list of read files to be checked for the .gz extension
    if [[ -z `grep '.gz' $TSVFILE` ]]
    then
        RETCODE="0"
    else
        RETCODE="1"
        MESSAGE='samtools-stats cannot read compressed (.gz) files. Decompress files with gunzip *.gz'
        echo $MESSAGE >> samtools-stats.log
        java -jar $BIRCH/script/ErrorBox2.jar "$MESSAGE"
    fi
fi

# If any of the files are compressed, open up an error message.
# Otherwise, run samtools-stats
if [ "$RETCODE" -eq "0" ]
then
    # Run samtools-stats for each set of read file(s)
    while read line; do
        nice samtools stats $ARGUMENTS $line  > $line.stats
    done < $READLIST
    rm $READLIST   
else
    rm $READLIST
    exit 2 # returns an error code
fi

