#!/bin/sh

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

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

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

for i; do
	case "$i" in
	-x)
		extclock=1; shift;;
	-y)
		sendrt=1; shift;;
	-m)
		metronome=1; shift;;
	-a)
		append=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
if $append {
	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
tracknew rec
songsetcurtrack rec
songrecord
songexportsmf "$1"
END
