#!/bin/bash

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

RETCODE="0"

# Check for readpair files.
READLIST=reads$$.txt
bl_seqreadlist.py --tsv "$TSVFILE" --outtype polluxcom > $READLIST

if [[ -z `cat $READLIST | grep '\S'` ]]
then
    RETCODE="2"
    MESSAGE='You must select one or more pairs of read files before running Pollux.'
    echo $MESSAGE >> pollux.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='Pollux cannot read compressed (.gz) files. Decompress files with gunzip *.gz'
        echo $MESSAGE >> pollux.log
        java -jar $BIRCH/script/ErrorBox2.jar "$MESSAGE"
    fi
fi

# If any of the files are compressed, open up an error message.
# Otherwise, run transrate
if [ "$RETCODE" -eq "0" ]
then
    while read line; do
        nice pollux $line -o $OUTDIR $ARGUMENTS >> pollux.log
    done < $READLIST
    rm $READLIST

    # Pollux puts a '.corrected' extension on output files. Many assemblers don't
    # recognize these file names as representing fastq files. So we add a .fq extension
    # to each of the .corrected files.
    cd $OUTDIR
    for file in `ls -1` ;
    do
        ext="${file##*.}"
        if [ ${ext} = 'corrected' ] 
        then
            mv $file $file.fq
        fi
    done    

else
    rm $READLIST
    exit 2 # returns an error code
fi

