///////////////////////////////////////////////////////////////////////////////
/// @file Disassembler.cpp
///
/// @brief Destiny3D Shader Disassembler
///
/// @author JesusFreak
///
/// This file is the intellectual property of Novus Delta, LLC.. Usage of the
/// contents of this file is subject to the Destiny3D Member License which
/// can be found at http://www.destiny3d.com.  Any other usage is prohibited.
///
/// This file is distributed "AS IS" without warranty of any kind.  Novus
/// Delta, LLC. does not guarantee the fitness of the contents of this file
/// for any particular purpose.
///
/// Copyright (C) 2001-2003 Novus Delta, LLC. All Rights Reserved.
///
/// <hr>
///                                 Change History
/// <hr>
///
/// @date May 2002
/// @author JesusFreak
/// @remarks Creation
///
///////////////////////////////////////////////////////////////////////////////

// Include needed headers
#include "deString.hpp"
#include "deFileSystem.hpp"
#include "deDriver.hpp"
#include "iostream.h"

/////////////////////////////////////////////////////////////////////////////////////////////
// deBoolean Disassemble(int ArgCount,char * Arguments[]) - The main program for the disassembler
/////////////////////////////////////////////////////////////////////////////////////////////
deBoolean Disassemble(int ArgCount,char * Arguments[])
{
	// Store the names of our input and output files in local variables
	deString InputFile = Arguments[2];
	deString OutputFile = Arguments[3];

	// Open the assembled shader file
	deFSReal BinaryFile;
	if(!BinaryFile.Open(InputFile,deFS_Open_Existing | deFS_Open_Read))
	{
		cout << "Error opening shader file!\n";
		return deFALSE;
	}

	// Create a new shader object
	IdeShader * Shader = IdeShader_Create();
	
	// Load the shader
	if(!Shader->Read(&BinaryFile))
	{
		BinaryFile.Close();
		Shader->Release();
		return deFALSE;
	}

	// Close the shader file
	BinaryFile.Close();

	// Disassemble the shader
	deString DisassembledCode;
	if(!Shader->Disassemble(&DisassembledCode))
	{
		Shader->Release();
		BinaryFile.Close();
		return deFALSE;
	}

	// Release our shader object
	Shader->Release();
	Shader = NULL;

	// Open the output file
	deFSReal CodeFile;
	if(!CodeFile.Open(OutputFile,deFS_Open_CreateAlways | deFS_Open_Write))
	{
		cout << "Error creating output file.\n";
		return deFALSE;
	}

	// Write the shader to the output file
	long SizeOfCode = strlen(DisassembledCode);
	if(CodeFile.Write((void*)(const char*)DisassembledCode,SizeOfCode) != SizeOfCode)
	{
		CodeFile.Close();
		return deFALSE;
	}

	// Close the assembled file
	CodeFile.Close();

	cout << "File disassembled successfully.\n";

	return deTRUE;
}