#!/usr/bin/perl
#
# GeoMOOSE.js Compiler
# (c) 2006-2007 Dan "Ducky" Little
# 
# 1.1 Revised 7/23/2007 to remove comments
# 1.2 Revised to use new all.js format
#

use strict;
use XML::DOM;

my $parentDirectory = '../htdocs/';
my $index = 'geomoose_uncompiled.html';
my $list = 'lib/all.js';
my $output = 'geomoose.html';
my $jsOutput = 'lib/GeoMOOSE.js';

my $parse = XML::DOM::Parser->new();

open fh, $parentDirectory.$index;
open output, '>'.$parentDirectory.$output;
open js, '>'.$parentDirectory.$jsOutput;

my $date = `date`;
chomp($date);

print js qq(/*
 * Compiled $date with the GeoMOOSE compiler.
 */
);

# Load in everything from the $index which has the listing of script tags.
my $jsFile = '';


open listfile, $parentDirectory.$list;
while(<listfile>) {
	my $line = $_;
	chomp($line);
	if($line =~ m/.*lib.*js/) {
		$line =~ s/[']//g;
		my @files = split(/,/, $line);
		foreach my $file (@files) {
			$file = $parentDirectory.$file;
			print "Adding $file... ";
			open inputfile, $file;
			while(<inputfile>) {
				$jsFile .= $_;
			}
			print "Done.\n";
		}
	}
}
close listfile;

while(<fh>) {
	my $line = $_;
	if($line =~ m/\<script/i and $line =~ m/src=/i and not($line =~ /\-\-/)) {
		my $scriptNode = $parse->parse($line);
		my $src= $scriptNode->getFirstChild()->getAttribute('src');
		if($src !~ m/Configuration\.js/i) {
		} else {
			print output $line;
		}
	} elsif($line =~ /\<\/head/) {
		# Add the name of our compiled library
		print output qq(<script type="text/javascript" src="$jsOutput"></script>\n);
		print output $line;
	} else {
		print output $line;
	}
}

# Strip the comments out!
# I totally borrowed this code from the PERL 6 FAQ
$jsFile =~ s#/\*[^*]*\*+([^/*][^*]*\*+)*/|//[^\n]*|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $2 ? $2 : ""#gse;
# this is my trying to remove // style comments
$jsFile =~ s/\t+\/\/.*\n//g;
$jsFile =~ s/;.*\/\/.*\n/;/g;
# And all the newlines and tabs..., why not?
$jsFile =~ s/;\s*\n/;/g;
$jsFile =~ s/[\t]//g;
# Remove the whitespaces around assignments and comparitors and arithmatic operators
$jsFile =~ s/\s+(=+|<|>|>=|<=|\+|\-|\/|\*|\&\&|\|\|)\s+/$1/g;

# More whitespace clean up
$jsFile =~ s/\)\s*\{/\)\{/g;
$jsFile =~ s/\{\s*/\{/g;
$jsFile =~ s/\s*\}/\}/g;

# Remove the "space" between fucntion fn-name (parameters)
$jsFile =~ s/function (.*)\s+\(/function $1(/g;

# Remove all the blank lines
$jsFile =~ s/\n+/\n/g;
$jsFile =~ s/\n\s*\n/\n/g;

print js $jsFile;
close js;
close output;
close fh;
