// HW2 .Arciv Pretty-Printer v1.12
// Created: 01/09/06 by Mikail
// Last updated: 04/17/06
// Homepage: http://www.geocities.com/Area51/Quadrant/3864/homeworld.htm

var d0, d1, d2, dn
var i, j

var MssgDebug = false
var MssgVerbose = true		// applies to WScript.exe and CScript.exe
var HostType = typeof(WScript)
var ErrrTable = []
var ErrrCount = 0
var StripComments = false

var AppVersion = '1.12'
var AppInfo = 'HW2 .Arciv Pretty-Printer v' + AppVersion + ' by Mikail'+ '\n'
var AppError = ''+
'1) Generate an .arciv file for the files you wish to compile '+ '\n'+
'   using ModPackager.'+ '\n'+
'2) Run the program using the following command-line:'+ '\n'+
''+ '\n'+
'	cscript [script file] [p.p. path] [.arciv file] [[destination folder]] [[-s]]'+ '\n'+
''+ '\n'+
'   where:'+ '\n'+
'	[script file] is the full path to "HW2_ArcivPretty.js".'+ '\n'+
''+ '\n'+
'	[p.p. path] is the full path to "HW2_PrettyPrinter.js".'+ '\n'+
''+ '\n'+
'	[.arciv file] is the full path to the .arciv file you '+ '\n'+
'	generated using ModPackager.'+ '\n'+
''+ '\n'+
'	[[destination folder]] (optional) is the path to the '+ '\n'+
'	folder where the reformatted files should be generated. '+ '\n'+
'	Any files in the destination folder will be '+ '\n'+
'	automatically overwritten. Use the "-a" switch, '+ '\n'+
'	instead, to if you want the files generated in the same '+ '\n'+
'	directory as the .arciv file. Or, use the "-o" switch, '+ '\n'+
'	instead, if you want to overwrite your source files. '+ '\n'+
'	If [[destination folder]] is ommitted entirely, a new '+ '\n'+
'	file will be created with the same name and in the same '+ '\n'+
'	directory as the original file, but with an additional '+ '\n'+
'	".pretty" extension.'+ '\n'+
''+ '\n'+
'	[[-s]] (optional) tells the pretty-printer to strip '+ '\n'+
'	comments from the source file.'+ '\n'+
''+ '\n'+
'	**IMPORTANT** if the process is interrupted before it '+ '\n'+
'	is complete, then there may be some garbage left over '+ '\n'+
'	in the source directory that will have to be deleted '+ '\n'+
'	manually. If overwriting source files, then the source '+ '\n'+
'	files may get overwritten with garbage.'+ '\n'

