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

# Use local libraries
use lib map { "$ENV{HOME}/sandbox/$_/lib" } qw( MIDI-Drummer-Tiny MIDI-Util Music-Duration Music-Duration-Partition );

use List::Util qw/ shuffle /;
use MIDI::Drummer::Tiny;
use MIDI::Util qw(setup_score);
use Music::Duration::Partition;
use Music::Scales;

my $size = shift || 4;
my $max  = shift || 8;
my $bpm  = shift || 90;
my $mod  = shift || 2; # Default: alternating

my $score = setup_score( bpm => $bpm );

$score->synch(
    \&melody,
    \&beat,
);

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

sub beat {
    my $d = MIDI::Drummer::Tiny->new( bpm => $bpm, score => $score );

    for my $n ( 1 .. $size * $max * 2 ) {
        $d->note( $d->quarter, $d->closed_hh );
    }
}

sub melody {
    my $mdp = Music::Duration::Partition->new(
        size => $size,
#        pool => [qw/ twn thn tqn ten tsn /],
        pool => [qw/ qn en sn /],
    );

    my $motif = $mdp->motif;

    my @scale = get_scale_MIDI( 'A', 3, 'pminor' );

    for my $i ( 1 .. $max ) {
        my @notes = map { $scale[ int rand @scale ] } 0 .. @$motif - 1;

        my @phrase = $i % $mod ? @$motif : shuffle @$motif;

        $mdp->add_to_score($score, \@phrase, \@notes);

        $score->r('wn');
    }
}
