#!/bin/sh -- # -*- perl -*- -w
eval 'exec perl -S $0 ${1+"$@"}'
    if 0;

@ctm=<STDIN>;

### Look for entity tags in alt, but not wholly contained
for ($i=0; $i<=$#ctm; $i++){
#    print "i = $i  $ctm[$i]";
    if ($ctm[$i] =~ /<(enamex|timex|numex)/i){
	### Search forward for the next end tag
	$j = $i;
	$inalt = -1;
	while ($j <= $#ctm && $ctm[$j] !~ /<\/(enamex|timex|numex)>/i){ 
	    if ($ctm[$j] =~ /<ALT_BEGIN/i){
		die "Whoa! big error, to begin alts in as ne tag"
		    if ($inalt != -1);
		$inalt=$j ;
	    } elsif ($inalt >= 0) {
		$inalt = -1 if ($ctm[$j] =~ /<ALT_END/i);
	    }
	    $j++; 
	}
	if ($inalt >= 0){
	    #print "TAG $inalt\n"; foreach $x($i .. $j){print "    $ctm[$x]"}
	    
	    ### find the alt_end
	    $alt_end = $j;
	    while ($alt_end <= $#ctm && $ctm[$alt_end] !~ /<alt_end>/i){ 
		$alt_end++;
	    }

	    ### Remember where to restart
	    $restart = $i;
	    
	    ### Find the alts to implode data to 
	    for ($k=$alt_end; $k>=$i; $k--){
		if ($ctm[$k] =~ /<(alt|alt_begin)>/i){
		    splice(@ctm,$k+1,0,@ctm[$i .. $inalt-1]);
		}
	    }
	    splice(@ctm,$i,$inalt-$i);
	    $i = $restart - 1;
	}

    } else {
	;
    }
}

### Make sure all entities are in alts
$in=0;
$inalt=0;
for ($i=0; $i<=$#ctm; $i++){
    if ($inalt == 1){
	print $ctm[$i];
	$inalt=0 if ($ctm[$i] =~ /<ALT_END>/i);
    } else {
	if ($ctm[$i] =~ /<ALT_BEGIN>/i){
	    $inalt=1;
	    print $ctm[$i];
	} elsif ($inalt == 0 &&
		 $ctm[$i] =~ /<(enamex|timex|numex)[^<>]+>[^<>]*$/i){
	    die "Error: syncronization error \$in = 1" if ($in == 1);
	    @a = split(/\s+/,$ctm[$i]);
	    print "$a[0] $a[1] * * <ALT_BEGIN>\n";
	    print "$ctm[$i]";
	    $in=1;
	} elsif ($inalt == 0 && $in == 1 &&
		 $ctm[$i] =~ /[^<>]*<\/(enamex|timex|numex)>[^<>]*$/i){
	    die "Error: syncronization error \$in = 0" if ($in == 0);
	    print $ctm[$i];
	    print "$a[0] $a[1] * * <ALT_END>\n";
	    $in=0;
	} else {
	    print $ctm[$i];
	}
    }
}

print "$a[0] $a[1] * * <ALT_END>\n" if ($in == 1);

exit;

