#!/usr/bin/perl -w
$| = 1;

$SIG{'INT'} = sub {
        die "\x1b[79D\x1b[31mInterrupted by user\x1b[39m" . " " x 69 . "\n";
};

-d "dev" || mkdir "dev", oct "0777";
-d "pac" || mkdir "pac", oct "0777";
-d "sym" || mkdir "sym", oct "0777";
-d "com" || mkdir "com", oct "0777";

open (OUTFILE, ">/dev/null");
($dev,$pac,$sym)=(0,0,0);
$grid="";
($name,$type,$dir) = ("", "", $dir);

while(<>) {
	if(/^ 				# begin of line
		\ *			# any number of spaces
		GRID			# Keyword: "grid"	
		. *			# anything else
	   \r?$/ix )			# match case insensitive to EOL (\n or \r\n)
	{
		$grid=$_;
	}
	if(/^ 				# begin of line
		\ *				# any number of spaces
		EDIT			# Keyword: "edit"
		\ +				# one or more spaces
		([-0-9a-z_]+)	# one or more characters $3
		\.				# point
		([-0-9a-z_]+)			# one or more characters $4
		;?				# slashdot (optional)
	   \r?$/ix )		# match case insensitive to EOL (\n or \r\n)
	{
		close OUTFILE;
		($on,$ot) = ($name,$type);
		($name,$type,$dir) = ($1,$2,$2);
		$name =~ tr/a-z/A-Z/;
		$type =~ tr/a-z/A-Z/;
		$dir =~ tr/A-Z/a-z/;
		$$dir++;
		open(OUTFILE, ">$dir/$name\.SCR");
		print OUTFILE $_ . $grid; # the grid will always be set in a new file
		printf STDERR "\x1b[79DDev: %04d  Pac: %04d  Sym: %04d  Current: %-20s",
		       $dev, $pac, $sym, $name;
		if($ot=~/DEV/i) {
			open(COM, ">com/$on\.SCR");
			open(T1,"<dev/$on\.SCR");
			while(<T1>) {
				if(/^PACKAGE +'?([-0-9a-z_]+)'? *;? *\r?$/i) {
					$package = $1; $package =~ tr/a-z/A-Z/;
					open(T2,"<pac/$package\.SCR"); while(<T2>) { print COM; } close T2;
					print COM "\r\n";
					next;
				}
				if(/^ADD +'?([-0-9a-z_]+)'? +/i) {
					$symbol = $1; $symbol =~ tr/a-z/A-Z/;
					open(T2,"<sym/$symbol\.SCR"); while(<T2>) { print COM; } close T2;
					print COM "\r\n";
				}
			}
			close T1;
			open(T1,"<dev/$on\.SCR"); while(<T1>) { print COM; } close T1;
		}
	} else {
		printf OUTFILE $_;
	}
	if(eof(ARGV))
	{
		close ARGV;
		close OUTFILE;
		open(OUTFILE, ">/dev/null");
	}
}

printf STDERR "\x1b[79DDone.". " " x 74 .
              "\nDevices:  %4d\nPackages: %4d\nSymbols:  %4d\n", $dev, $pac, $sym;

close OUTFILE;

