#!/usr/bin/perl

my $filename =shift @ARGV; # the name of the il file to read

my $state="main"; # the state of the parser : namespace, method, method2
my $name ="";     # the current namespace 
my $file =undef;  # the current file object
my %seen;         # what have we seen namespace -> file object map

open IN ,"$filename" or die "Cannot open $filename"; # open the input file
openfile ("Global");  # start with the global namespace as default

#######################
sub openfile
{
    my $name1 =shift;
    if (exists($seen{$name1}))
    {
	$file = $seen{$name1};
	print $file "// APPENDING $name1 to $name\n";

	if ($name ne $name1)
	{
	    print "inside $name appending $name1\n";
	}
	$name = $name1;
    }
    else
    {
	my $outname = "$filename.$name1.il";
	print "open $outname for $name1\n";
	my $somefile;
	open $somefile,">$outname" or die;
	$file=$seen{$name1}=$somefile;
	$name = $name1;
    }    
}


## Main routine
while (<IN>)
{
    if (/\.namespace '([\w\.]+)'/)
    {
	$name = $1;
	
	$state = "namespace";
	openfile ($name);
    }
    
    if  ($state eq "method")
    {
	# we need a "{"
	if (/\s+}/)
	{
	    #ending methos
	    $state = "namespace";
	}
	else
	{
	    $state = "method";
	}
    }
    if  ($state eq "methodstart")
    {
	# we need a "{"
	if (!/\{/)
	{
	    if (!/\}/) #empty
	    {
		die "missing {" . $_;
	    }
	    else
	    {
		$state = "namespace";
	    }
	}
	else
	{
	    $state = "method2";
	}
    }
    
#
    if (/\.method .* .* \'([\w.]+).*\}/)
    {
#    print "DONE: method $1\n";
    }
    elsif (/\.method .* \'([\w.]+)\'/)
    {
	$methodsig = $1;
	$state = "methodstart";
#    print "Entering method $1\n";
    }
    
    
# now output the stuff
    if ($state eq "method")
    {
	print $file "//$_";
    }
    else
    {
	print $file $_;
    }
    
# we have 
    if ($state eq "method2")
    {
	$state = "method";
    }
    
}

# close all the files
close IN;
foreach  (values %seen)
{
    close $_;
}
