#!/usr/bin/perl

# simplicit program that
# doubles time values of notes

use strict;
my %duration = (
    '\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 $lvl = 0; # 0 is outside music

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

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

    if ($lvl < 1) { # outside
	if (m/\\lyricmode/) {
	    # skip lyricmode
	} elsif (m/^[a-zA-Z]+ =.* (\\relative [a-h](e?s|is)?[,']?|\\figuremode) \{/) {
	    $lvl = 1;
	} elsif (m/\\new Dynamics \{/) {
	    $lvl = 1;
	}
    } else { # inside
	if (m/\\(key|time)/) {
	    # don't modify
	} else {
	    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 $dur = $3;
		    my $end = $5;

		    if (!defined($dur) || $dur eq "") {
			if ($old eq "") {
			    print "missing first duration: <$line>\n";
			}
		    } elsif ($dur eq $old) {
			# dupblicate duration, remove it
			$fld[$ix] = "$sta$end";
			$ch++;
		    } else {
			# different duration, let it be
			$old = $dur;
		    }
		}
		#print STDERR "$line: <$tok>\n";
	    }
	    if ($ch) {
		#print "in: <$line>\n";
		#print "ut: <  ", join(" ", @fld), ">\n";
		$line = "  " . join(" ", @fld);
	    }
	}
    }
    print "$line\n";
}
