#!/usr/bin/perl

$|=1;

sub begin_RULES { @ctr=(); $ctext= ''; $chdr= ''; }
sub end_RULES { %ref= %def; $indent= 10; }

sub begin_DEF { push(@texts,$ctext); $ctext=''; }
sub end_DEF {
    $ctext =~ s/\\n/ /g;
    $def{$ctext}= join('.',@ctr);
    $ctext= pop(@texts)."\U$ctext";
}

sub begin_R { push(@texts,$ctext); $ctext=''; }
sub end_R {
    $ctext =~ s/\\n/ /g;
    if ($indent && !defined($ref{$ctext})) {
	warn "ref $ctext ?";
	$ref{$ctext}= '?';
    }
    $setref= '['.$ref{$ctext}.']';
    $ctext= pop(@texts).$ctext;
}

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

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

sub end_ss {
    &output;
}

while (<>) {
    chomp;
    if (s/^-//) {
	if (length($setref) && m/[^-0-9a-z\']/i) {
	    $_= $`.$setref.$&.$';
	    $setref= '';
	}
	$ctext.= $_;
    } elsif (m/^[()]/) {
	$elefn= $';
	$oc= $& eq '(' ? 'begin_' : 'end_';
	if ($elefn =~ m/^S+/) {
	    $tslev= length($elefn);
	    $elefn= $oc.'ss';
	} else {
	    $elefn= $oc.$elefn;
	}
	&$elefn;
    } elsif (s/^\#//) {
    } elsif (s/^C//) {
    } else {
	die "$_ ?";
    }
}

close STDOUT or die $!;
