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

use MIDI::Drummer::Tiny;
use MIDI::Util qw(setup_score midi_format);
use Music::Duration::Partition;
use Music::Scales;
use Music::Voss qw/ powers /;

my $size = shift || 4;
my $max  = shift || 8;
my $bpm  = shift || 90;

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;
#use Data::Dumper;warn(__PACKAGE__,' ',__LINE__," MARK: ",Dumper$motif);exit;

    my ( $scale, $genf ) = get_genf( 'A', 5, 'minor' );

    for my $i ( 1 .. $max ) {
        my @notes = map { $scale->[ $genf->($_) % @$scale ] } 0 .. @$motif - 1;
#use Data::Dumper;warn(__PACKAGE__,' ',__LINE__," MARK: ",Dumper\@notes);exit;

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

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

sub get_genf {
    my ( $note, $octave, $type ) = @_;

    my @scale = map { $_ . $octave } get_scale_notes( $note, $type );
    @scale = midi_format(@scale);

    my $seed = [ map { sub { int rand 2 } } @scale ];
    my $genf = powers( calls => $seed );

    return \@scale, $genf;
}
