#!/bin/bash
input=$1
output=$2 
outDir=$3
mkdir $outDir
EOL=$4
mismatches=$5
partial=$6
name=$(basename "$7")
ext="${name##*.}"
name="${name%.*}"
prefix=$name"_"
dir="$(cd "$(dirname "$0")" && pwd)"

for ((i=8;i<=$#;i=i+2))
do
	j=$((i+1))
  echo -e "${!i}\t${!j}" >> $outDir/barcodes.txt
done

cd $outDir
echo "$3"
result=`$dir/sff2fastq $input | $dir/fastx_barcode_splitter.pl --bcfile $outDir/barcodes.txt --prefix "$prefix" --suffix ".fastq" --$EOL --mismatches $mismatches --partial $partial`
echo "$result" | tail -n +2 | sed 's/\t/,/g' > output.txt
echo "<html><head><title>$name demultiplex</title></head><body><table border='1'><thead><tr><th>ID</th><th>Count</th><th>FASTQ</th><th>FASTA</th></tr></thead><tbody>" >> $output
ls
while IFS=, read barcode count location
	do
		if [ "total" == "$barcode" ] 
		then 
			echo "<tr><td>$barcode</td><td>$count</td><td></td><td></td></tr>" >> $output
			break
		fi
		file=$name"_"$barcode
		cat $file.fastq | perl -e '$i=0;while(< >){if(/^\@/&&$i==0){s/^\@/\>/;print;}elsif($i==1){print;$i=-3}$i++;}' > $file.fasta
		cat $file.fastq
		echo "<tr><td>$barcode</td><td>$count</td><td><a href='$file.fastq'>$file.fastq</a></td><td><a href='$file.fasta'>$file.fasta</a></td></tr>" >> $output
done < output.txt
echo "</tbody></body></html>" >> $output
