#!/usr/bin/perl -w
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#NAME
#  abctextfix - Adjustments to %%text etc. inside ABC files
#
#SYNOPSIS
#  abctextfix [file]..
#
#REQUIRES
#
#DESCRIPTION
# For now, the only adjustment is to search out %%begintext sections, and add
# '%% ' to the start of each text line. This protects the text from buggy ABC
# "player" programs that interpret the text as "music".
#
# A side effect of this program is to trim away trailing white space, which
# includes CR (\r) characters as well as spaces and tabs.  And each file's
# write time is changed to now. ;-)
#
#OPTIONS
#
#EXAMPLES
#
#FILES
#
#BUGS
# This script doesn't (yet) work as a filter, i.e., if called with no files
# on the command line, it doesn't read from STDIN and write to STDOUT. Maybe
# I'll fix this some day, when I need it.
#
#SEE ALSO
#
#AUTHOR
# John Chambers <jc@trillian.mit.edu> 2013-1-25
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

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

$files = 0;	# Number of files processed.

foreach $arg (@ARGV) {
	if (-f $arg) {
		&onefile($arg);
		++$files;
	}
}

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

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
sub onefile {
	local($file) = @_;
	local($intext,$line,@tune);
	unless (open(F,$file)) {
		print STDERR "$P: ### Can't read \"$file\" [$!]\n" if $V>0;
		return;
	}
	print "$file ...\n" if $V>1;
	while ($line = <F>) {
		$line =~ s/[\r\s]+$//;
		if ($line =~ /^%%begintext/) {
			$intext = 1;
			push @tune, $line;
		} elsif ($line =~ /^%%endtext/) {
			push @tune, $line;
			$intext = 0;
		} elsif ($intext) {
			if ($line =~ /^%%/) {	# Don't apply this fix twice.
				push @tune, $line;
			} else {
				push @tune, "%% $line";	# Comment out the line.
			}
		} else {
			push @tune, $line;
		}
	}
	if (open(F,">$file")) {
		for $line (@tune) {
			print F "$line\n";
		}
	} else {
		print STDERR "$P: ### Can't write \"$file\" [$!]\n" if $V>0;
	}
	close F;
}
