#!/usr/bin/perl

use SGMLS::Refs;

$mw= 78;
$indent= 10;

sgml('start', '');
sgml('end', sub { close STDOUT or die $!; });

sgml('<TITLE>','');
sgml('</TITLE>', sub {
    $ctext =~ s/\n/ /g; $ctext =~ s/^\s+//; $ctext =~ s/\s+$//;
    $ind= (78-length($ctext))/2;
    print ' 'x$ind,uc($ctext),"\n" or die $!;
    print ' 'x$ind,'-'x length($ctext),"\n" or die $!;
});

sub output {
    $ctext =~ s/^\s+//;
    $ctext =~ s/\.\n/\.  /g;
    $ctext =~ s/\n/ /g;
    $ctext =~ s/\s+$//;
    $ctext= $chdr.$ctext;
    $chdr= '';
    while ($ctext =~ m/^(.{1,$mw})$/ ||
	   $ctext =~ m/^(.{1,$mw}) +/ ||
	   $ctext =~ m/^(.{1,$mw})/) {
	print $1,"\n" or die $!;
	$ctext= $';
	$ctext= (' 'x($indent)).$ctext if length $ctext;
    }
    $ctext= '';
}

sub begin_ss {
    my ($lev,$elem,$event) = @_;
    $ctr[$lev]++;
    $#ctr= $lev;
    &output;
    print "\n" or die $! if $lev<=1;
    $chdr= sprintf "%-${indent}s",join('.',@ctr).'.';
}
sub end_ss {
    &output;
}

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 { push(@texts,$ctext); $ctext=''; });
sgml('</DEF>', sub { $ctext= pop(@texts).uc $ctext; });

sub end_r {
    my ($elem,$event) = @_;
    $txt= a($elem,'TXT');
    if (!defined $ref{$txt}) {
	warn "ref $txt ?";
	$ref{$txt}= '?';
    } else {
        $num= $ref{$txt};
    }
    $ctext.= "[$num]";
}
sgml('</R>', \&end_r);
sgml('</RQ>', \&end_r);

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

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