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

use strict;
use XML::DOM;

my $index = 'index_uncompiled.html';
my $output = 'index.html';
my $jsOutput = 'lib/GeoMOOSE.js';

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

open fh, $index;
open output, '>'.$output;
open js, '>'.$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 = '';
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) {
			print 'Adding... '.$src;
			open jsfile, $src;
			while(<jsfile>) {
			#	print js $_;
				$jsFile = $jsFile.$_;
			}
			close jsfile;
			print " Done.\n";
		} 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;
