#!/bin/bash

export IGDATA=/home/david/tmp/ncbi-igblast-1.0.0;

clonalType=${@:(-3):1}
html=${@:(-2):1}
imageDir=${@:(-1):1}
dataCount=`expr $# - 3`
inputData=${@:(1):dataCount}
dir="$(cd "$(dirname "$0")" && pwd)"
array=("$@")
echo "<html><h3>Progress</h3><table><tr><td>info</td></tr>" > $html
echo "<tr><td>-----------------------------------</td></tr>" >> $html

id=${inputData[0]}
forwardSlash="/"
mergerInput=()
count=0
for current in $inputData; do
    if [[ "$current" != *"$forwardSlash"* ]]; then
        id=$current
        count=0
        mergerInput+=($id)
        continue
    fi
    fileName=$(basename $current)
    convertedFileName="${fileName%.*}"
    convertedFileName="$PWD/$convertedFileName.converted"
	bash $dir/imgtconvert.sh $current $id $count $convertedFileName
	mergerInput+=($convertedFileName)
	count=$((count+1))
done
wait



echo "<tr><td>-----------------------------------</td></tr>" >> $html
echo "<tr><td>merging</td></tr>" >> $html

python $dir/igblastmerge.py ${mergerInput[*]}  --output $PWD/merged.txt

echo "<tr><td>done</td></tr>" >> $html
echo "<tr><td>-----------------------------------</td></tr>" >> $html
echo "<tr><td>plotting</td></tr>" >> $html


inputFile=$PWD/merged.txt
outputFile=$html
outputDir=$imageDir
mkdir $outputDir
Rscript --verbose $dir/RScript.r $inputFile $outputDir $outputDir $clonalType 2>&1
echo "<html>" > $outputFile
echo "<img src='VPlot.png'/>" >> $outputFile
echo "<img src='DPlot.png'/>" >> $outputFile
echo "<img src='JPlot.png'/>" >> $outputFile

samples=`cat $outputDir/samples.txt`
count=1
echo "<table border='1'>" >> $outputFile
for sample in $samples; do
	echo "<tr><td colspan='3' height='100'></td>" >> $outputFile
	echo "<tr><td colspan='3'><h1>$sample</h1></td></tr>" >> $outputFile
	echo "<tr><td><h2>V-D Heatmap:</h2></td><td><h2>V-J Heatmap:</h2></td><td><h2>D-J Heatmap:</h2></td></tr><tr>" >> $outputFile
	mv "$outputDir/HeatmapVD_$sample.png" "$outputDir/VD_$sample.png"
	echo "<td><img src='VD_$sample.png'/></td>" >> $outputFile
	mv "$outputDir/HeatmapVJ_$sample.png" "$outputDir/VJ_$sample.png"
	echo "<td><img src='VJ_$sample.png'/></td>" >> $outputFile
	mv "$outputDir/HeatmapDJ_$sample.png" "$outputDir/DJ_$sample.png"
	echo "<td><img src='DJ_$sample.png'/></td></tr>" >> $outputFile
	count=$((count+1))
done
echo "</table>" >> $outputFile
echo "<h1>$clonalType</h1>" >> $outputFile

echo "</html>" >> $outputFile
