#!/usr/bin/perl

sub begin_taq {
    die if defined $ctext;
    $ctext='';
}
sub end_tac {
    $rtext= $ctext;
    $rtext =~ s/\\n/ /g; $rtext =~ s/^ +//; $rtext =~ s/ +$//; $rtext =~ s/ +/ /g;
    $atxt= "ATXT CDATA \L$rtext\E\n" unless defined $atxt;
}
sub end_taq {
    undef $atxt;
    &end_tac;
    print "$atxt($telm\n)$telm\n" or die $!;
    undef $ctext;
}
sub begin_ta {
    &begin_taq;
}
sub end_ta {
    &end_tac;
    print "$atxt($telm\n-$ctext\n" or die $!;
    undef $ctext;
    $trail= ")$telm\n";
}
sub endtrail {
    return unless defined $trail;
    print $trail or die $!;
    undef $trail;
}

while (<>) {
    chomp;
    if (s/^-//) {
        if (defined $ctext) {
            $ctext.= $_;
        } elsif (defined $trail && m/[^-0-9a-z\']/i) {
            print "-$`\n$trail-$&$'\n" or die $!;
            undef $trail;
        } else {
            print "-$_\n" or die $!;
        }
    } elsif (m/^AT CDATA /) {
        $atxt= "ATXT CDATA $'\n";
    } elsif (m/^AT IMPLIED$/) {
        undef $atxt;
    } elsif (m/^([()])(DEF|R)$/) {
        &endtrail;
        $telm= $2;
        $1 eq '(' ? &begin_ta : &end_ta;
    } elsif (m/^([()])(LAB|RQ)$/) {
        &endtrail;
        $telm= $2;
        $1 eq '(' ? &begin_taq : &end_taq;
    } else {
        &endtrail;
        print "$_\n" or die $!;
    }
}

close STDOUT or die $!;
