#!/usr/bin/perl -w

use strict;

my $barlim = 5;

sub trim() {
    s/%.*//;
    tr/ \t\n/ /s;
    s/^ //;
    s/ $//;
}

sub fixlyr($);
my $lyr = "";
my $hyp = 0;
my $lstchr = "";
sub fixlyr($) {
    my $str = shift;
    return if (!defined($str) || $str eq "");
    if ($str =~ m/^"([^"]+)"([0-9.\/*]*) ?(.*)$/) {
    } elsif ($lstchr eq '"') {
	# ignore
    } else {
	print "NOMATCH: $str\n";
	return;
    }
    my $tst = $1;
    my $num = $2;
    my $rest = $3;
    $tst  = "" unless ($tst);
    $num  = "" unless ($num);
    $rest = "" unless ($rest);
    if ($rest eq '"') {
	$rest = "";
	$lstchr = '"';
    }
    if ($tst =~ m/^(-|­) $/) {
	# ignore this
	if ($hyp == 0) {
	    $lyr .= " -- ";
	    $hyp = 1;
	}
	$tst = "";
    }
    if ($tst =~ m/^\r$/) {
	# ignore this
	$tst = "";
    }
#    print "\n";
#    print "$str\n";
#    print "<$tst|$num|$rest>\n";
    if ($tst eq "") {
	# do nothing
    } elsif ($tst =~ m/ $/) {
	$lyr .= $tst;
	$hyp = 0;
    } else {
	if ($tst =~ m/ $/) {
	    $lyr .= "${tst}-- ";
	} else {
	    $lyr .= "$tst -- ";
	}
	$hyp = 0;
    }
    fixlyr($rest);
    if (length($lyr) > 50) {
	print "  $lyr\n";
	$lyr = "";
    }
}


my $bars = 0;
my $state = "";
my $line = "";
while (<>) {
    if ($state eq "") {
	if (m/^track(.)channel(.) = \\lyricmode/) {
	    print "l\l$1 = \\lyricmode {\n";
	    $state = "lyric";
	} elsif (m/^track(.)channel(.) = \\relative c/) {
	    print "m\l$1 = \\relative c {\n";
	    $state = "music";
	} else {
	    # ignore data
	}
    } elsif ($state eq "lyric") {
	trim();
	next if (m/^$/);
	if (m/^}/) {
	    if ($lyr) {
		print "  $lyr\n";
		$lyr = "";
	    }
	    print "}\n";
	    $state = "";
	} elsif (m/^\|$/) {
	    # ignore this
	} elsif (m/^"/) {
	    fixlyr($_);
	}
    } elsif ($state eq "music") {
	trim();
	next if (m/^$/);
	if (m/^}/) {
	    print "  $line |\n" if ($line);
	    print "}\n";
	    $state = "";
	    $bars = 0;
	} elsif (m/^\|$/) {
	    $line = join(" ", $line, "|");
	    $bars++;
	    if ($bars == $barlim) {
		print "  $line\n";
		$line = "";
		$bars = 0;
	    }
	} else {
	    $line = join(" ", $line, $_);
	}
    }
}
