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

sub read_titles($$)
{
  my $file = shift;
  my $title = shift;

  open(TITLES, $file) || die "Reading $file: $!";
  while(<TITLES>)
  {
    my @a = split /[\t\n]/;
    $$title{$a[0]} = $a[1];
  }
  close TITLES;
}

sub get_title($$)
{
  my $title = shift;
  my $id = shift;

  my $result = $$title{$id};
  die sprintf "line %d: Undefined id %s\n", $., $id if (!defined($result));
  return $result;
}

die "Missing argument -dir=" unless defined($::dir);
die "Missing argument -titles=" unless defined($::titles);
my %title; 
read_titles $::titles, \%title;

my $file = $::dir . '/yref.txt';
open(SRC, $file) || die "Reading $file: $!";
while(<SRC>)
{
  s/\s+$//;
  if (!/^([\w\.]+)\.html#?([\w\.]*)/)
  {
    printf "line %d: %s\n", $., $_;
    next;
  }
  my $id = $1;
  my $title = get_title(\%title, $1);

  if (length($2) > 0)
  {
    $id = $2;
    $title = get_title(\%title, $2);
  }

  printf "<!ENTITY yref.%s SYSTEM \"yref/%s.xml\">\n", $id, $id;

   # printf "before [%s]\n", $_;
  # if (/^([\w\.]+)\.html#([\w\.]+)/)
  # {
   #  printf "aaa [%s]=[%s]\n", $1, $2;
  # }
}

