#!/import/perl/bin/perl
# tunes2html.pl ../ascii/dt.toc ../ascii/dt.tunetoc > DigiTradTunes.html

$tocfile = shift;
open(TOC,$tocfile) || die;

while (<TOC>) {
    chop;
    ($songid, $songnum, $line, $start, $end, $tunecodes, $title, $cats) = split(/;/);
    $songid =~ tr/ //d;
    $Songs{$songid} = 1;
    $tunecodes =~ s/^%//;
    $tunecodes =~ tr/ //d;
    foreach $tuneid (split(/%/,$tunecodes)) {
	$songs = $TuneSong{$tuneid};
	$songs .= ";" if $songs;
	$TuneSong{$tuneid} = "$songs$songid:$title";
    }
}

while (<>) {
    chop;
    ($tuneid,$line,$start,$end,$title)=split(/;/);
    $tuneid =~ tr/ //d;
    $title = $tuneid unless $title;
    $sortkey = $title;
    $sortkey =~ s/^\W+//;
    $sortkey =~ tr/a-z/A-Z/;
    $sortkey =~ s/^THE |^A //i;
    $sortkey =~ s/^\W+//;
    push(@ttoc, "$sortkey;$tuneid;$title");
}

print <<EOF;
<TITLE>Digital Tradition Folk Song Tunes</TITLE>
<H1>Digital Tradition Folk Song Tunes</H1>
<P>
Select a first letter to see tune titles,
or go to the
<A HREF="AboutDigiTrad.html">Digital Tradition</A>
Database to
<A HREF="/digitrad/titles">Search Titles</A>
or <A HREF="/digitrad">Search Full Text</A>.
<UL>
EOF

foreach (sort @ttoc) {
    ($sortkey,$tuneid,$title)=split(/;/);
    $flet = $sortkey;
    $flet =~ /^(....[\S]*)/;
    $fword = $1;
    $fword =~ s/,$//;
    $fword =~ tr/a-z/A-Z/;
    $flet = substr($flet,0,1);
    $flet = "0-9" if $flet =~ /[0-9]/;

    if ($flet ne $letter) {
	&finish if defined $fname;
	$letter = $flet;
	$saveword = $fword;
	$fname = "dt-tunes-$letter.html";
	open(OUT,">$fname") || die;
	print OUT <<EOF;
<TITLE>Digital Tradition Tunes starting with $letter</TITLE>
<H1>Digital Tradition Tunes starting with $letter</H1>
<P>
Select a tune,
or go to the <A HREF="/digitrad/titles">Digital Tradition Database</A>
to enter a search pattern.
<UL>
EOF
    }
    $prevword = $fword;
    print OUT "<LI><A HREF=\"/digitrad/tune=$tuneid\">$title</A>";
    @songs = split(/;/, $TuneSong{$tuneid});
    if ($#songs < 0) {
	$f = " ";
	@songs = ($tuneid), $f = "*" if $Songs{$tuneid};
	printf STDERR "unreferenced tune: %-12s %1s %s\n", $tuneid, $f, $title;
    }
    if ($#songs == 0) {
	($sid,$stitle) = split(/:/,$songs[0],2);
	print OUT " - <A HREF=\"/digitrad/song=$sid\">[words]</A>";
    } elsif ($#songs > 0) {
	print OUT "\n<UL>";
	foreach $s (@songs) {
	    ($sid,$stitle) = split(/:/,$s,2);
	    print OUT "\n<LI>words: <A HREF=\"/digitrad/song=$sid\">$stitle</A>";
	}
	print OUT "\n</UL>";
    } else {
	print OUT " - [unreferenced]";
    }
    print OUT "\n";
}

&finish;
print "</UL>\n";

sub finish {
    print(OUT "</MENU>\n");
    close(OUT);
    print "<LI><A HREF=\"$fname\">$saveword .. $prevword</A>\n";
}