if (HostType != 'undefined')
{
	// set up file objects
	var ProgArgs = WScript.Arguments
	var fso = new ActiveXObject('Scripting.FileSystemObject')
	var WshShell = new ActiveXObject('WScript.Shell')
	var TOCRootPath

	if (ProgArgs.length == 0)
	{
		PrintMessage(AppInfo)
		PrintMessage(AppError)
	}
	else
	{
		d0 = new Date()

		var PrettyPath = ProgArgs(0)
		var SRCFilePath = ProgArgs(1)
		var SRCRootPath = SRCFilePath.substring(0, SRCFilePath.lastIndexOf('\\') + 1)
		if (SRCRootPath == '')
		{
			SRCRootPath = WshShell.CurrentDirectory + '\\'
		}
		var WRTRootPath
		if (ProgArgs.length > 2)
		{
			WRTRootPath = ProgArgs(2)
			if ((WRTRootPath.charAt(WRTRootPath.length - 1) != '\\') && (WRTRootPath != '-o') && (WRTRootPath != '-a'))
			{
				WRTRootPath += '\\'
			}
		}

		var i = 3;
		while (i < ProgArgs.length)
		{
			if (ProgArgs(i) == '-s')	StripComments = true
			i += 1
		}

		// read the input file and store it as a string
		var TempObject = fso.OpenTextFile(SRCFilePath, 1)
		var CodeString = TempObject.ReadAll()
		TempObject.Close()
	
		// process the code
		var CodeString = ConvertTable(CodeString)
		eval(CodeString)

		// debugging
		if (MssgDebug == true)
		{
			var DebugTableObject = fso.OpenTextFile(SRCFilePath + '.debug1', 2, 1, 0)
			DebugTableObject.Write(CodeString)
			DebugTableObject.Close()
			var DebugProgressObject = fso.OpenTextFile(SRCFilePath + '.debug2', 2, 1, 0)
			DebugProgressObject.Write('')
			DebugProgressObject.Close()
			var DebugWrittenObject = fso.OpenTextFile(SRCFilePath + '.debug3', 2, 1, 0)
			DebugWrittenObject.Write('')
			DebugWrittenObject.Close()
		}

		for (i in Archive.TOCList)
		{
			TOCRootPath = Archive.TOCList[i].TOCHeader.RootPath
			for (j in Archive.TOCList[i].RootFolder)
			{
				var TempLevel = 'Archive.TOCList[' + i + '].RootFolder.' + j
				var TempTable = Archive.TOCList[i].RootFolder[j]
				if (MssgDebug == true)
				{
					DebugProgressObject = fso.OpenTextFile(SRCFilePath + '.debug2', 8, 1, 0)
					DebugProgressObject.Write(TempLevel + '\n')
					DebugProgressObject.Close()
				}
				if (j == 'Folders')
				{
					IterateFolders(TempTable, TempLevel)
				}
				else if (j == 'Files')
				{
					IterateFiles(TempTable, TempLevel)
				}
			}
		}
	
		dn = new Date()
		PrintMessage('Total time elapsed: ' + ((dn - d0)/1000) + ' seconds\n')
		PrintMessage('Total files with errors: ' + ErrrCount + '\n')
		if (ErrrCount > 0)
		{
			TempString = 'These files had errors and were not copied:\n'
			for (i = 0; i < ErrrCount; i ++)
			{
				TempString = TempString + '"' + ErrrTable[i] + '"\n'
			}
			PrintMessage(TempString)
			if (MssgDebug == true)
			{
				var TempObject = fso.OpenTextFile(SRCFilePath + '.errlog', 1)
				TempObject.Write(TempString)
				TempObject.Close()
			}
		}
	}
}

function IterateFolders(SubTable, Level)
{
	var i, j
	for (i in SubTable)
	{
		for (j in SubTable[i])
		{
			var NewLevel = Level + '[' + i + '].' + j
			if (MssgDebug == true)
			{
				DebugProgressObject = fso.OpenTextFile(SRCFilePath + '.debug2', 8, 1, 0)
				DebugProgressObject.Write(NewLevel + '\n')
				DebugProgressObject.Close()
			}
			var TempTable = SubTable[i][j]
			if (j == 'Folders')
			{
				IterateFolders(TempTable, NewLevel)
			}
			else if (j == 'Files')
			{
				IterateFiles(TempTable, NewLevel)
			}
		}
	}
}

