#!/usr/bin/perl
#
#NAME
#  abcmedley - combine abc tunes into medley page
#
#SYNOPSIS
#  abcmedley "Title" file..
#
#DESCRIPTION
#  Read a list of abc files (or passage from stdin), and write output that is
#  a  titled medley.  The title will be at the top of the first page, and the
#  titles of the tunes will be converted to part names.  Also, we modify  the
#  X: lines, making an X:1 title section plus sequentially numbered X: parts.
#
#  If the title is the name of a file, it will be read and used for  the  X:1
#  part  of  the  medley.  It probably shouldn't contain music.  If the title
#  isn't a file name, we will generate an X:1 initial portion of  the  output
#  with the minimum needed to satisfy abc2ps.
#
#  We then read the tune files, converting their T: titles to P:  part names.
#  Only  the  first  title  will  be  used,  because  abc2ps refuses to print
#  multiple part names for a single tune.
#
#HEADERS
#  As a special kludge, you may include M and L header fields on the  command
#  line, and they will override the corresponding lines in the files. This is
#  mostly used to convert between C| and 2/4 time.
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu>

$| = 1;
$V = 1;
for $arg (@ARGV) {
	if (-f $arg) {
		push @files, $arg;
	} elsif ($arg =~ /^M:(.*)/) {
		$Mhdr = $1;
	} elsif ($arg =~ /^L:(.*)/) {
		$Lhdr = $1;
	} elsif (!$Title) {
		$Title = $arg;
	} else {
		print STDERR "$0: Unknown arg \"$arg\" ignored.\n";
	}
}
$Title = 'Medley' unless defined $Title;
($hdr1 = "$Title.hdr") =~ s/\s+//g;
($hdr2 = "hdr/$Title.hdr") =~ s/\s+//g;
$X = 0;	# Number of parts we've seen so far.

print "Exists: $hdr1\n" if -f $hdr1 && $V>1;
print "Exists: $hdr2\n" if -f $hdr2 && $V>1;

if  ( -f $hdr1 ) {			# Header file exists in current dir?
	open(T,$hdr1) ||
		die "$0: Can't read \"$hdr1\" [$!]\n";
	while (<T>) {print}
} elsif  ( -f $hdr2 ) {		# Header file exists in hdr dir?
	open(T,$hdr2) ||
		die "$0: Can't read \"$hdr2\" [$!]\n";
	while (<T>) {print}
} else {
	print "X: $X\n";		# Generate title lines.
	print "T: $Title\n";
	print "K: C\n\n";
}

file:
for $file (@files) {
	unless (open(F,$file)) {
		print STDERR "$0: Can'd read \"$file\" [$!]\n";
		next file;
	}
line:
	for $line (<F>) {
		if ($line) {
			if ($line =~ s/^(X:\s*)(\d*)\s*//) {
				if ($2 > $X) {$X = $2} else {++$X}	# New part encountered.
				print "\nX: $X\n";
				next line;
			} elsif ($line =~ /^(T:)\s*(.*)/) {	# Title.
				if (!$P{$X}) {
					$P{$X} = $2;
					$T = "P: $2";	# Convert to part name.
				} else {
					$P{$X} .= " ($2)";
					$T .= " ($2)";	# Convert to part name.
				}
				next line;
			} elsif ($line =~ /^(M:)\s*(.*)/) {
				$line = "M:$Mhdr\n" if $Mhdr;
			} elsif ($line =~ /^(L:)\s*(.*)/) {
				$line = "L:$Lhdr\n" if $Lhdr;
			} else {
				if ($T) {print "$T\n"; $T = ''}
			}
			print $line;
		}
	}
}
print "\n";
