#!/usr/bin/perl -dw
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#NAME
#  abcdiff - Compare two ABC music files and show the differences.
#
#SYNOPSIS
#  ABCdiff file1 file2
#REQUIRES
#
#DESCRIPTION
# 
#
#OPTIONS
# The main options are saying which features of ABC notation to compare
#
#EXAMPLES
#
#FILES
#
#BUGS
#
#SEE ALSO
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu> 2017-8-12
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

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

$files = 0;
$comparenotes = 1;	# Default: compare the tunes' notes.

arg:
for $arg (@ARGV) {
	print STDERR "$P: arg=\"$arg\"\n" if $V>2;
	if (($flg,$opt) = ($arg =~ m/^([-+])(.*)/)) {
		print STDERR "$P: flg=\"$flg\" opt=\"$opt\" \n" if $V>2;
		if ($opt eq 'N') {
			$comparenotes = ($flg eq '+');
		} else {
			print STDERR "$P: flg=\"$flg\" opt=\"$opt\" not understood.\n" if $V>0;
		}
	} else {
		if ($files = 0 && -f $arg) {
			$file1 = $arg;
			print STDERR "$P: file1=\"$file1\"\n" if $V>2;
			++ $files;
			next arg;
		}
		if ($files = 1 && -f $arg) {
			$file2 = $arg;
			print STDERR "$P: file2=\"$file2\"\n" if $V>2;
			++ $files;
			next arg;
		}
		print STDERR "$P: arg=\"$arg\" not recognized.\n" if $V>2;
	}
}
if ($files != 2) {
	print STDERR "$P: files=$files; 2 required.\n" if $V>0;
	exit 1;
}

$diffs = &compare($file1,$file2);
print STDERR "$P: $diffs differences found.\n" if $V>1 || $exitstat;

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

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

sub compare {my $F='compare'; local($f1,$f2);
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# Compare the contents of two files.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	local($diffcnt) = 0;
	local(@tune1,@tune2,$val);
#	local $/;		# Slurp up entire files
	if (open(F1,$f1) {
		print STDERR "$F: Reading \"$f1\" ...\n" if $V>0;
		@tune1 = <F1>;	# Slurp up f1's contents
	} else {
		print STDERR "$F: Can't open \"$f1\" [$?]\n" if $V>0;
		return -1;
	}
	if (open(F2,$f2) {
		print STDERR "$F: Reading \"$f2\" ...\n" if $V>0;
		@tune2 = <F2>;	# Slurp up f2's contents
	} else {
		print STDERR "$F: Can't open \"$f2\" [$?]\n" if $V>0;
		return -2;
	}
	print STDERR "$F: Nothing found in \"$f2\"" if !$tune1 && $V>0;
	print STDERR "$F: Nothing found in \"$f2\"" if !$tune2 && $V>0;
	

}

