#!/usr/bin/perl

use SGMLS::Refs;

$indent= 10;

sgml('start', sub {
    print "\@Doc \@Text \@Begin\n" or die $!;
});
sgml('end', sub {
    &doctail;
    print "\@End \@Text\n" or die $!;
    close STDOUT or die $!;
});

sgml('<TITLE>', sub { $ctext.= "\@RawCentredDisplay { {2.0 2.0} \@Scale { \@B {\n"; });
sgml('</TITLE>', sub { $ctext.= "} } }\n"; &output; });

sub doctail {
    if (defined $ctail) {
        print $ctail or die $!;
        undef $ctail;
    }
}

sub output {
    $ctext =~ s/\.\n/\.  /g;
    $ctext =~ s/\n/ /g;
    $ctext =~ s/([^.]\") +/$1 /g;
    $ctext =~ s/\"\"//g;
    if (defined $chdr) {
        &doctail;
        printf "//%.2fvx\n",1.0+2.0/($cspc*$cspc+2) or die $!;
        print "$chdr |2co {\n" or die $!;
        undef $chdr;
        $ctail= "\n}\n";
        $ctext =~ s/^\"\s+/\"/;
        $ctext =~ s/^\s+//;
    }
    $octext= '';
    while ($ctext =~ m/^(.{1,79}[^\n.])\" \"/) {
        $octext.= "$1\"\n\"";
        $ctext= $';
    }
    $octext.= $ctext;
    $octext =~ s/\"([-,.0-9a-zA-Z]+)\"/$1/g;
    print $octext or die $!;
    $ctext= '';
}

sub begin_ss {
    my ($lev,$elem,$event) = @_;
    $ctr[$lev]++;
    $#ctr= $lev;
    &output;
    $cspc= $lev;
    $chdr= join('.',@ctr).'.';
    $chdr= "\@CNP\n\@B{$chdr}" if !$lev;
}
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 { $ctext.= "\@B{"; });
sgml('</DEF>', sub { $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) = @_;
    $data =~ s/[\"\@]/\\$&/g;
    $data =~ s/ +/\"$&\"/g;
    $ctext.= "\"$data\"";
}

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