#!/usr/bin/perl -w
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#NAME
#  tuneinfo -
#
#SYNOPSIS
#  tuneinfo [file]..
#
#REQUIRES
#
#DESCRIPTION
#  Read a lot of ABC tunes, and write selected info to stdout.
#
#  What info is printed is likely to vary from time to time ...
#
#OPTIONS
#
#EXAMPLES
#
#FILES
#
#BUGS
#
#SEE ALSO
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu> 2012
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

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

for $arg (@ARGV) {
	print "$P: ARG: $arg ...\n" if $V>2;
	if (-f $arg) {
		print "$P: File $arg ...\n" if $V>1;
		&onefile($arg);
	} else {
		print STDERR "$P: No file \"$arg\"\n" if $V>0;
	}
}

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

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

sub onefile {my $f = shift;
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	local($line,$tunes,$intune,$inhdr,$X,$T,$O,$K);
	$tunes = 0;		# Count the tunes read
	if (open(F,$f)) {
		$intune = 0;	# Whether we're reading a tune.
		$inhdr = 0;		# Whether we're in the header section of a tune.
	} else {
		print STDERR "$P: ### Can't read \"$f\" [$?]\n" if $V>0;
		return 0;
	}
	$X = $T = $O = $K = '';
line:
	while ($line = <F>) {
		$line =~ s/[\r\s]+$//;
		if ($line =~ /^X:\s*(\d+)(.*)/) {		# X: index
			$X = $1;
			$inhdr = 1;
			print STDERR "$P: X=\"$X\"\n" if $V>1;
			next line;
		}
		if ($line =~ /^T:\s*(.*)/) {		# T: Title
			if ($1 && !$T) {
				($T = $1) =~ s/\s*\[.*\]//;	# Strip out bracketed text
				$T =~ s"\s#.+$"";			# Strip off comments
				print STDERR "$P: T=\"$T\"\n" if $V>1;
			} else {
				print STDERR "$P: T=\"$1\" ignored.\n" if $V>1;
			}
			next line;
		}
		if ($line =~ /^K:\s*(.*)/) {		# K: Key
			if ($1 && !$K) {
				$K = $1;
				print STDERR "$P: K=\"$K\"\n" if $V>1;
			} else {
				print STDERR "$P: K=\"$1\" ignored.\n" if $V>1;
			}
			next line;
		}
		if ($line =~ /^O:\s*(.*)/) {		# O: Origin
			$O = $1;
			print STDERR "$P: O=\"$O\"\n" if $V>1;
			next line;
		}
	}
	print STDERR "$P: Done with \"$f\"\n" if $V>1;
	printf "%22s %7s  $T\n", $O, $K;
	return $tunes;
}

