#!/bin/bash

# Greensleaves - Ancient traditional song
# Program: Copyright (C) 2002  Pedro Lopez-Cabanillas
# based on a public domain musical arrangement by Aaron Fontaine.
# Download the score from http://www.mutopiaproject.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

tune="45-64 4,\
      48-64-39-64 2, 4a-64-3b-64 4,\
      4c-64-3c-64 3, 4d-64 8, 4c-64 4,\
      4a-64-37-64 2, 47-64 4,\
      43-64-3b-64 3, 45-64 8, 47-64 4,\
      48-64-39-64 2, 45-64 4,\
      45-64-41-64 3, 44-64 8, 45-64 4,\
      47-64-40-64 2, 44-64 4,\
      40-64-34-64 2, 45-64 4,\
      48-64-39-64 2, 4a-64-3b-64 4,\
      4c-64-3c-64 3, 4d-64 8, 4c-64 4,\
      4a-64-37-64 2, 47-64 4,\
      43-64-3b-64 3, 45-64 8, 47-64 4,\
      48-64-39-64 3, 47-64 8, 45-64 4,\
      44-64-34-64 3, 42-64 8, 44-64 4,\
      45-64-39-64 2, 0 4,\
      45-64-39-64 2, 0 4,\
      4f-64-3c-64 2, 4f-64 4,\
      4f-64-3c-64 3, 4d-64 8, 4c-64 4,\
      4a-64-37-64 2, 47-64 4,\
      43-64-3b-64 3, 45-64 8, 47-64 4,\
      48-64-39-64 2, 45-64 4,\
      45-64-41-64 3, 44-64 8, 45-64 4,\
      47-64-40-64 2, 44-64 4,\
      40-64-34-64 2, 0 4,\
      4f-64-3c-64 2, 4f-64 4,\
      4f-64-3c-64 3, 4d-64 8, 4c-64 4,\
      4a-64-37-64 2, 47-64 4,\
      43-64-3b-64 3, 45-64 8, 47-64 4,\
      48-64-39-64 3, 47-64 8, 45-64 4,\
      44-64-34-64 3, 42-64 8, 44-64 4,\
      45-64-39-64 2, 0 4,\
      45-64-39-64 1,"

mididev="${1:-/dev/midi1}"
tempo=160 # bpm
declare -a TIME

function computetimes() {
	for T in 1 2 3 4 8; do
		let "ms = 2400000 / ( $T * $tempo )"
		TIME[$T]=$ms'e-4s'
	done
}

function playnotes() {
	if [ "$1" == "0" ]; then
		sleep ${TIME[$2]}
	else
		echo -ne '\x90\x'${1//-/'\x'} >&3
		sleep ${TIME[$2]}
		echo -ne '\x80\x'${1//-/'\x'} >&3
	fi
}

function playtune() {
	echo $1|while read -d, msg length; do
			playnotes $msg $length
		done
}


if [ -e $mididev -a -w $mididev ]; then
	echo
	echo "This is \"Greensleaves\", an ancient traditional song"
	echo "based on a public domain arrangement by Aaron Fontaine."
	echo "Download the score from http://www.mutopiaproject.org"

	hash sleep 
	computetimes
	exec 3>$mididev
	echo -ne '\xb0\x07\x40' >&3	# volume
	echo -ne '\xc0\x18' >&3		# instrument = guitar
	playtune "$tune" 
	exec 3<&-
	echo
else
	echo "`basename $0`: invalid MIDI device ($mididev)"
fi
