#! /usr/bin/perl
#
# script to copy the autogenerated source code exceptions referring to Ktype into
# from errors.SourceCodeException.java to types.KTypeSourceCodeException.java

use warnings;
use strict;

use Data::Dumper;

#my $sourceFile = 'SourceCodeException.java';
#my $targetFile = 'KTypeSourceCodeException.java';

my $arg1 = shift or die("Missing argument 2: path to generated exception file");
my $arg2 = shift or die("Missing argument 3: path to generated type exception file");

my $source = $arg1;
my $target = $arg2;

extractKTypeExceptions($source, $target);

exit(0);


sub extractKTypeExceptions{

	my $source = shift;
	my $target = shift;
	
	open( SFILE, "<", $source) or die ("Can't open file $source : $!");
	my @sLines = <SFILE>;
	close SFILE;
	
	open( TFILE, "<", $target) or die ("Can't open file $target : $!");
	my @tLines = <TFILE>;
	close TFILE;
	
	open( SFILE, ">", $source) or die("Can't open file $source : $!");
	open( TFILE, ">", $target) or die("Can't open file $target : $!");
	
	my $activeS = 0;
	my $activeT = 0;

   	foreach my $tLine ( @tLines ) {

		if ($activeT==0)
		{
			print TFILE $tLine;
			if($tLine =~ /\/\/MARKER BEGIN INJECT/)
			{
				$activeT = 1; 
			}
		}
		elsif ($activeT == 1)
		{
			my $WriteToKTypes = 0;
			foreach my $sLine ( @sLines ) {
		
				if ($activeS==0)
				{
					print SFILE $sLine;
					if($sLine =~ /\/\/MARKER BEGIN INJECT/)
					{
						$activeS = 1; 
					}
				}
				else
				{
					if($sLine =~ /\/\/MARKER END INJECT/)
					{
						print SFILE $sLine;
						$activeS = 0; 
					}
					else
					{
						# Copy exceptions that belong to types to types.KTypesSourceCodeExceptions
						# and general exceptions to errors.SourceCodeExceptions
						if ($sLine =~ /AutoGenerated Method/)
						{
							if ($sLine =~ /depends on kenya.types/)
							{
								$WriteToKTypes = 1;
							}
							else
							{
								$WriteToKTypes = 0;
							}
						}
						# print to types.KTypesSourceCodeExceptions
						if ($WriteToKTypes == 1)
						{
							print TFILE $sLine
						}
						# print to errors.SourceCodeExceptions
						if ($WriteToKTypes == 0)
						{
							print SFILE $sLine;
						}
					}
				}
		
			}

			$activeT = 2; 
		}
		elsif ($activeT == 2)
		{
			if($tLine =~ /\/\/MARKER END INJECT/)
			{
				print TFILE $tLine;
				$activeT = 0; 
			}
		}
	
	}
 

   close SFILE;
   close TFILE;
}
