/*=========================================================================
*
* Classes.c	- Class conversion
*
* Version			1.0
* Revision date
*
*=======================================================================*/
#include <Windows.h>

#include "Classes.h"

#include "conventi.h"
#include "print.h"
#include "system.h"

#include "ModLib.h"
#include "PlgLoad.h"
#include "ModSave.h"
#include "PhySave.h"
#include "VseSave.h"
#include "ZooSave.h"

#include "Levels.h"

#include "SaveModifLst.h"

//--------------------------------------------------------------------


/****************************************************************************
*		Description:	compute all the classes found in the source directory
*
*		Parameters:		sRawData	: source directory
*						sGameData	: destination directory
*---------------------------------------------------------------------------
*		Revision date:                                      Author:         
*****************************************************************************/
void MLT_vComputeAllClasses (char *sRawData, char *sGameData)
{
  xString			sDirectory;
  HANDLE			hHandle;
  WIN32_FIND_DATA	stFindFileData;

  // change directory
  GetCurrentDirectory(256, sDirectory);
  SetCurrentDirectory(sRawData);

  // search all the classes files
  memset(&stFindFileData,0,sizeof(stFindFileData));
  hHandle = FindFirstFile("World/Graphics/Objects/Classes/*.mod", &stFindFileData);
  if( hHandle == INVALID_HANDLE_VALUE)
  {
    SetCurrentDirectory(sDirectory);
    printf("Can't find Classes directory");
    return;
  }
  
  do
  {
    if(strlen(stFindFileData.cFileName) == 0) break;

    // compute the class
    MLT_vComputeOneClassMod(MLT_p_cGetFileNameWithoutExt(stFindFileData.cFileName), MLT_p_cGetFileNameWithoutExt(stFindFileData.cFileName), sRawData, sGameData);
  }
  while(FindNextFile(hHandle, &stFindFileData));
  FindClose(hHandle);

  // restore directory
  SetCurrentDirectory(sDirectory);
}


/****************************************************************************
*		Description:	compute the specified class
*
*		Parameters:		sClassName	: class to convert
*						sRawData	: source directory
*						sGameData	: destination directory
*---------------------------------------------------------------------------
*		Revision date:                                      Author:         
*****************************************************************************/
void MLT_vComputeOneClass (char *sClassName, char *sRawData, char *sGameData)
{
// WIN version
#ifndef _WINDOWS

  xString			sDirectory, sFileSearch;
  HANDLE			hHandle;
  WIN32_FIND_DATA	stFindFileData;

  // change directory
  GetCurrentDirectory(256, sDirectory);

  // search for the class file
  if (g_bStandardConfig)
  {	
	SetCurrentDirectory(sRawData);
	sprintf(sFileSearch, "World\\Graphics\\Objects\\Classes\\%s.mod", sClassName);
  }
  else
	sprintf(sFileSearch, "%s\\%s.mod", g_szClasses, sClassName);

  memset(&stFindFileData,0,sizeof(stFindFileData));
  hHandle = FindFirstFile(sFileSearch, &stFindFileData);
  if( hHandle == INVALID_HANDLE_VALUE)
  {
    SetCurrentDirectory(sDirectory);
    fprintf(stderr, "\nError : Can't find %s classe\n", sClassName);
    return;
  }
  do
  {
    if(strlen(stFindFileData.cFileName) == 0) break;

    // compute the MOD file
    MLT_vComputeOneClassMod(MLT_p_cGetFileNameWithoutExt(stFindFileData.cFileName), MLT_p_cGetFileNameWithoutExt(stFindFileData.cFileName), sRawData, sGameData);
  }
  while(FindNextFile(hHandle, &stFindFileData));
  FindClose(hHandle);

  // restore directory
  SetCurrentDirectory(sDirectory);

// DOS version
#else
  MLT_vComputeOneClassMod(sClassName, sClassName, sRawData, sGameData);
#endif
}


