#!/usr/bin/perl

use Switch;
use MIDI;

my $filename = shift || die;
my $trackno = shift || 0;

my @tracks = `./track.pl $filename`;

if(scalar @tracks > 1 && $trackno == 0)
{
	print stderr "Multiple tracks detected, please choose one:\n";
	my $i=1;
	foreach my $track (@tracks)
	{
		print stderr "\t$i.) $track";
		$i++;
	}
	$trackno = <>;
	chomp $trackno;
}

my @lines = `./score.pl $filename $trackno | grep -P \"^note\" | awk '{printf \"%i|%i|%i\\n\", \$2,\$3,\$5}'`;

print &get_tempo($filename) . "\n";
print "0\n";
#print "Start\tLength\tNote\n";
foreach $line (@lines)
{
	$line =~ /([\d]*)[|]([\d]*)[|]([\d]*)/;
	#print "$1\t$2\t" . &convert_to_note($3) . "\n";
	print "$1\t$2\t$3\n";
}

print "-1\t-1\t-1\n";


sub convert_to_note
{
	my $note = shift || die "Send note!\n";
	my $octave = int($note/12);
	$note = $note % 12;

	switch($note)
	{
		case 0
		{
			$note="C";
		}
		case 1
		{
			$note="C#";
		}
		case 2
		{
			$note="D";
		}
		case 3
		{
			$note="D#";
		}
		case 4
		{
			$note="E";
		}
		case 5
		{
			$note="F";
		}
		case 6
		{
			$note="F#";
		}
		case 7
		{
			$note="G";
		}
		case 8
		{
			$note="G#";
		}
		case 9
		{
			$note="A";
		}
		case 10
		{
			$note="A#";
		}
		case 11
		{
			$note="B";
		}
	}

	return "$octave-$note";
}

sub get_tempo
{
	my $filename = shift || die "Need filename!\n";

#	This meta event sets the sequence tempo in terms of microseconds per quarter-note.
#
#	MICROSECONDS_PER_MINUTE = 60,000,000
#
#	BPM = MICROSECONDS_PER_MINUTE / MPQN
#	MPQN = MICROSECONDS_PER_MINUTE / BPM

	$cmd = "./score.pl $filename 0 | grep -a tempo";
	$v = `$cmd`;

	$v =~ /[\w]* [\w]* ([\d]*)/;
	return $1;
}

