#!/bin/bash
# 
# Creates a wav file from dynamic transposition score
# using CSound
#
play=0 # set to 1 to start playing after making wav file
run() {
	cmd=$1
	echo "$cmd"
	eval "$cmd"
	if [ $? -ne 0 ]; then
		echo "Aborting ..."
		exit 1
	fi
}

if [ $# -lt 1 ]; then
	echo "Usage: $0 <dtt|dtm> [<m> <n> <s>]"
	echo "will convert a <dtt> or <dtm> file to sco and play"
	echo "<m> is a start measure to play"
	echo "<n> is the number of measures to play"
	echo "<s> is the number of beats preceeding the first measure"
	exit 1
fi
m=1
n=0
s=0
if [ $# -gt 1 ]; then
	m=$2
fi
if [ $# -gt 2 ]; then
	n=$3
fi
if [ $# -gt 3 ]; then
	s=$4
fi
i=$1
if [ ! -f $i ]; then
	echo "ERROR: Cannot read '$i'"
	exit 1
fi
d=$(dirname "$0")
b=$(basename "$i")
f=${b%.*}
h="$d/${f}-head.sco"
if [ ! -f $h ]; then
	echo "ERROR: Cannot read '$h'"
	exit 1
fi
sco=${f}.sco
orc="$d/${f}.orc"
wav=${f}.wav
tmp=${f}-tmp.sco
echo "Reading $i and writing to $sco"
if [ $n -ne 0 ]; then
	echo "start measure: m=$m"
	echo "measures to play: n=$n"
	echo "off-beats: s=$s"
	run "$d/dtc -s $s -m $m -n $n $i $tmp"
else
	run "$d/dtc $i $tmp"
fi
run "cat $h $tmp > $sco"
echo "Reading $orc $sco and writing to $wav"
run "csound --output=$wav $orc $sco"
if test $play -eq 1
then
if [[ $OSTYPE == "linux-gnu"* ]]; then
	player=play
elif [[ $OSTYPE == "darwin"* ]]; then
	player=afplay
else
	echo "Cannot play on this platform: '$OSTYPE'"
	exit 1
fi
run "$player $wav"
fi
