#!/bin/sh

function usage {
	echo "usage: smfplay [-mxy] [-d device] [-i device] midifile"
	exit 2
}

set -- `getopt xymd:i: $* 2>/dev/null`
if test $? != 0; then
	usage;
fi

extclock=0
sendrt=0
input=""
device=$MIDIDEV
metronome=0
tempo=0

for i; do
	case "$i" in
	-x)
		extclock=1; shift;;
	-y)
		sendrt=1; shift;;
	-m)
		metronome=1; shift;;
	-d)
		device=$2; shift; shift;;
	-i)
		input=$2; shift; shift;;
	--)
		shift; break;;
	esac
done

if [ "$#" != "1" -o -z "$1" ]; then 
	usage;
fi

midish -b << END
songimportsmf "$1"
if "$device" {
	devattach 0 "$device"
	if $extclock == 1 {
		devsetmaster 0
	}
	if $sendrt {
		devsendrt 0 1
	}
}
if "$input" {
	devattach 1 "$input"
	filtnew myfilt
	filtdevmap myfilt 1 0
	songsetcurfilt myfilt
}
metroswitch $metronome
songplay
END
