#!/bin/sh

if [ $# -lt 4 ]
then
	echo "Usage: $0 <reference> <library> <output dirname/basename> <query>..."
	exit 0
fi

echo "## Breakpoint Library Mapping started at `date` ##"

export SEED_LEN=36
export MIN_COVER=10
export LIB_LEN=60

BIN=`cd \`dirname $0\`; pwd`
REF=$1
LIB=$2
PREFIX=$3_

shift 3

for QUERY in $*
do
	echo "## Processing query $QUERY ##"
	OUTPUT=$PREFIX`basename $QUERY`

	echo "## Aligning the query against the library ##"
	sh     $BIN/align $LIB $QUERY > $OUTPUT.ini.sam

	echo "## Filtering hits for breakpoint coverage ##"
	python $BIN/filter.py $LIB_LEN $SEED_LEN $MIN_COVER $OUTPUT.ini.sam > $OUTPUT.fil.sam

	echo "## Converting hits to Fastq ##"
	python $BIN/sam2fq.py $OUTPUT.fil.sam > $OUTPUT.fil.fq

	echo "## Aligning the hits against the reference ##"
	sh     $BIN/align $REF $OUTPUT.fil.fq > $OUTPUT.ref.sam 

	echo "## Splitting hits for uniqueness ##"
	python $BIN/splituni.py $OUTPUT.fil.sam $OUTPUT.ref.sam > $OUTPUT.uni.sam 2> $OUTPUT.xun.sam
done


echo "## Scoring and reporting calls ##"
SVCALL=$PREFIX`date +%y%m%d_%H%M%S`.svcall
python $BIN/svhit.py $PREFIX*.uni.sam > $SVCALL.uni
python $BIN/svhit.py $PREFIX*.xun.sam > $SVCALL.xun
python $BIN/svcall.py $SVCALL.uni $SVCALL.xun > $SVCALL 2> $SVCALL.txt

echo "## Breakpoint Library Mapping ended at `date` ##"
