#!/usr/bin/perl
#
# abcrenumber file...
#
# Dumb program to renumber the X:  lines in an ABC file.  This should
# be doable in one line using -pi.bak, but I couldn't get it to reset
# $X to 1 for each new file.  If anyone figures out how to make  this
# work correctly, let me know.
#
#AUTHOR John Chambers <jc@trillian.mit.edu> 2001/03/14

push @INC, '.', "$ENV{'HOME'}/sh";
require "Backup.pm";
$exitstat = 0;
$V = $ENV{'V_abcrenumber'} || 1;

file:
for $old (@ARGV) {
	$new = "$old.new";
	close OLD;		# Paranoia.
	close NEW;		# Paranoia.
	print STDERR "$old\n" if $V>1;
	unless (open(OLD,$old)) {
		print STDERR "$0: Can't read \"$old\" [$!]\n";
		++$exitstat;
		next file;
	}
	unless(open(NEW,">$new")) {
		print STDERR "$0: Can't write \"$new\" [$!]\n";
		++$exitstat;
		next file;
	}
	$X = 1;			# Tune counter resets for each file..
	for $l (<OLD>) {
		if ($l =~ /^(X:\s*)/) {
			$l = $1 . $X++ . "\n";	# Do it!
		}
		print STDERR $l if $V>2;
		print NEW $l;
	}
	close NEW;		# Make sure everything's written.
	&Backup($old);	# Rename input file.
	unless (rename($new,$old)) {
		print STDERR "$0: Can't rename \"$new\" to \"$old\" [$!]\n";
		++$exitstat;
	}
}

exit $exitstat;
