package Util;

sub protect {
  local ($_) = @_;
  my ($prot, @close) = ('', '');
  my ($l, $m, $r);

%verb = ( '(' => '@<(>', ')' => '@<)>', '<' => '@[<]', '>' => '@[>]',
          '[' => '@{[}', ']' => '@{]}', '{' => '@({)', '}' => '@(})',
          '@' => '@(@)' );
%otherside = ( '(' => ')', '<' => '>', '[' => ']', '{' => '}' );

 SPECIAL:
  while (/[\Q()<>[]{}@\E]/g) {
    ($l, $m, $_) = ($`, $&, $');  #'
    $prot .= $l;
    ($m eq $close[$#close]) && ($prot .= $m, pop(@close), next SPECIAL);
    ($m ne '@') &&       ($prot .= $verb{$m}, next SPECIAL);
    (/^\w*([\Q(<[{\E])/) && ($prot .= "\@$&", $_ = $', #'
                             push(@close, $otherside{$1}), next SPECIAL);
    # $prot .= $verb{'@'};
    $prot .= '@';
  }
  $prot . $_ . join("", @close);   
}
1;