#!/bin/sh

mydir=`dirname "$0"`
infile="$1"
outfile="$2"

if [ t"$infile" = "t" ] || [ t"$outfile" = "t" ]; then
    echo "Usage: $0 infile.wav outfile.txt"
    exit 2
fi

mkdir -p "$mydir"/out || exit 1

inbase=`basename "$infile"`
inbase=${inbase%.*}

echo "Processing input WAV file $infile, writing results to $outfile..." 1>&2

# Run the Silvet plugin.
#
# 1. Run the plugin. This will produce an output file
# out/${inbase}.csv

VAMP_PATH="$mydir" sonic-annotator \
    -t "$mydir"/silvet-piano.ttl \
    -w csv \
    --csv-separator ' ' \
    --csv-one-file "$mydir/out/$inbase.csv" \
    --csv-force \
    "$infile" || exit 1

# 2. Check the output file exists

poutfile="out/${inbase}.csv"
if [ ! -f "$poutfile" ]; then
    echo "output file $poutfile not found! bailing out"; exit 1
fi

# 3. Convert the format. Sonic Annotator produced
#
# starttime duration freq note label
#
# while we want
#
# starttime endtime freq

cat "$poutfile" | awk '{ print $1, $1+$2, $3 }' > "$outfile"

echo "Done, output is in $outfile"
