#!/usr/bin/perl

# a simple script to replace all @G ... @`other' regions with 
# @= ... @>@; lines
# comments are allowed at the end of the lines.
# only one style of comments is accepted: /* ... */. note that these are not
# output

open FILE, "$ARGV[0]" or die "Cannot open input file $ARGV[0]\n";
open FILEOUT, ">$ARGV[1]" or die "Cannot open output file $ARGV[1]\n";

$state = 0;
while (<FILE>) {

    $inline = $_;


    if ( $inline =~ m/^\@G(.*)$/ ) { # @G detected, this line is part of the `other language' region

	$inline = $1; $state = 1; 
	if ( not $inline ) { $inline = " Start \@\@G (generic) language section"; }
	printf FILEOUT "\@q%s\@>\n", "$inline";

    } elsif ( $inline =~ m/^\@[\scp].*$/ ) { # @`other' detected, so `other language' region is over

	$state = 0;
	printf FILEOUT "%s", "$inline"; 

    } elsif ( $inline =~ m/^\s*\@=.*$/ ) { # @= detected, just copy the line

	printf FILEOUT "%s", "$inline"; 

    } elsif ( $inline =~ m/^\@g(.*)$/ ) { # @`other' detected, so `other language' region is over

	$inline = $1; $state = 0; 
	if ( not $inline ) { $inline = "End generic language section"; }
	printf FILEOUT "\@q%s\@>\n", "$inline";

    } elsif ( $state == 1 ) {

	if ( $inline =~ m/\/\*/ ) {
	    
	    $inline =~ m/^(.*\S|)\s*(\/\*.*\*\/)\s*$/;
	    $string = $1; $comment = $2;
	    
	} else {
	    
	    $inline =~ m/^(.*)$/;
	    $string = $1; $comment = "";
	    
	}

	if ( $string ) {

	    printf FILEOUT "\@=%s\@>\@;", "$string";

	} else {

	    printf FILEOUT "\@=%s\@>\@;", " ";

	}

	if ( $comment ) {

	    printf FILEOUT "%s", "$comment";

	}

	printf FILEOUT "%s", "\n";

    } else {
	
	printf FILEOUT "%s", "$inline";
	
    }
    
}
