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

# Roman numeral analysis of the most common bass lines.

use Music::BachChoralHarmony;
use Music::ToRoman;

my $size = shift || 4;

my $bach = Music::BachChoralHarmony->new;
my $songs = $bach->parse();

my %score;

# Process each song for key and chord
for my $song ( sort keys %$songs ) {
    my $key = $songs->{$song}{key};

    # Get the scale name
    my $name = $key =~ /M/ ? 'major' : 'minor';
    $key =~ s/_?M//i;

    my $mtr = Music::ToRoman->new(
        scale_note => $key,
        scale_name => $name,
        chords     => 0,
    );
#    print "SONG: $song in $key $name\n";

    # The last seen roman group
    my $last;
    my @seen;

    # Turn the bass into a roman representation
    for my $event ( @{ $songs->{$song}{events} } ) {
        my $bass = $event->{bass};

        # Get the roman representation based on the scale position
        my $roman = $mtr->parse($bass);
#        print "\tBASS: $bass, ROMAN: $roman\n";

        # Tally the seen group
        push @seen, $roman;

        if ( @seen == $size ) {
            my $group = join ',', @seen;
            @seen = ();
            $score{ $last . ' ' . $group }++ if $last;

            # Tally the bigram
            $last = $group;
        }
    }
}
use Data::Dumper;warn(__PACKAGE__,' ',__LINE__," MARK: ",Dumper[map{"$_: $score{$_}"}sort{$score{$a}<=>$score{$b}}keys%score]);
