#!/usr/local/bin/perl -w
#
# Expand references to bibliography:
# replaces [[xxx]] with
# <a href="url-of-xxx">[xxx]</a>
#
# url-of-xxx is constructed from the refsrc file (an
# HTML file with biblio-entries), and the anchors found
# in that file.
#
# Biblio-entries in refsrc must have the form:
# < ...name="ref-yyy"...> or < ...id="ref-yyy"...>
#
# Option -r gives the prefix for anchors, otherwise refsrc
# is used as prefix.
#
# Bert Bos <bert@w3.org>
# $Id: addcite,v 2.4 2006-10-09 18:55:52 ihickson Exp $

use Getopt::Std;
use lib 'bin';
use utils;

$PROG = substr($0, rindex($0, "/") + 1);
$USAGE = "Usage: $PROG [-r prefix] refsrc [file [output]]\n";

my %refanch;			# Holds cite keys and anchors
my %refclass;			# Holds class of reference (normref,...)


# Read the bibliography $_[0], store keys and anchors in hash table $refs
sub read_refs {
    my $buf = readfile($_[0]);
    while ($buf =~ /(<[^>]+\b(?:name|id)\s*=\s*[\"\']?(ref-([^\s\"\'>]*))[\"\']?.*?>)/sio) {
	$buf = $';
	$stag = $1;
	$key = $3;
	$refanch{$key} = $2;

	# Check for class
	if ($stag =~ /\bclass\s*=\s*[\"\']?([^\s\"\'>]+)[\"\']?/) {
	    $refclass{$key} = $1;
	}
    }
}


### main

getopts('r:') || die $USAGE;
if ($#ARGV >= 0) {$refsrc = $ARGV[0]; shift;} else {die $USAGE;}
if ($#ARGV >= 0) {$file = $ARGV[0]; shift;} else {$file = '-';}
if ($#ARGV >= 0) {$output = $ARGV[0]; shift;} else {$output = '-';}
if ($#ARGV >= 0) {die $USAGE;}

my $prefix = defined $opt_r ? $opt_r : $refsrc;

read_refs($refsrc);

my $buf = readfile($file);

open(OUT, ">$output") or die "$PROG: cannot write to file $output\n";

# Loop over input, looking for [[xxx]] or [[-xxx]]
while ($buf =~ /\[\[(-)?(\S+?)\]\]/so) {
    $buf = $';
    print OUT $`;
    $firstletter = $1;
    $key = $2;
    if (! defined $refanch{$key}) {
	print STDERR "$PROG: no biblioentry found for [[$key]]\n";
	print OUT $&;
    } else {
	if (defined $firstletter or !defined $refclass{$key}) {
	    $class = "informref";
	} else {
	    $class = $refclass{$key};
	}
	print OUT "<a href=\"$prefix#$refanch{$key}\" rel=\"biblioentry\" ";
	print OUT "class=\"noxref\"><span class=\"$class\">[$key]</span></a>";
    }
}

print OUT $buf;			# Final part

close(OUT);

