#!/usr/bin/perl -w
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#NAME
#  corneymod -
#
#SYNOPSIS
#  corneymod [file]..
#
#REQUIRES
#
#DESCRIPTION
#  This is a quick kludge to massage the abc2win-style ABC files from the
#  corneymuses site into somewhat more standard ABC that's converted more
#  correctly by abc2ps and its clones.
#
#OPTIONS
#
#EXAMPLES
#
#FILES
#
#BUGS
#
#SEE ALSO
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu>
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

$| = 1;
$exitstat = 0;
($P = $0) =~ s".*/"";
$V = $ENV{"V_$P"} || $ENV{"D_$P"} || 2;	# Verbose level.

arg:
for $f (@ARGV) {
	unless (open(F,$f)) {
		print STDERR "$P: Can't read \"$f\" [$!]\n" if $V>0;
		next arg;
	}
	@ftune = <F>;			# Slurp up the tune
	close F;
	@gtune = ();
	($g = $f) =~ s/\.ABC$/x.abc/;	# Write data to this file name
	unless (open(G,">$g")) {
		print STDERR "$P: Can't write \"$g\" [$!]\n" if $V>0;
		next arg;
	}
	$intune = 0;
line:
	for $l (@ftune) {			# Run thru the tune
		$l =~ s/[\r\s\cZ]+$//;	# Trim away white stuff
		if ($l =~ /^K:/) {		# Have we reached the music?
			$intune = 1;		# Now we can start chewing on the music
		} elsif ($intune) {	
			if ($l =~ /(.*?)(\s*\!)$/) {	# ! lines treated as end-of-staff
				$l = $1;
				$l =~ s/\s*(:*\|)$/ $1/;	# add space before bar lines
			} elsif ($l =~ /(.*?)([:\|\s]+)$/) {	# add continue to other lines
				$l = "$1 $2 \\";
			} elsif ($l eq '') {
				print "$P: Blank line in $f\n" if $V>2;
				last line 
			}
			$l =~ s/\s*:\|\s*\|:\s*/ :: /;	# ! lines with double repeat
		}
		push @gtune, $l;				# Write the modified line.
	}
	$gtune[$#gtune] =~ s/\s*\\$//;		# No final continue
	for $l (@gtune) {
		print G "$l\n";
	}
	close G;
	print "Done: $g\n";
}

print "$P: Exit with status $exitstat.\n" if $V>1;
exit $exitstat;

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
