#!/usr/bin/perl
#
# This program reads a file full of tune descriptions  and  generates
# initial  abc  files  from it.  This is rather ad hoc.  You probably
# don't want to use it.  It deals with a couple of file formats  that
# I've  found  and  want  to  convert,  but  probably  won't work for
# whatever files you're looking at now, so I won't say anything  more
# about it.

$| = 1;
$class = $title = $flag = $notes = '';

for $l (<>) {
	chomp $l;	# Requires perl 5
	if (!$l) {
		&outtune;
	} elsif (($flag,$text) = ($l =~ m'^([+-_=])\1\1\s(.*)')) {
		print "New: $flag $text\n" if $D;
		if ($flag eq '=') {
			$class = $text;
		} elsif (($t,$n) = ($text =~ m/([-\w\s'.]+)(.*)/)) {
			&outtune if $title;
			($title = $t) =~ s/\s+/ /g;
			($notes[$notes = 0] = $n) =~ s/^\s*\(\s*//;
		} else {
			print "--- Drop \"$l\"\n";
		}
	} else  {
		$l =~ s/^\s*//;
		if ($l) {
			$notes[++$notes] = $l;
		}
	}
}

exit 0;

sub outtune {
	if ($title) {
		$file = &ttl($title) . '.abc';
		if (-f $file) {
			print "$file \"$file\" already exists.\n";
		} elsif (!open(O,">$file")) {
			print "$file can't be created [$!]\n";
		} else {
			print O "X: 1\n";
			print O "T: $title\n";
			$notes[$notes] =~ s/\s*\)\s*$//;
			for ($n = 0; $n <= $notes; $n ++) {
				if ($x = $notes[$n]) {
					print O "N: $x\n";
				}
			}
			close O;
		}
	}
	$title = $flag = $notes = '';
}
 
sub ttl {
	local($t) = @_;
	$t =~ s/^the\s+//i;
	$t =~ s/\s+(\w)/\u$1/g;
	$t =~ s/[-\s'.]+//g;
	$t;
}
