#!/usr/bin/perl -w
#
# Quickie for extracting the tune number from the Waifs tunes
# in T/TuneName.abc and linking them to X/0123.abc

$! = 1;

@files = glob("T/*.abc");

file:
for $f (@files) {
	unless (open(F,$f)) {
		print "$f\tis unreadable ($!)\n";
		next file;
	}
	$X = $N = $S = $T = '';
	line:
	while (<F>) {
		if (/^X:\s*(\d+)/) {
			$X = $1;
		} elsif (/^T:\s*(.*)\s*\(#*(\d+)(-*[A-F]*)\)/) {
			$T = $1;
			$N = $2;
			$S = $3;
			last line;
		} else {
		}
	}
	close F;
	$N = $X unless $N;	# Use X: number if not given.
	$M = $N if $N > $M;	# Note the maximum.
	unless ($N) {
		print "$f\tcontains no tune number.\n";
		next file;
	}
	$t = sprintf("X/%04d$S.abc",$N);
	if (-f $t) {
		print "$f\tnot linked; $t already exists.\n";
	} else {
		if (link($f,$t)) {
			print "$f\t-> $t\n";
		} else {
			print "$f\t-> $t failed ($!)\n";
		}
	}
}

for ($i = 1; $i <= $M; $i++) {
	$n0 = sprintf("X/%04d.abc",$i);
	$nA = sprintf("X/%04d-A.abc",$i);
	unless (-f $n0 || -f "$nA") {
		print "### $n0 missing.\n";
	}
}
