package xm::cblocks;
use xm::o;
use strict;

sub DESC 
{" 
  look into the actual C-text and mark pairs of { and }. These are
  then called <CBLK>

  rem: the blocks have depthnumbers.
"}

sub x_off
{
    my $in = shift;
    
    $in =~ s{\{} {\&\#7B\;}sg;
    $in =~ s{\}} {\&\#7D\;}sg;
    
    return $in;
}

sub x_on
{
    my $in = shift;
    
    $in =~ s{\&\#7B\;} {\{}sg;
    $in =~ s{\&\#7D\;} {\}}sg;
    
    
    return $in
}

sub DO
{
    my $in = shift;
    my $d;
    
    # every brace inside CPRE/CSTR/CCHR/CDOC and their derivatives shall 
    # not count - shut them off here
    for $d (qw{ CPRE CSTR CCHR CDOC })
    {
        $in =~ s{<($d[A-Z]*)(\s[^<>]*)?>(?!<\1[\s>]) 
		   ((?:.(?!</?\1[\s>]))*.) (</\1(?:\s[^<>]*)?>) } 
            { "<$1$2>".x_off($3).$4 }gsex;
    }
    
    # ready - so let's scan for the brace-pairs...
    
    my $i = 10;
    while ( 
        $in =~ s{ ( \{ [^\{\}]* \} ) }
            { ++$i; "<CBLK $i>".x_off($1)."</CBLK $i>" }gsex
    ) { };
    
    # done. Now move inner CBLKs to CBLKS - makes parsing easier 
    # for later modules that handle just full CBLK areas.
    
    while (
        $in =~ s{ (<CBLK\s*\d+>) ((?:.(?!</?CBLK\s*\d*>))*.?) 
            		<(CBLK\s*\d+)> ((?:.(?!</?CBLK\s*\d*>))*.?) </\3> }
                { $1.$2."<CBLKS>".$4."</CBLKS>" }gsex
    ) { };
    
    $in =~ s{(</?)CBLK\s*\d+>} {$1."CBLK>"}gsex;  # clean numbers out
    
    # finally revert to braces as literals...
    
    return x_on($in);
} 

sub ARGS { return    xm::o::args_stdin(@_,DESC); }
sub main { return DO(xm::o::args_stdin(@_,DESC)); }

1;