#!/bin/sh

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

extclock=0
sendrt=0
input=""
device=$MIDIDEV
metronome="off"
tempo=0
append=0
pos=0

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

exec midish -b <<EOF
if $append {
	import "$1"
}
g $pos
if "$device" {
	if "$input" {
		dnew 0 "$device" wo
	} else {
		dnew 0 "$device" rw
	}
	if $extclock == 1 {
		dclkrx 0
	}
	if $sendrt {
		dclktx {0}
	}
}
if "$input" {
	dnew 1 "$input" ro
	fnew myfilt
	fmap {any {1 0..15}} {any {0 0..15}}
}
m $metronome
tnew rec
xnew sx
r
export "$1"
EOF
