#!/usr/bin/perl
#
# NAME
#   abcsplit
#
# SYNOPSIS
#   abcsplit [file]..
#
# DESCRIPTION
#   This program reads thru its input, looking for abc music.  When it
#   finds a chunk of music, it creates a file derived from the  title,
#   and writes the music to the file.
#
#   If  there  is  already  a file by the given name, we add '_' and a
#   number to the name.
#
# SEE ALSO
#   abcjoin
#
# BUGS
#   Each time this is run, an  entirely  new  set  of  files  will  be
#   created.   Maybe we should compare each tune to the existing file,
#   and if they are identical, not write  anything.   But  that's  for
#   future release.
#
# AUTHOR
#   John Chambers <jc@trillian.mit.edu>

$| = 1;
($me = $0) =~ s'.*/'';
$D = $ ENV{"D_$me"} || $ENV{"V_$me"} || $ENV{"T_$me"} || 0;
&inittune;

for $l (<>) {
	chomp $l;
	if (!$l) {
		print "Got blank line.\n" if $D;
		&outtune if $lines > 1;
		next;
	}
	if ($l =~ /^X:/) {
		print "Got X: line.\n" if $D;
		&outtune if $lines > 1;
		$tune[$lines++] = "$l\n";
		next;
	}
	if ($l =~ /^T:\s*(.*)/) {
		if (!$T) {
			$T = $1;
			$T =~ s/^the\s+//i;	# Delete initial definite article.
			$T =~ s/^an?\s+//i;	# Delete initial indefinite article.
			$T =~ s/[^A-Za-z0-9]//g;	# Delete non-alphanum chars.
		}
		$tune[$lines++] = "$l\n";
		next;
	}
	if ($l =~ /^X:/) {
		print "Got \"$l\"\n" if $D;
		next;
	}
	if ($lines > 0) {
		print "Line $lines is \"$l\"\n" if $D;
		$tune[$lines++] = "$l\n";
	}
}
&outtune if $lines > 1;
exit 0;

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Initialization for a new tune.
sub inittune {
	@tune = ();
	$lines = 0;
	$T = '';
}

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Output one tune.
sub outtune {
	local($i) = 0;
	local($t) = "$T.abc";
	while (-f $t) {
		print "Tune \"$t\" exists already.\n" if $D;
		$i ++;
		$t = $T . '_' . $i . '.abc';
	}
	print "Tune \"$t\" ...\n" if $D;
	if (open(T,">$t")) {
		print T @tune;
		close T;
	} else {
		print STDERR "$0: Can't write \"$t\" [$!]\n";
	}
	&inittune;
}
