#JCDebug.pl
#
#A script to enable/disable JCDebug.
#
require 5.004; #Make sure people are using a decent perl interpreter.
use Getopt::Long;
use Cwd;

$enable=0;
$disable=0;

GetOptions(
		   "e"=>\$enable,
		   "enable"=>\$enable,
		   "d"=>\$disable,
		   "disable"=>\$disable,
		   );


if((!$enable && !$disable)||($enable && $disable)) {
	print "You must choose to enable or disable JCDebug\n";
	print "code with the -e or -d options.\n";
	exit(1);
}

if($enable) {
	undef $/;
}

foreach $file (@ARGV) {
	chomp $file;
	if(!-f $file) {
		warn "$file is not a file, skipping\n";
		next;
	}
	($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,
	 $size,$atime,$mtime,$ctime,$blksize,$blocks)=stat $file;
	$bakfile="$file.bak";
	unless(rename($file,$bakfile)) {
		warn "Could not rename $file to $bakfile, skipping\n";
		next;
	}
	unless(open(IN,"$bakfile")) {
		warn "Could not open $bakfile for reading, skipping\n";
		next;
	}
	unless(open(OUT,">$file")) {
		warn "Could not open $file for writing, skipping\n";
		next;
	}
	while(<IN>) {
		if($enable){ #File at a time
			s!/\* JCDEBUG_START (JCDebug[^;]+\;) JCDEBUG_END \*/!$1!mg;
			s!(/\*\s*DEBUG_START)!$1*/!mg;
			s!(DEBUG_END\s*\*/)!/*$1!mg;
			print OUT;
		}
		if($disable) { #This is pretty ugly right now.
			
			if(m!/\*\s*DEBUG_START\s*\*/!) {
				s!(/\*\s*DEBUG_START\s*)\*/!$1!;
				print OUT;
				while(<IN>) {
					if(m!/\*\s*DEBUG_END\s*\*/!) {
						s!/\*(\s*DEBUG_END\s*\*/)!$1!;
						print OUT;
						last;
					}
					print OUT;
				}
			} #End wrapped case
			elsif(m!JCDebug[(.]+.*\)\;!) { #Single line JCDebug.
				s!(JCDebug[(.]+.*\)\;)!/\* JCDEBUG_START $1 JCDEBUG_END \*/!;
				print OUT;
			} #End single line case
			elsif(m!JCDebug[.(]+!) { #Multi line JCDebug
				s!(JCDebug[.(].*)!/\* JCDEBUG_START $1!;
				print OUT;
				while(<IN>) {
					if(m!\)\;!) {
						s!(\)\;)!$1 JCDEBUG_END \*/!;
						print OUT;
						last;
					}
					print OUT;
				}
			} #End multi-line case
			else {
				print OUT;
			}
		}
		
	}

	close IN;
	close OUT;
	chmod 644,$bakfile;
#List the OS's that use del instead of rm.
#unlink doesn't seem to work under windows.
	if($^O=~m/(windows|msdos|NT|Win32)/i) {
		system("del $bakfile");
	}
	else {
		system("rm $bakfile");
	}
	chmod $mode,$file;
}








