#!/usr/bin/env perl
use strict;
use warnings;

use lib '/Users/gene/sandbox/MIDI-Util/lib';
use MIDI::Util; # https://metacpan.org/release/MIDI-Util
use lib '/Users/gene/sandbox/Music-Cadence/lib';
use Music::Cadence; # https://metacpan.org/release/Music-Cadence

my $max = shift || 16;

my @notes = qw/ C4 D4 E4 F4 G4 A4 B4 C5 /;

my @leaders = qw/ 1 2 4 7 /;

my $score = MIDI::Util::setup_score( bpm => 100 );
 
my $mc = Music::Cadence->new( octave => 4 );

for my $i ( 1 .. $max ) {
    my $note1 = $notes[ int rand @notes ];
    my $note2 = $notes[ int rand @notes ];

    $score->n( 'qn', $note1, $note2 );

    if ( $i % 4 == 0 ) {
        my $chords = $mc->cadence(
            type    => 'half',
            leading => $leaders[ int rand @leaders ],
        );
        $score->n( 'hn', @$_ ) for @$chords;
    }
}

my $chords = $mc->cadence( type => 'deceptive' );
$score->n( 'hn', @$_ ) for @$chords;

$chords = $mc->cadence( type => 'plagal' );
$score->n( 'hn', @$_ ) for @$chords;

$score->write_score("$0.mid");
