#!/usr/bin/perl

# simplicit program that
# doubles time values of notes

use strict;
my %scale = (
    '\maxima' => '\maxima',
    '\longa'  => '\maxima',
    '\breve'  => '\longa',
    1   => '\breve',
    2   =>  1,
    4   =>  2,
    8   =>  4,
    16  =>  8,
    32  => 16,
    64  => 32,
    128 => 64,
);

#print join(" ", @ARGV), "\n";
my $ln = 0; # next bar number
my $lvl = 0; # 0 is outside music

while (<>) {
    #print;
    chomp;
    my $line = $_;
    my $lnum = "";

    s/{/ { /;
    s/}/ } /;
    tr/ \t\n\r\f/ /s;
    s/ $//;
    #s/%.*//;

    if ($lvl < 1) { # outside
	$ln = 1;
	if (m/^[a-zA-Z]+ =.* (\\relative [a-h](e?s|is)?[,']?|\\figuremode) \{/) {
	    $lvl = 1;
	    #print STDERR "$lvl $ln: $line\n";
	} elsif (m/\\new Dynamics \{/) {
	    $lvl = 1;
	}
    } else { # inside
	my $ch = 0;
	my @fld = split;
	for (my $ix = 0; $ix < @fld; $ix++) {
	    my $tok = $fld[$ix];
	    if ($tok eq "{") { $lvl++; next }
	    if ($tok eq "}") { $lvl--; next }
	    if ($tok =~ /^[\\=0-9\"\|%#]/) { next; }
	    #if ($tok =~ /\./) { next; } # scheme variables can have dots
	    if ($tok =~ /^[A-QS-Zi-qt-z\(\)\?]/) { next; } # probably markup text
	    if ($tok =~ /^[A-Za-z]{4,}/) { next; } # probably markup text
	    if ($tok eq "--") { next; } # probably lyrics separator
	    if ($tok eq "_") { next; } # probably lyrics extender


	    if ($tok =~ /^([srRa-h](is|es|s)?[,']*)(\d+|\\breve|\\longa|\\maxima)?(.*)$/ ) {
		my $sta = $1;
		my $num = $3;
		my $end = $4;

		if (!defined($num) || $num eq "") { next; }
		my $nv = $scale{$num};
		if (!defined($nv)) { next; }

		my $ns = "$sta$nv$end";
		$fld[$ix] = $ns;
		$ch++;
		#if ($tok =~ /^r/) { print "<$sta/$num/$nv/$end>\n"; }
		#if ($tok =~ /\./) { print "<$sta/$num/$nv/$end>\n"; }

		next;
	    }
	    print STDERR "$line: <$tok>\n";
	}
	if ($ch) {
	    #print "in: <$line>\n";
	    #print "ut: <  ", join(" ", @fld), ">\n";
	    $line = "  " . join(" ", @fld);
	}
    }
    print "$line\n";
}
