#!/bin/perl -w
use MIDI; # ...which "use"s MIDI::Track et al
use DBI;
use Data::Dumper;
use warnings;
use strict;

my $dbfile = shift || die("No File");
my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","");


# Get time:
my $sth = $dbh->prepare("SELECT clk FROM GeneralInfo");
$sth->execute();
my $result = $sth->fetch;
my $timebase = $result->[0];

$sth = $dbh->prepare("SELECT p.PhaseName, p.PhaseBegin, p.PhaseEnd, t.TBank 
                      FROM Phases p, Transactions t
                      WHERE (p.PhaseName = 'WR' OR p.PhaseName = 'RD')
                      AND p.Transact = t.ID
                      ORDER BY PhaseBegin");
$sth->execute();

my @score;

push(\@score, ['text_event', 0, 'Sonification']);
push(\@score, ['patch_change', 0, 1, 8]);
push(\@score, ['instrument_name', 0, 81]);

while(my @row = $sth->fetchrow_array)
{
    #print $row[0]."\t".$row[1]."\t".$row[2]."\t".$row[3]."\n";
    # ('note', starttime, duration, channel, note, velocity)
    my $note;
    if($row[3] == 0)
    {
        $note = 72; #C
    }
    elsif($row[3] == 1)
    {
        $note = 75; #Eb
    }
    elsif($row[3] == 2)
    {
        $note = 76; #E
    }
    elsif($row[3] == 3)
    {
        $note = 77; #F
    }
    elsif($row[3] == 4)
    {
        $note = 78; #Gb
    }
    elsif($row[3] == 5)
    {
        $note = 79; #G
    }
    elsif($row[3] == 6)
    {
        $note = 82; #Bb
    }
    elsif($row[3] == 7)
    {
        $note = 84; #C
    }
    push(\@score, ['note', $row[1]/$timebase, 1, 1, $note, 96]);
}

#print Dumper(\@score);

#MIDI::Score::dump_score( \@score );

my $track = MIDI::Track->new;
my @events = @{MIDI::Score::score_r_to_events_r( \@score )};

$track->events(@events);
#$track->dump();

my $opus = MIDI::Opus->new({ 'format' => 0,  'ticks' => 240,  'tracks' => [ $track ] });
$opus->write_to_file('cowbell.mid');


