#!/bin/bash

if [ $# -lt 2 ] ; then
echo "Usage: $0 [-s] LISTFILENAME OUTPUTDIR"
exit 1
fi

retainstructure=0

while [ $# -gt 2 ] ; do
case $1 in
-d) retainstructure=1 ; shift 1 ; echo here;;
*) shift 1 ;;
esac
done

listfile="$1"
echo listfile "$listfile"
outputdir="$2"


while read infile; do
	if [ "$infile" -a -f "$infile" ]; then
		before="$(date +%s)"
		echo "_____________________________________________________"
		echo " "
		echo Processing file "$infile"
		echo " "
		if [ $retainstructure -eq 0 ]; then
			pathandfile=`basename "$infile"`
		else
			pathandfile="`echo "$infile" | egrep -o '[^/]*/[^/]*/[^/]*$'`"
			echo pathandfile "$pathandfile"
		fi
		outfile="$outputdir"/"$pathandfile".txt
		
		logfile=_logfiles/"$pathandfile".log
		chromafile=_chromadata/"$pathandfile".csv
		
		mkdir -p "`dirname "$outfile"`"
		
		echo "[sonic annotator] ..."
		helper=n		
		VAMP_PATH=. ./sonic-annotator -d vamp:matthiasm:nnls_chroma:simplechord -w csv --csv-stdout "$infile" | cut -d ',' -f 2- |
		while read line; do			
			# echo "$line"
			if [ $helper = y ]; then
				echo "$oldstart" `echo "$line" | cut -d ',' -f 1` "$oldchord"
			fi
			oldstart=`echo "$line" | cut -d ',' -f 1`
			oldchord=`echo "$line" | cut -d ',' -f 2 | sed 's/"//g'`
			helper=y
		done > "$outfile"
		after="$(date +%s)"
		elapsed_seconds="$(expr $after - $before)"
		echo "  -->" time elapsed: $elapsed_seconds seconds
		echo " "
	else if [ ! "$infile" ]; then echo ...; fi
	fi		
done < "$listfile"