function IterateFiles(SubTable, Level)
{
	var i, j
	for (i in SubTable)
	{
		for (j in SubTable[i])
		{
			var NewLevel = Level + '[' + i + '].' + j
			var TempTable = SubTable[i][j]
			if (MssgDebug == true)
			{
				DebugProgressObject = fso.OpenTextFile(SRCFilePath + '.debug2', 8, 1, 0)
				DebugProgressObject.Write(NewLevel + '\n')
				DebugProgressObject.Close()
			}
			if (j == 'Path')
			{
				var TOCFilePath = TempTable
				var OUTFilePath = TOCFilePath + '.pretty'
				var WRTFilePath = TOCFilePath.replace(TOCRootPath, WRTRootPath)
				var ARCFilePath = TOCFilePath.replace(TOCRootPath, SRCRootPath)
				var TOCFoldPath = TOCFilePath.substring(0, TOCFilePath.lastIndexOf('\\') + 1)
				var WRTFoldPath = TOCFoldPath.replace(TOCRootPath, WRTRootPath)
				var ARCFoldPath = TOCFoldPath.replace(TOCRootPath, SRCRootPath)

				var CommandString = 'cscript "' + PrettyPath + '" "' + TOCFilePath + '"'
				if (StripComments == true)
				{
					CommandString += ' -s'
				}

				PrintVerbose('Level: ' + NewLevel)
				PrintMessage('File: "' + TOCFilePath + '"')
				PrintVerbose('Command-line: ' + CommandString)

				d1 = new Date()
				var ErrorCode = WshShell.Run(CommandString, 2, 7)
				if (ErrorCode > 0)
				{
					AlertMessage('Error: HW2_PrettyPrinter encountered a problem parsing the file. This may be due to errors within the file itself.\n')
					ErrrTable[ErrrCount] = TOCFilePath
					ErrrCount += 1
				}
				d2 = new Date()

				if (MssgDebug == true)
				{
					DebugWrittenObject = fso.OpenTextFile(SRCFilePath + '.debug3', 8, 1, 0)
					if (ErrorCode == 0)
					{
						DebugWrittenObject.Write(TOCFilePath + '\n')
					}
					else
					{
						DebugWrittenObject.Write(ErrorMessage + '\n')
					}
					DebugWrittenObject.Close()
				}

				PrintMessage('Time: ' + ((d2 - d1)/1000) + ' seconds\n')

				// overwrite source files
				if (WRTRootPath == '-o')
				{
					fso.DeleteFile(TOCFilePath)
					fso.MoveFile(OUTFilePath, TOCFilePath)
				}
				// new file in the same directory as the .arciv file
				else if (WRTRootPath == '-a')
				{
					CreateFolderTree(ARCFoldPath)
					fso.CopyFile(OUTFilePath, ARCFilePath, 1)
					fso.DeleteFile(OUTFilePath)
				}
				// new file in same path, but with ".pretty" extension
				else if (WRTRootPath == null)
				{
				}
				// new file in specified directory
				else
				{
					if (fso.FileExists(OUTFilePath) == 1)
					{
						CreateFolderTree(WRTFoldPath)
						fso.CopyFile(OUTFilePath, WRTFilePath, 1)
						fso.DeleteFile(OUTFilePath)
					}
					else
					{
						AlertMessage('Error: File not copied.\n')
					}
				}
			}
		}
	}
}

function CreateFolderTree(TempString)
{
	var TempIndex = 0
	var TempString2 = ''
	var TempLength = TempString.length
	while (TempString2.length < TempLength)
	{
		TempIndex += TempString.substring(TempIndex, TempLength).indexOf('\\') + 1
		TempString2 = TempString.substring(0, TempIndex)
//		PrintMessage('TempIndex = ' + TempIndex + ', TempString2 = ' + TempString2)
		if (fso.FolderExists(TempString2) == 0)
		{
			fso.CreateFolder(TempString2)
		}
	}
}

function ConvertTable(TempString)
{
	TempString = TempString.replace(/\\/mg, '\\\\')
	TempString = TempString.replace(/\[\[/mg, '\"')
	TempString = TempString.replace(/\]\]/mg, '\"')
	TempString = TempString.replace(/\]/mg, '')
	TempString = TempString.replace(/\[/mg, '')
	TempString = TempString.replace(/\-\-/mg, '\/\/')
	TempString = TempString.replace(/\=/mg, '\:')
	TempString = TempString.replace(/Archive : /mg, 'Archive = ')

	TempRegexp = /\,(\s*)\}/mg
	TempTable = TempString.match(TempRegexp)
	while (TempTable != null)
	{
		TempString = TempString.replace(TempRegexp, '$1\}')
		TempTable = TempString.match(TempRegexp)
	}

	return TempString
}

function PrintMessage(TempString)
{
	if (HostType != 'undefined')
	{
		WScript.Echo(TempString)
	}
}

function PrintVerbose(TempString)
{
	if ((HostType != 'undefined') && (MssgVerbose == true))
	{
		WScript.Echo(TempString)
	}
}

function AlertMessage(TempString)
{
	if (HostType != 'undefined')
	{
		WScript.Echo(TempString)		
	}
	else
	{
		alert(TempString)
	}
}
