#!/usr/bin/perl -w

use strict;

($ARGV[0]) || die "Usage: $0 file \n";

open(SRC, "< $ARGV[0].cpl") || die "Can't open file $ARGV[0].cpl\n";
my @sourcelines = <SRC>;
my $source = join("",@sourcelines);
close(SRC);

my $error = 0;
my $pname = "";

# print out the while file size:
print "Team size: " . length($source) . "bytes\n";
if (length($source) > 8096) {
	if ($source =~ /.*\(team\s(\w+)/){
			$pname = $1;
	};
	print "!!!Team  $pname (". &getmappedname($pname). ") exceed compiler limit!!!\n";
	$error = 1;
}

my ($i, $size);
my $run = 1;

while ($run) {
	# find process
	$i = index($source,"(cp");
	if($i == -1){
		$run = 0;
	}else{
		# look for closing )		
		$source = substr($source,$i);
		#print "bef\n" .$source;
		if ($source =~ /\(cp\s(\w+)/){
			$pname = $1;
		};
		
		$size = &findclosing($source);
		
		print "Size of process: $pname is: $size bytes\n";
		if($size > 1024) {			
			print "!!!Process $pname (". &getmappedname($pname). ") exceed compiler limit!!!\n";
			$error = 1;
		}
		$source = substr($source,$size);	
		#print "after\n" .$source;
	}
}

exit $error;

sub findclosing{
	my $str = $_[0];
	my $i;
	my $len = length($str);
	my $opens = 0;
	my $chr;
	for($i=0 ; $i < $len; $i++){	
		$chr = substr($str,$i,1);
		if($chr eq "(") { $opens = $opens + 1; }
		if($chr eq ")") { $opens = $opens - 1; }
		if($opens == 0){
			return $i+1;
		}			
	}
	print "find no corresponding closing \")\"! (maybe a comment with of ())";
	return 1;
}

sub getmappedname{
	my $str = $_[0];
	if (open(MAP, "< $ARGV[0].map")){	
		my $line;
		while  ($line = <MAP>){			
			if($line =~ /(\w+)->$str$/){
				close(MAP);	
				return $1;
			}
		}
		close(MAP);	
	}else{
		return "";
	};
}
