#!/usr/bin/perl

use SGMLS::Refs;

$indent= 10;

sub sani {
    $data= $_[0];
    $data =~ s/\&/\&amp\;/g;
    $data =~ s/\</\&lt\;/g;
    $data =~ s/\>/\&gt\;/g;
    $data =~ s/\"/\&quot\;/g;
    $data;
}

sgml('start', sub {
    print "<html><head>\n" or die $!;
});
sgml('end', sub {
    &doctail;
    print "</html>\n" or die $!;
    close STDOUT or die $!;
});

sgml('<TITLE>', sub {
    print "<title>" or die $!;
});
sgml('</TITLE>', sub {
    print "$ctext</title>\n<body><h1>$ctext</h1>\n" or die $!;
    $ctext= '';
});
    
sub doctail {
    if (defined $ctail) {
        print $ctail or die $!;
        undef $ctail;
    }
}

sub output {
    print $ctext or die $!;
    $ctext= '';
}

sub begin_ss {
    my ($lev,$elem,$event) = @_;
    &output;
    print "<dl>\n" or die $! if !$lev;
    $ctr[$lev]++;
    $#ctr= $lev;
    $cspc= $lev;
    $chdr= join('.',@ctr);
    print "<dt><A name=\"n$chdr\">$chdr.\n<dd>\n" or die $!;
}
sub end_ss {
    my ($lev,$elem,$event) = @_;
    &output;
    print "</dl>\n" or die $! if !$lev;
}

for ($x=0;$x<=4;$x++) {
    $ss= 'S'x$x;
    $d= "sgml('<S$ss>', sub { &begin_ss($x,\@_); });".
        "sgml('</S$ss>', sub { &end_ss($x,\@_); }); 1;";
    eval $d or die $@;
}

sub a {
    my $z= $_[0]->attribute($_[1]);
    return defined $z ? $z->value : undef;
}

sgml('<PREDEF>', sub {
    my ($elem,$event) = @_;
    $txt= a($elem,'TXT');
    $ref{$txt}.= ',' if defined $ref{$txt};
    $ref{$txt}.= a($elem,'NUM');
});

sgml('<DEF>', sub {
    my ($elem,$event) = @_;
    &output;
    $txt= a($elem,'TXT');
    print "<A name=\"n$ref{$txt}\"><em>" or die $!;
});
sgml('</DEF>', sub {
    &output;
    print "</em></A>" or die $!;
});

sgml('<R>', sub {
    my ($elem,$event) = @_;
    &output;
    $txt= a($elem,'TXT');
    print "<A href=\"#n$ref{$txt}\">" or die $!;
});
sgml('<RQ>', sub {
    my ($elem,$event) = @_;
    &output;
    $txt= a($elem,'TXT');
    print "<A href=\"#n$ref{$txt}\">[$ref{$txt}]</A>" or die $!;
});
sgml('</R>', sub {
    &output;
    print "</A>" or die $!;
});

sub odata {
    my ($d,$event) = @_;
    $ctext.= &sani($d);
}

sgml('cdata', \&odata);
sgml('sdata', \&odata);
sgml('re', sub { $ctext.= "\n"; });
