#!/bin/bash

#JunctionDiff-vs-background.sh $variants $genomes ${reference.fields.crr_path} ${reference.fields.31G_var_paths} ${reference.54G_var_paths} $output_filtered $output_report $scoreThresholdA $scoreThresholdB $distance $minlength

#set some defaults
output_report="output_reports.tsv"   
		
set -- `getopt -n$0 -u -a --longoptions="variants: reference: VN_junctions: cgatools_binary: outputfile_filtered: outputfile_report: scoreThresholdA: scoreThresholdB: distance: minlength: " "h:" "$@"` || usage
[ $# -eq 0 ] && usage

while [ $# -gt 0 ]
do
    case "$1" in
       	--variants) 			variants=$2;shift;;  
		--reference)			crr=$2;shift;; 
		--VN_junctions)			VN_junctionfiles_list=$2;shift;;  	
		--cgatools_binary)		cgatools_binary=$2;shift;; 				#cgatools binary to use
		--outputfile_filtered) 	output_filtered=$2;shift;;  
		--outputfile_report) 	output_report=$2;shift;;  
		--scoreThresholdA) 		scoreThresholdA=$2;shift;;  
		--scoreThresholdB) 		scoreThresholdB=$2;shift;;  
		--distance) 			distance=$2;shift;;  
		--minlength) 			minlength=$2;shift;;		
        -h)        		shift;;
		--)        		shift;break;;
        -*)        		usage;;
        *)         		break;;            
    esac
    shift
done


# make copy of input junctions file, as this file will be altered
junctions="junctions.tsv"
cp $variants $junctions  


###  run JunctionDiff against all of the VN junctionfiles

echo "running JunctionDiff against each of the VN genomes"

# for each line in VN genomes list of junctionfiles, run junctiondiff
count=0
while read line           
do  
	if [[ $line != "" ]] # catch empty lines
	then
		count=$[$count+1]         
		${cgatools_binary} junctiondiff \
		--beta \
		--statout \
		--reference $crr \
		--junctionsA $junctions \
		--junctionsB $line \
		--scoreThresholdA $scoreThresholdA \
		--scoreThresholdB $scoreThresholdB \
		--distance $distance \
		--minlength $minlength 

		#concatenate all reports
		echo -e "report of run $count:\n----------------------" >> $output_report
		cat report.tsv >> $output_report
		echo "" >> $output_report

	
		#rename output file to junctions file for next iteration	
		rm $junctions
		mv "diff-$junctions" $junctions
		fi
done <  $VN_junctionfiles_list
	
cp $junctions $output_filtered



