#!/bin/sh

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

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

while getopts amxyd:i: optname; do
	case "$optname" in
	a)
		append=1;;
	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
if $append {
	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
tracknew rec
songsetcurtrack rec
sysexnew sx
songsetcursysex sx
songrecord
songexportsmf "$1"
EOF