/****************************************************************************
*		Description:	compute the MOD file in the specified class
*
*		Parameters:		sClassName	: class to convert
*						sModName	: file to convert
*						sRawData	: source directory
*						sGameData	: destination directory
*---------------------------------------------------------------------------
*		Revision date:                                      Author:         
*****************************************************************************/
void MLT_vComputeOneClassMod (char *sClassName, char *sModName, char *sRawData, char *sGameData)
{
  xString	sRawClass, sGameClass, sFile, sSection, sFileM, sFile1;
  int		i, f;

  // register globals
  sprintf(g_sFileIn, "%s", sModName);
  sprintf(g_sFileMaterial, "%s", sClassName);
  sprintf(g_sDirectorySave, "%s\\", sClassName);

  // DISPLAY
  MLT_vOutput( C_ComRes_cTitleLine, "\nClass %s\\%s.mod",sClassName, sModName);

  // init paths
  if (g_bStandardConfig)
	sprintf(sRawClass, "%s\\World\\Graphics\\Objects\\Classes", sRawData);
  else
	sprintf(sRawClass, "%s", g_szClasses);

  sprintf(sGameClass, "%s\\World\\Graphics\\Objects\\Classes\\%s", sGameData, sClassName);

  // change directory
  CreateDirectory(sGameClass, NULL);
  SetCurrentDirectory(sGameClass); 

  // prepare TBL notifications
  MLT_vInitSaveTbl();

  // notify MOD file
  sprintf(sFile, "%s.mod", g_sFileIn);
  SCR_fn_v_SvL1_RegisterNotify(sFile, MLT_vSaveEmptyModHeader, NULL, SCR_EA_Ntfy_AddOrModifySection);

// multitextures
  // notify TEX file
  sprintf(sFile, "%s.tex", g_sFileIn);
  if (!SCR_fn_c_RdL0_IsSectionExists(sFile))
  {
    SCR_fn_v_SvL1_RegisterNotify(sFile, MLT_vSaveTexFile, NULL, SCR_EA_Ntfy_AddOrModifySection);
	g_bExistTex = FALSE;
  }
  else
	g_bExistTex = TRUE;

  // notify VMT file
  sprintf(sFile, "%s.vmt", g_sFileIn);
  if (!SCR_fn_c_RdL0_IsSectionExists(sFile))
    SCR_fn_v_SvL1_RegisterNotify(sFile, MLT_vSaveVmtFile, NULL, SCR_EA_Ntfy_AddOrModifySection);

  // notify TBL file
  sprintf(sFile, "%s.tbl", g_sFileIn);
  SCR_fn_v_SvL1_RegisterNotify(sFile, MLT_vSaveTblFile, (void *)0x1, SCR_EA_Ntfy_AddSection);

  // notify PHY file
  sprintf(sFile, "%s.phy", g_sFileIn);
  SCR_fn_v_SvL1_RegisterNotify(sFile, MLT_vSavePhyFile, NULL, SCR_EA_Ntfy_AddSection);

  // notify ZOO file
  sprintf(sFile, "%s.zoo", g_sFileIn);
  if (!SCR_fn_c_RdL0_IsSectionExists(sFile))
    SCR_fn_v_SvL1_RegisterNotify(sFile, MLT_vSaveZooFile, NULL, SCR_EA_Ntfy_AddSection);

  // if ZOO file exist, check if must be rebuilt
  else
  {   
	  if (g_bIgnoreZoo)
	  {	
		  i=remove(sFile);
		  if (!i)
			  SCR_fn_v_SvL1_RegisterNotify(sFile, MLT_vSaveZooFile, NULL, SCR_EA_Ntfy_AddSection);
	  }
	  else
	  {	
		 xString sSection;
		 
		 CopyFile(sFile, "temp.zoo", FALSE);
		 SCR_fn_v_RdL0_ComputeSectionName(sSection, sFile, M_AllCollideSets, "");
		 SCR_fn_v_SvL1_RegisterNotify(sSection/*sFile*/, MLT_vSaveAllCollideSetsSection, NULL, SCR_EA_Ntfy_RebuildSection);
	  }
  }

  // notify VSE file
  sprintf(sFile, "%s.vse", g_sFileIn);
  if (!SCR_fn_c_RdL0_IsSectionExists(sFile))
    SCR_fn_v_SvL1_RegisterNotify(sFile, MLT_vSaveVseFile, NULL, SCR_EA_Ntfy_AddSection);
  else
  {	
	CopyFile(sFile, "temp.vse", FALSE);
	remove(sFile);
	SCR_fn_v_SvL1_RegisterNotify(sFile, MLT_vSaveVseFile, NULL, SCR_EA_Ntfy_AddSection);
  }

  // save all notified sections
  SCR_fn_v_SvL1_UpdateAllNotify();

  // register path for load
  SCR_fn_v_RdL0_RegisterPath(sGameClass);

  // change directory
  SetCurrentDirectory(sRawClass);

  // DISPLAY
  MLT_vOutput( C_ComRes_cNormalLine, "\n\tLoad...");

  // load MOD file
  MLT_vLoadModFileInLib();

  // load PLG file
  MLT_vLoadPLGFileInLib();


  // DISPLAY
  MLT_vOutput( C_ComRes_cNormalLine, "\n\tCreate Physical...");

  // build physical sections
  MLT_vMakePhysicalInLib();

  // change directory
  SetCurrentDirectory(sGameClass); 

  // DISPLAY
  MLT_vOutput( C_ComRes_cNormalLine, "\n\tSave...");

  // save MOD file
  MLT_vSaveLibInModFile(TRUE, TRUE, TRUE, TRUE);
  // save PLG file
  MLT_vSaveLibInPLGFile();

  // if necessary, remove old files
  g_bExistMdf = FALSE;
  g_bExistMdt = FALSE;
  if (g_bEraseMdf)	
  {	
	  strcpy (sFile, sGameClass);
	  sprintf(sFileM, "%s.mdf", sClassName);
	  strcat(sFile, sFileM);
      _chmod(sFile, _S_IREAD | _S_IWRITE );
	  f = remove(sFile);		//remove the old gmt file
	  if (f != -1) 
	    g_bExistMdf = TRUE;

	  strcpy (sFile, sGameClass);
	  sprintf(sFileM, "%s.mdt", sClassName);
	  strcat(sFile, sFileM);
      _chmod(sFile, _S_IREAD | _S_IWRITE );
	  f = remove(sFile);		//remove the old gmt file
	  if (f != -1) 
	    g_bExistMdt = TRUE;
  }

  // save all notified sections
  SCR_fn_v_SvL1_UpdateAllNotify();
  
  // rebuild TBL sections
  sprintf(sFile, "%s.tbl", g_sFileIn);
  SCR_fn_v_RdL0_ComputeSectionName(sSection, sFile, M_TBL_HEADER, "");
  SCR_fn_v_SvL1_RegisterNotify(sSection, MLT_vSaveTblFile, NULL, SCR_EA_Ntfy_RebuildSection);
  SCR_fn_v_SvL1_UpdateAllNotify();

  // erase the libs
  MLT_vEraseLib();
  MLT_vErasePLGLib();

  // update ModifLst file
  MLT_vUpdatePathInModifFile(sGameClass);

  // close all opened files for VSE
  SCR_fn_v_RdL0_Close();
  strcpy(sFile, sGameClass);
  strcat(sFile, "temp.vse");
  remove(sFile);
  MLT_vInitSystem();

  // close all opened files for ZOO
  if (!g_bIgnoreZoo)
  {	
	  SCR_fn_v_RdL0_Close();
	  strcpy (sFile, sGameClass);
	  strcat(sFile, "temp.zoo");
	  remove(sFile);
	  MLT_vInitSystem();
  }

  // DISPLAY
  MLT_vOutput( C_ComRes_cResultLine, "\nClass %s converted\n",sClassName);

  // clean all opened structures
  for (i=3; i<256; i++)
	_close((int)i);
  MLT_vInitSystem();



// multitextures
  if (g_bIgnoreTex && g_bExistTex)
  {
	  FILE *fileR, *file;
	  xString sRead;
	  
	  strcpy (sFile, sGameClass);
	  sprintf(sFileM, "%s.tex", sClassName);
	  strcat(sFile, sFileM);

	  strcpy (sFile1, sGameClass);
	  strcat(sFile1, "temp.tex");

	  fileR=fopen(sFile1, "rt");
	  file =fopen(sFile, "r+");
	  if (!fileR) return;
	  if (!file) return;

	  while (!feof(fileR))
	  {
		fgets(sRead, 256, fileR);
		if (strstr(sRead, "Texture"))
		{	//a new section begins
			MLT_vSearch(sRead, file);
			fputs(sRead, file);
			fgets(sRead, 256, fileR);
			while (!strstr(sRead, "}"))
			{	fputs(sRead, file);
				fgets(sRead, 256, fileR);
			}
		}
	  }
	  fclose(file);
	  fclose(fileR);
	  remove(sFile1);
  }

}


