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

# Plot the number of notes for each song.

#use lib map { "$ENV{HOME}/sandbox/$_/lib" } qw(Music-BachChoralHarmony); # local author libs
use Music::BachChoralHarmony;

#my $data_file = 'share/jsbach_chorals_harmony.data'; # local author files
#my $key_title = 'share/jsbach_BWV_keys_titles.txt';  # "
my $bach = Music::BachChoralHarmony->new(
#    data_file => $data_file,
#    key_title => $key_title,
);
my $songs = $bach->parse();

my %score;
for my $id ( keys %$songs ) {
    my $sum = 0;

    for my $event ( @{ $songs->{$id}{events} } ) {
        $sum += count_ones( $event->{notes} );
    }

    $score{$id} = $sum;
}

use Chart::Points;
my $chart = Chart::Points->new( 1000, 400 );

$chart->set(
    title         => 'Number of Notes by Chorale',
    pt_size       => 10,
    legend_labels => ['No.'],
    x_label       => 'Chorale BWV',
    y_label       => 'Number of notes',
    x_ticks       => 'vertical',
    precision     => 0,
    grid_lines    => 1,
    colors        => {
        grid_lines => 'gray',
    },
);

my @sorted = sort { $score{$a} <=> $score{$b} } keys %score;
$chart->add_dataset( map { $songs->{$_}{bwv} } @sorted );
$chart->add_dataset( map { $score{$_} } @sorted );

$chart->png("$0.png");

sub count_ones {
    my ($bits) = @_;
    $bits =~ tr/0//d;
    return length $bits;
}
