#!/usr/bin/perl

open (TOCFILE, "$ARGV[0]");
$DIR = `dirname "$ARGV[0]"`;
chomp($DIR);

$trackno = 1;
while (<TOCFILE>) {
    if (/^FILE /) {
	if ($file = `find "$DIR" -type f -not -empty -maxdepth 1 -regex ".+/0*$trackno\\..+\\.flac"`) {
	    chomp($file);
	    $file = substr($file, 0, length($file) - 4) . "wav";
	    $_ = $file;
	    if (/.+\/([^\/]+)$/) {
		print "FILE \"$1\" 0\n";
	    } else {
		print "FILE \"$file\" 0\n";
	    }
	} else {
	    warn "Can't find file for track $trackno";
	    print $_;
	}
	$trackno++;
    } else {
      print $_;
    }
}

close(TOCFILE);

die "No tracks in TOC file $ARGV[0]" if ($trackno == 1);
