package xm::pfe::dpansaddfooter;
use strict;
use xm::o;
use xm::pfe::dpansreflist;

sub DESC
{"
   scan the Annex F of the Draft Proposal On Forth - Html Version - and
   add references to the footer of the words pages generated as present
   in the input file. Otherwise, the output is the same as the input.
"};

sub per_DPANSITEM
{
    my ($ann,$in,$end,$dpansdef) = @_;

    my $dpanslink = "";
    $in =~ s{ (<DPANS:?LINK(?:\s[^<>]*)?>) 
		  ((?:.(?!</DPANS:?LINK[\s>]))*.) 
                  (</DPANS:?LINK(?:\s[^<>]*)?>) }
    { $dpanslink = $2; $1.$2.$3 }gsex;

    my $dpansxref = "";
    $in =~ s{ (<DPANS:?XREF(?:\s[^<>]*)?>) 
		  ((?:.(?!</DPANS:?XREF[\s>]))*.) 
                  (</DPANS:?XREF(?:\s[^<>]*)?>) }
    { $dpansxref = $2; $1.$2.$3 }gsex;

    $dpanslink =~ s:</a>:</a href>:g;

    $$dpansdef{"&quot;$dpansxref&quot;"} = $dpanslink
	if length $dpansxref and length $dpanslink;

    return "";
}

sub build_dpansref
{
    my ($in, $dpansdef) = @_;

    $in =~ s{ (<DPANS:?ITEM(?:\s[^<>]*)?>) 
		  ((?:.(?!</DPANS:?ITEM[\s>]))*.)
                  (</DPANS:?ITEM(?:\s[^<>]*)?>) }
    {
        per_DPANSITEM ($1,$2,$3,$dpansdef);
    }gsex;

    return $dpansdef;
}

sub apply_dpansref
{
    my ($in, $dpansdef) = @_;

    # print STDERR "<!apply hash=", scalar %$dpansdef, ">";

    $in =~ s{     (<MAKEWORDREF(?:\s[^<>]*)?>)
		      ((?:.(?!</MAKEWORDREF[\s>]))*.)
		      (<INTOWORDLIST(?:\s[^<>]*)?> FORTH/ ) 
		      ((?:.(?!</MAKEWORDREF[\s>]))*.)
		      (<CSTRWORDREF(?:\s[^<>]*)?>)       
		      ((?:.(?!</CSTRWORDREF[\s>]))*.)
		      (</CSTRWORDREF(?:\s[^<>]*)?>) }
    {
	my $def = "";
	if (exists $$dpansdef{"&quot;$6&quot;"})
	{
	    $def = " (dpANS".$$dpansdef{"&quot;$6&quot;"}.") ";
	}else{
	    $def = " (dpANS".$$dpansdef{$6}.") " if exists $$dpansdef{$6};
	}

	# print STDERR (length $def ? "[$6]" : "($6)");
	$1.$2.$3.$4.$def.$5.$6.$7
    }gsex;

    return $in;
}

sub DO
{
    my $in = shift;
    my $dpans = "";
    $dpans = $o{dpans} if exists $o{dpans};
    if (! -e $dpans)
    {
	if (-d "dpans")	{
	    $dpans = "dpans";
	}elsif (-d "dpans94") {
	    $dpans = "dpans94";
	}elsif (-d "../dpans") {
	    $dpans = "../dpans";
	}elsif (-d "dpans94") {
	    $dpans = "../dpans94";
	}else{
	    return $in; # do nothing;
	}
    }

    my $dpansxml = xm::pfe::dpansreflist::mklist($dpans);
    return $in if not length $dpansxml;

    my %dpansdef;
    return &apply_dpansref($in, &build_dpansref($dpansxml, \%dpansdef));
}

sub ARGS { return xm::o::args_stdin(@_,DESC); }
sub main { return DO(xm::o::args_stdin(@_,DESC)); }

1; # perl module