#!/usr/bin/perl -ws
use strict;

my $EXTENSION = '.xml';

sub SimpleFile($$$;@)
{
  my $type = shift;
  my $name = shift;
  my $format = shift;

  my $file = "$::DIR/$type.$name$EXTENSION";
  open(FILE, ">$file") || die "Can't write to $file: $!";
  printf FILE $format, @_; 
  close FILE;
  printf "<!ENTITY %s.%s SYSTEM \"%s.%s$EXTENSION\">\n",
    $type, $name, $type, $name;
}

$::DIR = 'ulink' unless(defined($::DIR));
$::PROTO = 'http' unless(defined($::PROTO));

mkdir $::DIR, 0775;
( -d $::DIR ) || die "Can't create directory $::DIR.";

while(<>)
{
  next if m/^\s*#/;
  next unless m/^([^\s]+)\s+(.+)/;

  my $url = (substr($2, 0, 1) ne '&')
  ? sprintf("%s://%s", $::PROTO, $2)
  : $2
  ;

  # no "\n" at end of last line. this would show up as a space in SGML/XML. 

  SimpleFile 'url', $1, 
    "<ulink url=\"&%s.%s;\">&%s.%s;</ulink>",
    $::PROTO, $1, $::PROTO, $1
    ;
  SimpleFile 'note', $1,
    "<footnote id=\"note.%s\"><simpara>&url.%s;</simpara></footnote>\n",
    $1, $1
    ;
  printf "<!ENTITY %s.%s \"%s\">\n", $::PROTO, $1, $url;
}
