#!/usr/local/bin/perl
# Make a database of defined references.
# Syntax of database:
# <Reference-key>;<anchor>;<file>;<n-or-i>
# Where <n-or-i> is "n" for normative and "i" for
# informative.
# Ian Jacobs - lehors@w3.org
# $Id: mkrefdb,v 1.4 2006-10-09 18:55:52 ihickson Exp $

$PROGNAME = substr($0, rindex($0, "/") + 1);

if (($_ = $ARGV[0], /^-r/) && $ARGV[0]) {
    shift;
    $realpath = $ARGV[0];
    shift;
} else {
    $realpath = ();
}

if ($#ARGV < 1) {
    print STDERR "Usage: $PROGNAME [-r realpath] references outdb\n";
    exit 1;
} else {
    $reff = $ARGV[0];
    shift;
    $outdb = $ARGV[0];
    shift;
    if (! $realpath) {
	$realpath = $reff;
    }
}

# copy file in memory
sub readfile {
    $buf = "";
    if (!open(INPUT, $_[0])) {
	print STDERR "$PROGNAME Error: Cannot open file: $_[0]\n";
	return;
    }
    while (<INPUT>) {
	$buf .= $_;
    }
    close(INPUT);
}

### main

# search for anchors. 
$anchorpre="ref-";
$pattern = "name=\"$anchorpre([^\"]*?)\"";
$normpattern = "class=\"([^\"]*?)\"";
open(DBASE, "> $outdb");
readfile($reff);
$_ = $buf;
$hfil = $realpath;
$hfil =~ s/\.src/\.html/;
while (/$pattern.*?$normpattern/sio) {
    $key = uc($1);
    print DBASE "$key;$anchorpre$key;$hfil;$2\n";
    $_ = $';	
}

close(OUTPUT);
close(DBASE);

