#!/usr/athena/bin/perl

$infile = $ARGV[0];
$left = $right = $newleft = $newright = 0;
$root = $top = 0;

open(MYINPUTFILE, $infile);
while(<MYINPUTFILE>)
   {
       my($line) = $_;
       chomp($line);
       $line =~ s/^ *//;  #remove spaces at beginning
       
       if ($line =~ m/^\(\(ROOT/) {
	   $top = 1;
	   $line =~ s/\(\(ROOT/\(ROOT/;  
       }
       if ($root == 0) {
	   $root = ($line =~ s/\(ROOT *//g);
	   if (!($root >= 1)) {$root = 0}  }
       
       # count number of left and  parens
       $newleft = ($line =~ s/\(/\(/g);
       $newright = ($line =~ s/\)/\)/g);
       
       $left = $newleft+$left;
       $right= $newright+$right;
       
       $line =~ s/^ \(/\(/g;

       if (($right >= $left+$root))
       {
	   #remove last right parens matching root parens:
	   $diff = $right-$left;
	   if ($diff>=1) {
	       chop($line);
	       if ($diff==2) {chop($line);}}

	   print "$line\n";
	   $left = $newleft = $right = $newright = 0;
	   $root = $top = 0;
       }
       else {
	   print "$line ";
	   $newleft = $newright = 0;
       }
   }
