#!/bin/sh

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

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

while getopts mxyd:i: optname; do
	case "$optname" in
	m)
		metronome=1;;
	x)
		extclock=1;;
	y)
		sendrt=1;;
	d)
		device=$OPTARG;;
	i)
		input=$OPTARG;;
	esac
done
shift $(($OPTIND - 1))
if [ "$#" != "1" -o -z "$1" ]; then 
	usage;
fi

exec midish -b <<EOF
songimportsmf "$1"
if "$device" {
	if "$input" {
		devattach 0 "$device" wo
	} else {
		devattach 0 "$device" rw
	}
	if $extclock == 1 {
		devsetmaster 0
	}
	if $sendrt {
		devsendrt 0 1
	}
}
if "$input" {
	devattach 1 "$input" ro
	filtnew myfilt
	filtdevmap myfilt 1 0
	songsetcurfilt myfilt
}
metroswitch $metronome
songplay
EOF
