#!/bin/bash
#====================== Suppression fichiers temporaires
cleanup() {
if test -f "$fcsv"; then rm -f "$fcsv"; fi
if test -f "$step1"; then rm -f "$step1"; fi
if test -f "$step2"; then rm -f "$step2"; fi
}

argv=`getopt v $*`
set -- ${argv}
for i
do
	case "$i" in
	-v) shift
		VERBOSE="-v"
		echo "!! Verbose enabled" >&2
		;;
	--) shift;;
	esac
done

fmidi="$1"

#======================= TEST FICHIER
if test -z "$fmidi" -o ! -f "$fmidi"
then
	echo '?? ukeyify [-v] <file> ' >&2
	echo '!! (should) return a csv coded midi file uploadable to a U-Key keyboard' >&2
	cleanup
	exit 1
fi

#======================= CONVERSION CSV
step1=`mktemp /tmp/ukcsv-v1-XXXXXX`
step2=`mktemp /tmp/ukcsv-v2-XXXXXX`
fcsv=`mktemp /tmp/ukcsv-v3-XXXXXX`

if test -n "$VERBOSE"
then
	echo -e "!! fmidi=$fmidi\nfcsv=$fcsv" >&2
	echo -e "!! mktemp : $step1 $step2" >&2
fi

if ! midicsv $fmidi > $step1
then
	echo '?? ukeyify : incorrect input file' >&2
	cleanup
	exit 2
fi

#======================= Suppress track specific attributes  
## VAL="(^[2-9]|^1[0-9]), 0,|End_of_file|End_track"
VAL="((^[2-9]|^1[0-9]), 0, Start_track|Cue_point_t|Lyric_t|MIDI_port|Text_t|Title_t|Instrument_name_t|End_of_file|End_track|Copyright_t|Key_signature)"
grep -v -E "$VAL" $step1 > $step2  
if test -n "$VERBOSE"
then
	echo -e "!! deleted lines " >&2
	grep -E "$VAL" $step1 | xargs -i echo "!! {}" >&2
fi

#====================== Sort and rename all tracks to track #1
#this ensure a midi-0 format
### sort -s -n -t, --key=2,1 $step2 | sed -r -e 's/^([2-9]|1[0-9])/1/' -e 's/Header, [0-9]*, [0-9]*,/Header, 0, 1,/' > $fcsv
sort -s -n -t, --key=2,1 $step2 | sed -r -e 's/^([2-9]|1[0-9])/1/' > $fcsv

#====================== create a new tail with the correct tick
lasttick=`tail -1 $fcsv | sed -r -e 's/^[0-9]*, ([0-9]*),.*/\1/'`
echo "1, $lasttick, End_track" >> $fcsv
echo "0, 0, End_of_file" >> $fcsv

#====================== Add cme specific data with awk script
#determine where ukeyify.awk is located
awkfile=`dirname $0` 2> /dev/null
if test -z "$awkfile" 
then
	wuk=`which ukeyify`
	awkfile=`dirname $wuk` 2> /dev/null
fi
awkfile=${awkfile}/ukeyify.awk
if test -n "$VERBOSE"
then
	echo -e "!! awkfile is $awkfile " >&2
fi
if test ! -f $awkfile
then
	echo "?? ukeyify : can't find ukeyify awk file $awkfile" >&2
	cleanup
	exit 3
fi

awk -f $awkfile $fcsv

cleanup

exit 0
