#! /usr/local/bin/perl -w
# Nastiness to start converting Pascal into C
# Optimized SOLELY for hacking a particular file. Caveat, uh, Runnor.
# Waider, November 1997

$structname=$unionname="";
#$deb=1;
$indent=0;

while(<>)
{
	if ( $deb )
	{
		$com=$_;
		chomp($com);
		print "/* $com */\n";
	}

	s/\s*\(\*(.*)\*\)/\/*$1*\//g;
	print,next if /^\s+$/;

	if ( !$gotconst )
	{
		if ( !$constdone )
		{
			$gotconst = /^\s*CONST\s*$/;
			next;
		}
	}

	if ( $gotconst )
	{
		if ( s/^\s*([A-Za-z0-9_]+)\s*=\s*(.*);\s*$/#define $1 $2\n/ )
			{
				print;
				next;
			}
	}

 	if ( !$gottype )
	{
		if ( $gottype = /^\s*TYPE\s*$/ )
		{
			$constdone = 1;
			next;
		}
	}
	
 	if ( /END;/ )
	{
		print " "x$indent;
		print "} ";
		print $structname if $structname ne "";
		print $unionname if $unionname ne "";
		print ";\n";
 		$indent -=4;
		$structname = $unionname = "";
		next;
	}

	if (/^(.*)\s*=\s*RECORD\s*$/i)
	{
		$structname="$1";
		next;
	}

	if ( $structname ne "" && $unionname eq "")
	{
		print " "x$indent;
		if (/CASE/)
		{
			$unionname=$structname;
 			$structname="";
			print "typedef union {\n";
		}
		else
		{
			print "typedef struct {\n";
		}
		$indent+=4;
		next;
	}

	if ( $unionname )
	{
		$ind=" "x$indent;
		if ( s/^\s*([0-9])+\s*:\s*\(\s*/struct \{\n/ )
		{ 
			push( @st, "str$1");
			$indent += 4;
		}

		if ( s/\);/\};\n/ ) 
		{ 
			$st=pop( @st ); 
			s/\};\n/\} $st;\n/; 
			$indent-=4;
		}

		if ( /case integer of/i )
		{
			$_="union {\n"; 
			push( @st, "uniX"); 
			$indent += 4;
		}
		
		s/([a-zA-Z_0-9]+)\s*:\s*[Pp][Ss][Tt][Rr]([0-9]+)/char $1\[$2\]/;
		s/([a-zA-Z_0-9]+)\s*:\s*[Pp][Aa][Cc][Kk][Er][Dd]\s+[Aa][Rr][Rr][Aa][Yy]\s*\[1..([^\]]+)]\s*[Oo][Ff]\s+[Cc][Hh][Aa][Rr]/char $1\[$2\]/;
 		s/([a-zA-Z_0-9]+)\s*:\s*[Pp][Aa][Cc][Kk][Ee][Dd]\s+[Aa][Rr][Rr][Aa][Yy]\s*\[1..([^\]]+)]\s*[Oo][Ff]\s+([a-zA-Z_0-9]+)/\U$3\E $1\[$2\]/;
 		s/([a-zA-Z_0-9]+)\s*:\s*([a-zA-Z_0-9]+)/\U$2\E $1/;
	    s/^\s*//;
	    print $ind;
	    print;
	    next;
	}
}
