/*---------------------------------------------------------------------------*/
/* AI_Proto.c : */
/* author : Olivier Didelot.*/
/* date   : 30/01/1997*/
/* modify : 04/02/1997  Lint 0 warnings excepted those specified at the end of AIMacros.h*/
/* modify : 25/03/1997  minor changes to avoid non NULL pointers (for editor)*/
/* modify : Olivier Couvreur 23/04/97 MMG + DIR*/
/* modify : Olivier Couvreur 15/05/97 Safe second pass for DsgVar + ReinitAI*/
/*---------------------------------------------------------------------------*/
/*#define AI_D_DebugMalloc*/
 
#include "AIUseCPA.h"
 
#include "AI_Mmg.h"
#include "specif/AIOption.h"
#include "AIMacros.h"
#include "AI_Erm.h"
 
#include "StrIntel.h"
#include "Intell.h"
 
#include "Action.h"
#include "Operator.h"
#include "Cond.h"
#include "KeyWord.h"
#include "Procedur.h"
#include "Function.h"
#include "Fields.h"
 
#include "Convert.h"
 
#include "AI_Struc.h"
#define __DeclareGlobalVariableAIProto_h__
#include "AI_Proto.h"
#undef __DeclareGlobalVariableAIProto_h__
#include "ReadRule.h"
#include "DsgMem.h"
 
#define __DeclareGlobalVariableSafe_h__
#include "safe.h" /*BART*/
#undef __DeclareGlobalVariableSafe_h__
 
#ifdef ACTIVE_AIDEBUG   /*** DR ***/
#include "AID_Erm.h"
#include "AID_Main.h"
#include "specif/AID_Trac.h"
#endif
 
#ifdef U64 /*AR980625*/
/* LOL*/
#include "GLD/Specif/DisplMsg.h"
#else	/* MT300399 */
#include "SNA.h"
#include "GAM/Specif/Demos.h"
#include "PTC.h"
#endif
 
/*ANNECY CHRISTOPHE MODIFICATIONS CF XAVIER*/
#if defined(ACTIVE_EDITOR)
SCR_tdst_Link_Table *AI_fn_p_stGetDsgVarLinkTable(void)
{
	return &(g_stDefinesLinkTable);
}
#endif /* ACTIVE_EDITOR */
/*ANNECY END CHRISTOPHE MODIFICATIONS CF XAVIER*/
 
#ifdef ACTIVE_EDITOR
extern "C" ACP_tdxBool g_bUseSAIWithEditor;
#endif /* ACTIVE_EDITOR */
 
#if defined(ACTIVE_EDITOR)
/* To activate 2nd pass checking*/
#define ACTIVE_2NDPASS_CHECKING
#if defined(ACTIVE_2NDPASS_CHECKING)
  /*#pragma message("ACTIVE_2NDPASS_CHECKING is defined ==> editor will run automaticaly if an error occured in AI while loading")*/
#endif
#endif
 
#if defined(AI_USE_SCRIPT)
#define  M_GetLinkValueWithKey(lKey) SCR_M_ul_Link_GetValue( ((SCR_tdst_Link_Value *) (lKey)) )
#define  M_GetComportLinkValueWithKey(lKey) \
((SCR_M_e_Link_GetState((SCR_tdst_Link_Value *) (lKey) ) != SCR_ELS_Link_NotInitialized) ? \
fn_ulGetComportLinkValueWithKey((SCR_tdst_Link_Value *)(lKey)) : 0)
#endif /* AI_USE_SCRIPT */
 
#if defined(__DEBUG_AI__) || defined(ACTIVE_2NDPASS_CHECKING)
char szForErrorStringAt2ndPass[256];
#endif
 
#if defined(AI_USE_SCRIPT)
#if defined(ACTIVE_2NDPASS_CHECKING)
	#define M_TestLinkTableValue(p_stMind,lKey,szStr) \
	if (SCR_M_e_Link_GetState((SCR_tdst_Link_Value *) (lKey) ) == SCR_ELS_Link_NotInitialized) \
	{	\
        sprintf(szForErrorStringAt2ndPass,"%s in %s",szStr,AI_M_szGetPersoName((p_stMind))); \
		M_AIWarningErrorAndNeverStopForDebug(E_uwAIWarningReferenceNotLoaded,C_ucErmOpenInfoWindow, szForErrorStringAt2ndPass); \
        AI_M_ucErrorFlag((p_stMind))=1; \
		fn_vForceEditor(); \
    }
#elif defined(__DEBUG_AI__)
	#define M_TestLinkTableValue(p_stMind,lKey,szStr) \
	if (SCR_M_e_Link_GetState((SCR_tdst_Link_Value *) (lKey) ) == SCR_ELS_Link_NotInitialized) \
	{	\
        sprintf(szForErrorStringAt2ndPass,"%s in %s",szStr,AI_M_szGetPersoName((p_stMind))); \
		M_AIFatalErrorMsg(E_uwAIFatalReferenceNotLoaded, szForErrorStringAt2ndPass); \
	}
#else
	#define M_TestLinkTableValue(p_stMind,lKey,szStr)
#endif /* ACTIVE_2NDPASS_CHECKING */
#endif /* AI_USE_SCRIPT */
 
#define _WP_D_DEFINE_WAYPOINTS_
#include "WP_Func.h"
#undef  _WP_D_DEFINE_WAYPOINTS_ 
 
#if defined(__DEBUG_AI__)
#define AI_LOGFILE
#endif
 
#if defined(AI_LOGFILE) 
#include <stdio.h>
FILE *fpAILogFile=NULL;
#define AI_ANIM_LOGFILE "AI_ANIM.LOG"
 
FILE *fpAIUnusedComportLogFile=NULL;
#define AI_UNUSEDCOMPORT_LOGFILE "AI_UnusedComport.LOG"
 
#endif
 
#if defined(AI_USE_SCRIPT)
unsigned long fn_ulGetComportLinkValueWithKey(SCR_tdst_Link_Value *p_stLinkValue)
{
	/* Give the value 1 to long1.*/
	SCR_M_v_Link_SetAdditionalLong(p_stLinkValue, 4, 1);
	return SCR_M_ul_Link_GetValue(p_stLinkValue);
}
#endif /* AI_USE_SCRIPT */
 
void fn_vTestUnusedComport()
{
#if defined(AI_LOGFILE) 
	unsigned int uiPos = 0, i=0;
	SCR_tdst_Link_Value	*p_stLinkValue = NULL;
 
	/* Get first element of array */
	SCR_M_DyAr_GetNextElement(SCR_tdst_Link_Value, uiPos, p_stLinkValue, SCR_M_st_Link_GetDynamicArray(&g_stComportLinkTable));
	
	while (p_stLinkValue != NULL) /* p_sValue is NULL at the end of the array */
	{
		/* Test current retrieved value */
		if (SCR_M_e_Link_GetState(p_stLinkValue) == SCR_ELS_Link_Initialized)
		{
			if (SCR_M_ul_Link_GetAdditionalLong(p_stLinkValue, 4) == 0)
			{
				if (fpAIUnusedComportLogFile)
				{
					fprintf(fpAIUnusedComportLogFile,"%s\n",SCR_M_p_sz_Link_GetKey(p_stLinkValue));
				}
			}
		}
		
		/* Get next element */
		uiPos++;
		SCR_M_DyAr_GetNextElement(SCR_tdst_Link_Value, uiPos, p_stLinkValue, SCR_M_st_Link_GetDynamicArray(&g_stComportLinkTable));
	}
	if (fpAIUnusedComportLogFile)
	{
		fclose(fpAIUnusedComportLogFile);
		fpAIUnusedComportLogFile=NULL;
	}
#endif /* AI_LOGFILE*/
}
 
/* to delete later : not used*/
 
#ifndef _FIRE_DEADCODE_U64_ /* Added by RUC */
void fn_vReinitComportMind(AI_tdxHandleToMind p_stMind)
{
	fn_vReinitComport(AI_M_p_stGetIntelligence(p_stMind));
	fn_vReinitComport(AI_M_p_stGetReflex(p_stMind));
}
#endif /* _FIRE_DEADCODE_U64_ */ /* Added by RUC */
 
 
 
#ifndef _FIRE_DEADCODE_U64_ /* Added by RUC */
unsigned long AI_ulSizeOfMind()
{
  return(sizeof(AI_tdstMind));
}
#endif /* _FIRE_DEADCODE_U64_ */ /* Added by RUC */
 
 
AI_tdstMind *fn_pstAllocMind(void)
{
	AI_tdstMind *p_stMind=NULL;
    MMG_fn_vAddMemoryInfo (MMG_C_lTypeAI , MMG_C_lSubTypeMind , NULL);
	M_AIAlloc(p_stMind, AI_tdstMind *, sizeof(AI_tdstMind));
	
	/* to be sure (for editor)*/
	AI_M_SetAIModel(p_stMind,NULL);
	AI_M_SetIntelligence(p_stMind,NULL);
	AI_M_SetReflex(p_stMind,NULL);
	AI_M_SetDsgMem(p_stMind,NULL);
 
    #if defined(ACTIVE_EDITOR)
    AI_M_ucErrorFlag(p_stMind)=0;           
    #endif
 
	AI_M_SetDoingIntel(p_stMind, 0);
 
#if defined(ACTIVE_EXEC_CHECKING) && defined(ACTIVE_EDITOR)
	fn_vReSetStopAIEngineFlag();
#endif
 
#ifdef ACTIVE_AIDEBUG /*** DR to initialize the trace ***/
/* Oliv' - use accessors instead of direct member - 25/11/1998*/
/*	p_stMind->p_stTrace=NULL;*/
	AI_M_SetTrace( p_stMind, NULL );
/* EndOfOliv'*/
	AIDebug_M_InitTrace( p_stMind );
	AIDebug_M_InitBuffer( p_stMind );
#endif
 
//XB 05/08/99
#ifndef D_THROW_CFAST_AI
//End XB
	p_stMind->CFast_lCmpMetaAction = 0; 
	p_stMind->CFast_lRfxMetaAction = 0; 
	p_stMind->CFast_lCmpMetaActionForMacro = 0; 
	p_stMind->CFast_lRfxMetaActionForMacro = 0; 
//XB 05/08/99
#endif /* D_THROW_CFAST_AI */
//End XB
 
	return p_stMind;
}
 
void fn_vFirstInitAIMemory()
{
	Erm_M_InitErrMsg(AI);
	Mmg_M_InitMmg(AI);
	
#if defined(AI_LOGFILE) 
	remove(AI_ANIM_LOGFILE);
	fpAILogFile=NULL;
	remove(AI_UNUSEDCOMPORT_LOGFILE);
	fpAIUnusedComportLogFile=NULL;
#endif
}
 
void fn_vInitAIFixMemory(unsigned long ulSize)
{
#ifdef MODE_STATIC_MEM_FOR_AI
	#if !defined(U64)
		Mmg_M_InitSpecificBlock(AI, E_ucAIBlockFix, ulSize, C_ulDefaultMaxNbStaticMalloc, 4, C_BlockWithFreeFlag | C_Check_AlignementFlag | C_Check_OverflowFlag);
	#else /* !U64 */
		#ifdef CHECK_MEMORY
			Mmg_M_InitSpecificBlock(AI, E_ucAIBlockFix, ulSize, C_ulDefaultMaxNbStaticMalloc, 4, C_BlockWithFreeFlag | C_Check_AlignementFlag | C_Check_OverflowFlag);
		#else /* CHECK_MEMORY */
			Mmg_M_InitSpecificBlock(AI, E_ucAIBlockFix, ulSize, C_ulDefaultMaxNbStaticMalloc, 4, C_BlockWithoutFreeFlag | C_Check_AlignementFlag | C_Check_OverflowFlag);
		#endif /* CHECK_MEMORY */
	#endif /* !U64 */
#endif /* MODE_STATIC_MEM_FOR_AI*/
}
 
void fn_vInitAILevelMemory(unsigned long ulSize)
{
#ifdef MODE_STATIC_MEM_FOR_AI
	#if !defined(U64)
		Mmg_M_InitSpecificBlock(AI, E_ucAIBlockLevel, ulSize, C_ulDefaultMaxNbStaticMalloc, 4, C_BlockWithFreeFlag | C_Check_AlignementFlag | C_Check_OverflowFlag);
	#else /* !U64 */
		#ifdef CHECK_MEMORY
			Mmg_M_InitSpecificBlock(AI, E_ucAIBlockLevel, ulSize, C_ulDefaultMaxNbStaticMalloc, 4, C_BlockWithFreeFlag | C_Check_AlignementFlag | C_Check_OverflowFlag);
		#else /* CHECK_MEMORY */
			Mmg_M_InitSpecificBlock(AI, E_ucAIBlockLevel, ulSize, C_ulDefaultMaxNbStaticMalloc, 4, C_BlockWithoutFreeFlag | C_Check_AlignementFlag | C_Check_OverflowFlag);
		#endif /* CHECK_MEMORY */
	#endif /* !U64 */
#endif /* MODE_STATIC_MEM_FOR_AI*/
}
 
 
#ifndef _FIRE_DEADCODE_U64_ /* Added by RUC */
void fn_vFreeAIFixMemory(void)
{
#ifdef MODE_STATIC_MEM_FOR_AI
	Mmg_M_FreeBlock(AI, E_ucAIBlockFix);
#endif /* MODE_STATIC_MEM_FOR_AI*/
}
#endif /* _FIRE_DEADCODE_U64_ */ /* Added by RUC */
 
 
void fn_vFreeAILevelMemory(void)
{
#ifdef MODE_STATIC_MEM_FOR_AI
	Mmg_M_FreeBlock(AI, E_ucAIBlockLevel);
#endif /* MODE_STATIC_MEM_FOR_AI*/
}
 
 
#ifndef _FIRE_DEADCODE_U64_ /* Added by RUC */
void fn_vDeleteAIFixMemory(void)
{
#ifdef MODE_STATIC_MEM_FOR_AI
	Mmg_M_DeleteBlock(AI, E_ucAIBlockFix);
#endif /* MODE_STATIC_MEM_FOR_AI*/
}
#endif /* _FIRE_DEADCODE_U64_ */ /* Added by RUC */
 
 
void fn_vDeleteAILevelMemory(void)
{
#ifdef MODE_STATIC_MEM_FOR_AI
	Mmg_M_DeleteBlock(AI, E_ucAIBlockLevel);
#endif /* MODE_STATIC_MEM_FOR_AI*/
}
 
#if !defined(RETAIL) || defined(FINAL_VERSION_FOR_TESTERS)
void AI_PrintUsedStaticMemory(void)
{
	Mmg_M_PrintUsedStaticMemoryInModule(AI);
}
#endif /* !defined(RETAIL) || defined(FINAL_VERSION_FOR_TESTERS) */
 
/**************************************************************************/
/*XB*/
#ifdef CHECK_MEMORY
void AI_CheckMemory(void)
{
	Mmg_M_CheckMemory(AI);
}
#endif /* CHECK_MEMORY */
/*End XB*/
 
/**************************************************************************/
/* XB 02/06/99 */
#ifndef FINAL_VERSION
unsigned long AI_fn_ulGetUsedStaticMemory(void)
{
	return Mmg_M_GetUsedStaticMemory(AI);
}
#endif /* FINAL_VERSION */
/* End XB 02/06/99 */
 
/***************************************
 * Set the memory block used by the AI *
 ***************************************/
void AI_fn_vAIUseFixMemory(void)
{
 AI_g_ucMemoryBlockUsed = E_ucAIBlockFix;
}
 
void AI_fn_vAIUseLevelMemory(void)
{
 AI_g_ucMemoryBlockUsed = E_ucAIBlockLevel;
}
 
unsigned char AI_g_ucDynamicAlloc = FALSE;
 
void *AI_fn_p_vTrueAlloc(unsigned long ulSize)
{
 void *p_vPointer = NULL;
	
 M_AIChooseMemoryBlock();
 
#if defined(U64) && !defined(FINAL_VERSION)
 g_ucModuleIdForDebug=1;
#endif
 
 if (AI_g_ucDynamicAlloc||(p_vPointer = Mmg_fn_p_vAlloc4Ch(ulSize,C_ucMmgDefaultChannel))==NULL)
 {
  #if defined(_DEBUG)
  if (!AI_g_ucDynamicAlloc)
  {
   Erm_M_ClearLastError(C_ucErmDefaultChannel);
   M_AIWarningError(E_uwAIDebugDynamicAllocation,C_ucErmOpenInfoWindow);
   Erm_M_ClearLastError(C_ucErmDefaultChannel);
   AI_g_ucDynamicAlloc = TRUE;
  }
  Mmg_M_SetModeAlloc4Ch(AI,E_ucDynamic,C_ucMmgDefaultChannel);
  p_vPointer = Mmg_fn_p_vAlloc4Ch(ulSize,C_ucMmgDefaultChannel);
  #endif /* _DEBUG */
 }
 memset(p_vPointer,0,ulSize);
 
#if defined(U64) && !defined(FINAL_VERSION)
 g_ucModuleIdForDebug=0xff;
#endif
 
 return (p_vPointer);
}
 
 
#ifndef _FIRE_DEADCODE_U64_ /* Added by RUC */
void *AI_fn_p_vTrueRealloc(void *p_vOldPointer,unsigned long ulSize)
{
 void *p_vPointer = NULL;
	
 M_AIChooseMemoryBlock();
 
 if (AI_g_ucDynamicAlloc||(p_vPointer = Mmg_fn_p_vRealloc4Ch(p_vOldPointer,ulSize,C_ucMmgDefaultChannel))==NULL)
 {
  #if defined(_DEBUG)
  if (!AI_g_ucDynamicAlloc)
  {
   Erm_M_ClearLastError(C_ucErmDefaultChannel);
   M_AIWarningError(E_uwAIDebugDynamicAllocation,C_ucErmOpenInfoWindow);
   Erm_M_ClearLastError(C_ucErmDefaultChannel);
   AI_g_ucDynamicAlloc = TRUE;
  }
  Mmg_M_SetModeAlloc4Ch(AI,E_ucDynamic,C_ucMmgDefaultChannel);
  p_vPointer = Mmg_fn_p_vAlloc4Ch(ulSize,C_ucMmgDefaultChannel);
  memcpy(p_vPointer,p_vOldPointer,ulSize);
  AI_fn_vTrueFree(p_vOldPointer);
  #endif /* _DEBUG */
 }
 return (p_vPointer);
}
#endif /* _FIRE_DEADCODE_U64_ */ /* Added by RUC */
 
 
#ifndef _FIRE_DEADCODE_U64_ /* Added by RUC */
void AI_fn_vTrueFree(void *p_vPointer)
{
 #if defined(_DEBUG)
 unsigned short uwBlocId;
 void *p_vBeginBloc;
 #endif /* _DEBUG */
 
 #if defined(_DEBUG)
/* Mmg_fn_vTestMallocIntegrityAt(p_vPointer);*/
 #endif /*_DEBUG*/
 
 M_AIChooseMemoryBlock();
 #if defined(_DEBUG)
 Mmg_fn_vWhereIs((void*)p_vPointer,&uwBlocId,&p_vBeginBloc);
 if (uwBlocId==0xffff)
  Mmg_M_SetModeAlloc4Ch(AI,E_ucDynamic,C_ucMmgDefaultChannel);
 else
  Mmg_M_SetModeAlloc4Ch(AI,uwBlocId&0x00ff,C_ucMmgDefaultChannel);
 #endif /* _DEBUG */
 Mmg_fn_vFree4Ch(p_vPointer,C_ucMmgDefaultChannel);
}
#endif /* _FIRE_DEADCODE_U64_ */ /* Added by RUC */
 
#ifndef _FIRE_DEADCODE_U64_ /* Added by RUC - Oliv' */
void AI_fn_vMemoryLogFile(void *p_vPointer,unsigned char ucAction,char *szFile,unsigned long ulLine)
{
 #if defined(_DEBUG)&& defined(AI_D_DebugMalloc)
 static unsigned long AI_s_ulNumberOfAllocation = 0;
 FILE *p_stFile;
 char szFileName[30];
 unsigned short uwBlocId;
 void *p_vBeginBloc;
 
 Mmg_fn_vWhereIs((void*)p_vPointer,&uwBlocId,&p_vBeginBloc);
 sprintf(szFileName,"Mem%04x.log",uwBlocId);
 if ((p_stFile = fopen(szFileName,"rt"))!=NULL) 
  fclose(p_stFile);
 else
  AI_s_ulNumberOfAllocation = 0;
 p_stFile = fopen(szFileName,"at");
 if (p_stFile!=NULL)
 {
  if (ucAction==AI_C_ActionMalloc) 
  {
   AI_s_ulNumberOfAllocation++;
   fprintf(p_stFile,"Malloc  : Number=#%010d, Block=#%04x, Offset=%p (%20s,%10d)\n",AI_s_ulNumberOfAllocation,uwBlocId,(long)p_vPointer-(long)p_vBeginBloc,szFile,ulLine);
  }
  if (ucAction==AI_C_ActionRealloc) 
  {
   fprintf(p_stFile,"Realloc : Number=#%010d, Block=#%04x, Offset=%p (%20s,%10d)\n",AI_s_ulNumberOfAllocation,uwBlocId,(long)p_vPointer-(long)p_vBeginBloc,szFile,ulLine);
  }
  else if (ucAction==AI_C_ActionFree) 
  {
   AI_s_ulNumberOfAllocation--;
   fprintf(p_stFile,"Free    : Number=#%010d, Block=#%04x, Offset=%p (%20s,%10d)\n",AI_s_ulNumberOfAllocation,uwBlocId,(long)p_vPointer-(long)p_vBeginBloc,szFile,ulLine);
  }
  fclose(p_stFile);
 }
 
 #endif /* _DEBUG && AI_D_DebugMalloc */
}
#endif /* _FIRE_DEADCODE_U64_ */ /* Added by RUC - Oliv' */
 
void fn_vInitAI(ACP_tdxBool _bLoadSnapShot)
{
    /* init function pointers tables*/
#if !defined(OPTIMIZED_COMMAND)
	fn_vInitFieldEntries();
 	fn_vInitOperatorEntries();
	fn_vInitMetaActionEntries();
	fn_vInitProcedureEntries();
	fn_vInitConditionEntries();
	fn_vInitFunctionEntries();
	fn_vInitKeyWordEntries();
#endif
	
#ifdef ACTIVE_AIDEBUG   /*** DR ***/
	AIDebug_fnv_InitMain();
#endif /*ACTIVE_AIDEBUG*/
 
	/* Blocking action management*/
	g_ucNewActionReturn = C_ACTION_ENGINE_NOTDEFINED; /* to set the action type using the script*/
	g_ucUseDefaultActionReturn = TRUE;/* the g_ucNewActionReturn is not taking into account*/
	
#if defined(AI_USE_SCRIPT)
	SCR_fn_v_Link_InitTable(&g_stMacroLinkTable);	
 
	SCR_fn_v_Link_InitTable(&g_stComportLinkTable);	
	SCR_fn_v_Link_InitTable(&g_stModelLinkTable);
	SCR_fn_v_Link_InitTable(&g_stDsgVarLinkTable);
	SCR_fn_v_Link_InitTable(&g_stDefinesLinkTable);
 
#endif /* AI_USE_SCRIPT */
	if (!_bLoadSnapShot)
		fn_vReadAIDefines(C_DefineAIFiles);
}
 
/*---------------------------------------------------------------------------*/
/*                        Moteur d'intelligence du Perso.*/
/*---------------------------------------------------------------------------*/
ACP_tdxBool fn_bDoIntelligencePerso(HIE_tdxHandleToSuperObject p_SuperObjPerso)
{
	AI_tdstMind *p_stPerso = AI_M_stGetMindOfSuperObj(p_SuperObjPerso);
	AI_M_SetDoingIntel(p_stPerso, 1);
    
	/* to avoid problems*/
	if (AI_M_p_stGetIntelligence(p_stPerso)!=NULL)
	{
#ifdef ACTIVE_AIDEBUG   /*** DR ***/
		if ( AI_M_p_stGetReflex(p_stPerso) == NULL ) /*for mind with intelligence but no reflex*/
		{
#ifndef U64_AIDEBUG
			AIDebug_M_EnterEngineLoop( p_stPerso );
#else
			AIDebug_M_EnterEngineLoop( p_SuperObjPerso );
#endif /* U64_AIDEBUG */
		}
		AIDebug_M_SetReflexOrAI( p_stPerso, AI_M_bGetDoingIntel(p_stPerso) );
#endif /*ACTIVE_AIDEBUG*/
		return fn_bIntelligenceEngine(p_SuperObjPerso, AI_M_p_stGetIntelligence(p_stPerso));
	}
	else 
		return FALSE;
}
 
/*---------------------------------------------------------------------------*/
/*                           Moteur de reflexe du Perso.*/
/*---------------------------------------------------------------------------*/
ACP_tdxBool fn_bDoReflexPerso(HIE_tdxHandleToSuperObject p_SuperObjPerso)
{
	AI_tdstMind *p_stPerso = AI_M_stGetMindOfSuperObj(p_SuperObjPerso);
    
	AI_M_SetDoingIntel(p_stPerso, 0);
    
	/* to avoid problems*/
	if (AI_M_p_stGetReflex(p_stPerso)!=NULL)
	{
#ifdef ACTIVE_AIDEBUG   /*** DR ***/
#ifndef U64_AIDEBUG
		AIDebug_M_EnterEngineLoop( p_stPerso );
#else
		AIDebug_M_EnterEngineLoop( p_SuperObjPerso );
#endif /* U64_AIDEBUG */
		AIDebug_M_SetReflexOrAI( p_stPerso, AI_M_bGetDoingIntel(p_stPerso) );
#endif /*ACTIVE_AIDEBUG*/
		return fn_bIntelligenceEngine(p_SuperObjPerso, AI_M_p_stGetReflex(p_stPerso));
	}
	else
		return FALSE;
}
 
#if defined(AI_USE_SCRIPT)
void fn_vSecondPassOfTree(AI_tdxHandleToMind p_stMind,tdstTreeInterpret *p_stTree)
{
	unsigned short i;
	tdstNodeInterpret *p_stNode;
	long lKey;
 
#if !defined(__DEBUG_AI__)		        
    p_stMind=p_stMind;
#endif
	
	if (p_stTree != NULL)
	{
		for (i = 0; i < M_GetNbNodeInterpret(p_stTree); i++)
		{
			p_stNode = M_GetNodeInterpretN(p_stTree, i);
			lKey=M_lKeyLinkInterpret(p_stNode);
 
			switch (M_GetTypeInterpret(p_stNode))
			{			
 
			case E_ti_MacroRef:
				M_TestLinkTableValue(p_stMind,lKey,SCR_M_p_sz_Link_GetKey((SCR_tdst_Link_Value *) (lKey)));
				M_p_stMacroInterpret(p_stNode) = (tdstMacro*) (M_GetLinkValueWithKey(lKey));
				break;
			case E_ti_ModelRef:
			    M_TestLinkTableValue(p_stMind,lKey,SCR_M_p_sz_Link_GetKey((SCR_tdst_Link_Value *) (lKey)));
				M_p_stModelInterpret(p_stNode) = (AI_tdstAIModel*) (M_GetLinkValueWithKey(lKey));
				break;
 
			case E_ti_DsgVar:
				M_SetTypeInterpret(p_stNode,E_ti_DsgVarRef);
				break;
 
			case E_ti_DsgVarRef:
			    M_TestLinkTableValue(p_stMind,lKey,SCR_M_p_sz_Link_GetKey((SCR_tdst_Link_Value *) (lKey)));
				M_lValueInterpret(p_stNode) = (long) (M_GetLinkValueWithKey(lKey));
				break;
 
			case E_ti_SuperObjectRef:
			    M_TestLinkTableValue(p_stMind,lKey,SCR_M_p_sz_Link_GetKey((SCR_tdst_Link_Value *) (lKey)));
				M_SuperObjectInterpret(p_stNode) = (HIE_tdxHandleToSuperObject)(M_GetLinkValueWithKey(lKey));
				break;
			
			case E_ti_PersoRef:
				{
					struct tdstEngineObject_ *p_stEngineObject;

					M_TestLinkTableValue(p_stMind,lKey,SCR_M_p_sz_Link_GetKey((SCR_tdst_Link_Value *) (lKey)));
					p_stEngineObject = M_p_stPersoRefInterpret(p_stNode) = (tdstEngineObject *)(M_GetLinkValueWithKey(lKey));
					#if defined (ACTIVE_EDITOR)
					/* if the reference is on an always */
					if ( p_stEngineObject && (p_stEngineObject != (void *)0x12345678) && fn_ucIsAnAlwaysObject(p_stEngineObject) )
					{
						/* look for the corresponding entry in the always table and mark it referenced */
						/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
						unsigned long				i;
						ALW_tdxHandleToModelList	h_AlwaysModelChild;
						/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
 
						LST2_M_DynamicForEachElementOf(&(g_stAlways.ALW_h_LstAlwaysModel),h_AlwaysModelChild,i)
						{
							if ( M_ObjectGetPersonalType(p_stEngineObject) == M_ObjectGetPersonalType(h_AlwaysModelChild->p_stAlwaysObject))
							{
								g_stAlways.d_bIsReferencedInLevel[i] = TRUE;
								break;
							}
						}
					}
					#endif /* ACTIVE_EDITOR */
				}
				break;
				
			case E_ti_ModuleRef:
				M_TestLinkTableValue(p_stMind,lKey,SCR_M_p_sz_Link_GetKey((SCR_tdst_Link_Value *) (lKey)));
				M_lModuleInterpret(p_stNode) = (long)(M_GetLinkValueWithKey(lKey));
				break;
 
			case E_ti_ActionRef:
#if defined(AI_LOGFILE) 
				if (fpAILogFile)
				{
#ifdef _DEBUG_STRING_FOR_PLA_
					if (SCR_M_e_Link_GetState((SCR_tdst_Link_Value *) (lKey) ) != SCR_ELS_Link_NotInitialized) 					
					{
					  tdxHandleToState h_State =(tdxHandleToState) (M_GetLinkValueWithKey(lKey));
					  tdstAnim3d *p_stAnim=fn_p_stGetAnimInState(h_State);
					  fprintf(fpAILogFile,"%s : %s\n",p_stAnim->szAnimName,SCR_M_p_sz_Link_GetKey((SCR_tdst_Link_Value *) (lKey)));
					}
#endif
				}
#endif
 
			    M_TestLinkTableValue(p_stMind,lKey,SCR_M_p_sz_Link_GetKey((SCR_tdst_Link_Value *) (lKey)));
				M_ActionInterpret(p_stNode) = (tdxHandleToState)(M_GetLinkValueWithKey(lKey));
				break;
				
			case E_ti_ComportRef:
			    M_TestLinkTableValue(p_stMind,lKey,SCR_M_p_sz_Link_GetKey((SCR_tdst_Link_Value *) (lKey)));
				M_ComportInterpret(p_stNode) = (tdstComport *)(M_GetComportLinkValueWithKey(lKey));
				break;
				
			case E_ti_WayPointRef:
	  		    M_TestLinkTableValue(p_stMind,lKey,SCR_M_p_sz_Link_GetKey((SCR_tdst_Link_Value *) (lKey)));
				M_lWayPointInterpret(p_stNode) = (WP_tdhWayPoint)(M_GetLinkValueWithKey(lKey));
				break;
 
			case E_ti_ObjectTableRef:
				M_TestLinkTableValue(p_stMind,lKey,SCR_M_p_sz_Link_GetKey((SCR_tdst_Link_Value *) (lKey)));
				M_lModuleInterpret(p_stNode) = (long)(M_GetLinkValueWithKey(lKey));
				break;
 
			case E_ti_GameMaterialRef:
				M_TestLinkTableValue(p_stMind,lKey,SCR_M_p_sz_Link_GetKey((SCR_tdst_Link_Value *) (lKey)));
				M_GameMaterialInterpret(p_stNode) = (GMT_tdxHandleToGameMaterial)(M_GetLinkValueWithKey(lKey));
#ifndef U64
				DEMO_fn_vPutGMTInList ((GMT_tdxHandleToGameMaterial)(M_GetLinkValueWithKey(lKey)));
#endif
				break;
 
/* ANNECY MT - 25/09/98 {*/
			case E_ti_Graph:
				M_TestLinkTableValue(p_stMind,lKey,SCR_M_p_sz_Link_GetKey((SCR_tdst_Link_Value *) (lKey)));
				M_p_stGraphInterpret(p_stNode) = (WP_tdHandleOfGraph)(M_GetLinkValueWithKey(lKey));
				break;
/* END ANNECY MT }*/
			}
		}
	}
}
 
void CFast_vInitStaticTree ( struct tdstNodeInterpret_ *, long, struct tdstNodeInterpret_ * ) ;
 
void fn_vSecondPassOfScriptAI(AI_tdxHandleToMind p_stMind,tdstScriptAI *p_stScriptAI)
{
	unsigned long i;
	unsigned char j;
	tdstComport *p_stComport;
	
	/* Loop on comport.*/
 
	for (i = 0; i < M_GetScriptAINbComport(p_stScriptAI); i++)
	{
		p_stComport = M_GetScriptAIComportN(p_stScriptAI, i);
		
		/* Second pass on Schedule.*/
		fn_vSecondPassOfTree(p_stMind,M_GetComportSchedule(p_stComport));
		
		/* Second pass on Rules.*/
		for (j = 0; j < M_GetComportNbRules(p_stComport); j++)
		{
			fn_vSecondPassOfTree(p_stMind,M_GetComportRuleN(p_stComport, j));
		}
	}
  /* CFAST : init reference */
  CFast_vInitStaticTree ( p_stMind->p_stAIModel->CFast_dst_ParamArray, 
                          p_stMind->p_stAIModel->uwNbParamNode, 
                          p_stMind->p_stAIModel->CFast_dst_RefTreeArray) ; 
}
#endif /* AI_USE_SCRIPT */
 
void fn_vReinitDesignerVariablesWithFlags(AI_tdxHandleToMind p_stMind,tdeObjectTreeInit eObjIniType)
{
	if (p_stMind!=NULL)
	{
		/* if designer variable*/
		if (M_GetDsgMem(p_stMind)!=NULL)
		{
			char *ptrSrc=NULL;
			char *ptrDst=M_GetDsgMemBuffer(p_stMind);
			unsigned char ucVarId;
 
		    /* reinit current values*/
			if (M_GetDsgMemBufferInit(p_stMind)==NULL)
			{
				/* from init values in model */
				ptrSrc=M_GetDsgMemDefaultInit(p_stMind);
			}
			else
			{
				/* from init values in perso*/
				ptrSrc=M_GetDsgMemBufferInit(p_stMind);
			}        
 
			/* loop on each dsgvar*/
			for (ucVarId=0;ucVarId<M_GetNbDsgVar(p_stMind);ucVarId++)
			{
				tdeDsgVarTypeId eDsgVarType=M_GetDsgVarType(p_stMind,ucVarId);
				
				/* don't reinit list*/
				if (eDsgVarType==eDsgVarType_List)
				{
/* ANNECY MT - 05/10/98 {*/
					tdstList *p_stDstList=(tdstList*) ( (char*) (ptrDst+M_GetDsgVarOffset(p_stMind,ucVarId)) );
					tdstList *p_stSrcList=(tdstList*) ( (char*) (ptrSrc+M_GetDsgVarOffset(p_stMind,ucVarId)) );
 
					M_InitList(p_stDstList,M_ucGetMaxSizeOfList(p_stSrcList));
/* END ANNECY MT }*/
				}
				/*
				// don't reinit array
				else if (fn_GetDsgVarType(eDsgVarType)==E_vt_Array)
				{
				}
				*/
				else /* array too*/
				{
					tdeObjectTreeInit eFlags=M_GetDsgVarInitType(p_stMind,ucVarId);
			
					/* if we have to reinit this DsgVar*/
					if (eObjIniType<=eFlags)
					{
						/* Offset of value of DsgVar*/
						unsigned long ulMyVarOffset=M_GetDsgVarOffset(p_stMind,ucVarId);
						unsigned long ulMyVarSize;
 
						if (fn_GetDsgVarType(eDsgVarType)==E_vt_Array)
						{
							 tdstArray *p_stArray=(tdstArray*) M_GetDsgVarAddrDefault(p_stMind,ucVarId);
							 ulMyVarSize=fn_ulSizeOfDsgVar(eDsgVarType,M_ARRAY_SIZE(p_stArray));	
						}
						else
							ulMyVarSize=fn_ulSizeOfDsgVar(eDsgVarType,0);
						memcpy(ptrDst + ulMyVarOffset,ptrSrc + ulMyVarOffset,ulMyVarSize);
					}	  
				} 
			}
		}
	}
}
 
/* POTICHE*/
 
void FirstInitDesignerVariables(AI_tdxHandleToMind p_stMind)
{
	if (p_stMind!=NULL)
	{
		/* if designer variable*/
		if (M_GetDsgMem(p_stMind)!=NULL)
		{			
			/* copy current values*/
			if (M_GetDsgMemBufferInit(p_stMind)==NULL)
			{
				/* from init values in model */
				memcpy(M_GetDsgMemBuffer(p_stMind),M_GetDsgMemDefaultInit(p_stMind),M_GetDsgVarSize(p_stMind));
			}
			else
			{
				/* from init values in perso*/
				memcpy(M_GetDsgMemBuffer(p_stMind),M_GetDsgMemBufferInit(p_stMind),M_GetDsgVarSize(p_stMind));
			}
		}
	}
}
 
void ReinitDesignerVariables(AI_tdxHandleToMind p_stMind)
{
/* ANNECY MT - 11/09/98 {*/
	/*
	if (p_stMind!=NULL)
	{
		// if designer variable
		if (M_GetDsgMem(p_stMind)!=NULL)
		{
			// copy current values
			if (M_GetDsgMemBufferInit(p_stMind)==NULL)
			{
				// from init values in model 
				memcpy(M_GetDsgMemBuffer(p_stMind),M_GetDsgMemDefaultInit(p_stMind),M_GetDsgVarSize(p_stMind));
			}
			else
			{
				// from init values in perso
				memcpy(M_GetDsgMemBuffer(p_stMind),M_GetDsgMemBufferInit(p_stMind),M_GetDsgVarSize(p_stMind));
			}
		}
	}
	*/
	if (p_stMind!=NULL)
	{
		/* if designer variable*/
		if (M_GetDsgMem(p_stMind)!=NULL)
		{
			char *ptrSrc=NULL;
			char *ptrDst=M_GetDsgMemBuffer(p_stMind);
			unsigned char ucVarId;
			
			/* reinit current values*/
			if (M_GetDsgMemBufferInit(p_stMind)==NULL)
			{
				/* from init values in model */
				ptrSrc=M_GetDsgMemDefaultInit(p_stMind);
			}
			else
			{
				/* from init values in perso*/
				ptrSrc=M_GetDsgMemBufferInit(p_stMind);
			}        
			
			/* loop on each dsgvar*/
			for (ucVarId=0;ucVarId<M_GetNbDsgVar(p_stMind);ucVarId++)
			{
				tdeDsgVarTypeId		eDsgVarType	= M_GetDsgVarType(p_stMind,ucVarId);
				tdeObjectTreeInit	eFlags		= M_GetDsgVarInitType(p_stMind,ucVarId);
 
				if (eFlags != OTI_WhenGameStart)
				{
					/* Offset of value of DsgVar*/
					unsigned long ulMyVarOffset=M_GetDsgVarOffset(p_stMind,ucVarId);
					unsigned long ulMyVarSize;
 
					if (fn_GetDsgVarType(eDsgVarType)==E_vt_Array)
					{
						 tdstArray *p_stArray=(tdstArray*) M_GetDsgVarAddrDefault(p_stMind,ucVarId);
						 ulMyVarSize=fn_ulSizeOfDsgVar(eDsgVarType,M_ARRAY_SIZE(p_stArray));	
					}
					else
						ulMyVarSize=fn_ulSizeOfDsgVar(eDsgVarType,0);
					memcpy(ptrDst + ulMyVarOffset,ptrSrc + ulMyVarOffset,ulMyVarSize);
				}	  
			}
		}
	}	
	/**/
/* END ANNECY MT }*/
}
 
 
void fn_vInsertDsgvarOneDsgVarInSAI(char *p_MyVarAddr,tdeDsgVarTypeId eDsgVarType,SAI_tdeFlags eFlags)
{
	switch(eDsgVarType)
	{
		/* pointers*/
		case eDsgVarType_WayPoint:
		case eDsgVarType_Comport:
		case eDsgVarType_Action:
		case eDsgVarType_Perso:
		case eDsgVarType_GameMaterial:
		  SAI_fn_bInsertPointerInTable((void *) p_MyVarAddr, eFlags);
		  break;
		case eDsgVarType_List: 
	   	  /* never initialized so nothing to do*/
		  break;
		case eDsgVarType_PersoArray:
		case eDsgVarType_VectorArray:
		case eDsgVarType_FloatArray:
		case eDsgVarType_IntegerArray:
		case eDsgVarType_WayPointArray:
		case eDsgVarType_TextArray:
		  /* should not happen*/
		  break;
 
/* Oliv' 06/08/1998*/
#if !defined(U64)
 
		default:
  		  /* values*/
		  SAI_fn_bInsertArrayInTable((void *) p_MyVarAddr, fn_ulSizeOfDsgVar(eDsgVarType,0), eFlags);
		  break;
 
#else  /* U64 */
 
/* Oliv' - 07/07/1999 - remove boolean save (considered as char) */
		/*case eDsgVarType_Boolean:
			SAI_fn_bInsertBoolInTable( (void *)p_MyVarAddr,1, eFlags);
			break;*/
/*		case eDsgVarType_Boolean:
			SAI_fn_bInsertCharInTable ( (void *)p_MyVarAddr, eFlags );
osSyncPrintf( "Inserting Bool at 0x%x\n", p_MyVarAddr );
			break;*/
/* EndOfOliv' */
		default:
		{
			register unsigned long ulSize = fn_ulSizeOfDsgVar( eDsgVarType, 0 );
			switch( ulSize )
			{
				case 1 : SAI_fn_bInsertCharInTable ( (void *)p_MyVarAddr, eFlags );					break;
				case 2 : SAI_fn_bInsertShortInTable( (void *)p_MyVarAddr, eFlags );					break;
				case 4 : SAI_fn_bInsertLongInTable ( (void *)p_MyVarAddr, eFlags );					break;
				default: SAI_fn_bInsertArrayInTable( (void *)p_MyVarAddr, ulSize, eFlags );	break;
			}
		  break;
		}
 
#endif /* U64 */
/* EndOfOliv'*/
	}
}
 
void AI_fn_vInsertDsgVarInSAI(AI_tdstMind *p_stMind)
{
 
#ifdef ACTIVE_EDITOR
	if (g_bUseSAIWithEditor)
	{
#endif /* ACTIVE_EDITOR */
 
  if (p_stMind!=NULL)
  {
	/* if DsgVar exists*/
    if ( (AI_M_p_stGetDsgMem(p_stMind) != NULL) && (AI_M_p_stGetDsgVar(p_stMind)!=NULL) )
    {
	  unsigned char ucVarId;
	  /* DsgVar loop*/
      for (ucVarId=0;ucVarId<M_GetNbDsgVar(p_stMind);ucVarId++)
	  {
        SAI_tdeFlags eFlags=M_GetDsgVarSaveType(p_stMind,ucVarId);
		/* if we have to save this DsgVar*/
		if (eFlags!=(SAI_tdeFlags) 0)
		{
		  /* Adress of current value of this DsgVar*/
          char *p_MyVarAddr=(char*) M_GetDsgVarAddr(p_stMind,ucVarId);
		  tdeDsgVarTypeId eDsgVarType=M_GetDsgVarType(p_stMind,ucVarId);
 
		  /* array*/
		  if (fn_GetDsgVarType(eDsgVarType)==E_vt_Array)
		  {
			unsigned char ucIndex=0;
			tdstArray *p_stArray=(tdstArray*) p_MyVarAddr;
			tdeDsgVarTypeId eDsgVarTypeId=M_ARRAY_TYPE(p_stArray);
 
			for (ucIndex=0;ucIndex<M_ARRAY_SIZE(p_stArray);ucIndex++)
			{
				p_MyVarAddr=(char*) M_ARRAY_ELEMENT(p_stArray,ucIndex);
				fn_vInsertDsgvarOneDsgVarInSAI(p_MyVarAddr,eDsgVarTypeId,eFlags);
			}
		  }
		  else
		  {
			fn_vInsertDsgvarOneDsgVarInSAI(p_MyVarAddr,eDsgVarType,eFlags);
		  }
		}
	  }
	}
  }
 
#ifdef ACTIVE_EDITOR
	}
#endif /* ACTIVE_EDITOR */
 
 
}
 
#if defined(AI_USE_SCRIPT)
 
#define CHOOSE_MODEL_DSGVAR 0
#define CHOOSE_PERSO_DSGVAR 1
 
void fn_vSecondPassOfOneDsgVar(AI_tdxHandleToMind p_stMind,char *p_MyVarAddr,tdeDsgVarTypeId eDsgVarType)
{
	SCR_tdst_Link_Value *p_stKey=(SCR_tdst_Link_Value *) ( *((long*)p_MyVarAddr) );
  switch(eDsgVarType)
	{
	case eDsgVarType_GameMaterial:
		/* game material pas initialise*/
    if ( p_stKey != NULL )
		{
      M_TestLinkTableValue(p_stMind,p_stKey,"DsgVar unknown game material reference");
      (*(C_TypeOfGameMaterial *)p_MyVarAddr) = (C_TypeOfGameMaterial) M_GetLinkValueWithKey(p_stKey);
		}
		break;
 
  case eDsgVarType_Perso:
		/* perso pas initialise*/
    if (p_stKey!=NULL) 
		{
      tdstEngineObject *p_stObject=NULL;
      M_TestLinkTableValue(p_stMind,p_stKey,"DsgVar unknown perso reference");
      if ( SCR_M_e_Link_GetState(p_stKey) == SCR_ELS_Link_Initialized )
      {
        p_stObject = (tdstEngineObject *) M_GetLinkValueWithKey(p_stKey);
        (*(C_TypeOfPerso *)p_MyVarAddr) = p_stObject ? M_GetSuperObject(p_stObject) : NULL;
      }
      else
        (*(C_TypeOfPerso *)p_MyVarAddr) = NULL;
		}
		break;
 
/* ANNECY OA - 13/08/99 { */
#ifndef U64		
  case eDsgVarType_SuperObject:
		/* super objet pas initialise*/
    if (p_stKey!=NULL) 
		{
      M_TestLinkTableValue(p_stMind,p_stKey,"DsgVar unknown SuperObject reference");
      if ( SCR_M_e_Link_GetState(p_stKey) == SCR_ELS_Link_Initialized )
      {
        (*(C_TypeOfSuperObject *)p_MyVarAddr) = (HIE_tdxHandleToSuperObject) M_GetLinkValueWithKey(p_stKey);
      }
      else
        (*(C_TypeOfSuperObject *)p_MyVarAddr) = NULL;
		}
		break;
#endif
/* END ANNECY OA } */
  
  case eDsgVarType_WayPoint: 
    /* waypoint pas initialise*/
		if (p_stKey!=(SCR_tdst_Link_Value *) WP_C_hWayPointInvalid) 
		{
      M_TestLinkTableValue(p_stMind,p_stKey,"DsgVar unknown waypoint reference");
      (*(C_TypeOfWayPoint *)p_MyVarAddr) = (C_TypeOfWayPoint) M_GetLinkValueWithKey(p_stKey);
		}
		break;
 
	case eDsgVarType_Comport: 
    /* comport pas initialisee*/
		if (p_stKey!=NULL) 
		{
      M_TestLinkTableValue(p_stMind,p_stKey,"DsgVar unknown comport reference");
      *((C_TypeOfComport *)p_MyVarAddr) = (C_TypeOfComport) M_GetLinkValueWithKey(p_stKey);
		}
		break;
 
	case eDsgVarType_Action: 
    /* action pas initialisee*/
		if (p_stKey!=NULL) 
		{
      M_TestLinkTableValue(p_stMind,p_stKey,"DsgVar unknown action reference");
      *((C_TypeOfAction *)p_MyVarAddr) = (C_TypeOfAction) M_GetLinkValueWithKey(p_stKey);
		}
		break;
 
	case eDsgVarType_Graph:
		/* graph not initialized*/
		if (p_stKey!=NULL) 
		{
      M_TestLinkTableValue(p_stMind,p_stKey,"DsgVar unknown graph reference");
      (*(C_TypeOfGraph *)p_MyVarAddr) = (C_TypeOfGraph) M_GetLinkValueWithKey(p_stKey);
		}
    break;
	}
}
 
void fn_vSecondPassOfDsgVar(AI_tdxHandleToMind p_stMind,unsigned char ucDsgVarId,unsigned char ucChoosePointer)
{
  if (p_stMind!=NULL)
  {
	tdeDsgVarTypeId eDsgVarType=M_GetDsgVarType(p_stMind,ucDsgVarId);
    char *p_MyVarAddr;
 
	if (ucChoosePointer==CHOOSE_MODEL_DSGVAR)
	{
	  p_MyVarAddr=(char*) M_GetDsgVarAddrDefault(p_stMind,ucDsgVarId);
	}
	else
	{
	  p_MyVarAddr=(char*) M_GetDsgVarAddrInit(p_stMind,ucDsgVarId);
	}
 
    /* array*/
	if (fn_GetDsgVarType(eDsgVarType)==E_vt_Array)
	{
		unsigned char ucIndex=0;
		tdstArray *p_stArray=(tdstArray*) p_MyVarAddr;
		tdeDsgVarTypeId eDsgVarTypeId=M_ARRAY_TYPE(p_stArray);
 
		for (ucIndex=0;ucIndex<M_ARRAY_SIZE(p_stArray);ucIndex++)
		{
			p_MyVarAddr=(char*) M_ARRAY_ELEMENT(p_stArray,ucIndex);
			fn_vSecondPassOfOneDsgVar(p_stMind,p_MyVarAddr,eDsgVarTypeId);
		}
	}
    else
	{
		fn_vSecondPassOfOneDsgVar(p_stMind,p_MyVarAddr,eDsgVarType);
	}
  }
}
 
 
void fn_vSecondPassOfDsgMem(AI_tdxHandleToMind p_stMind, ACP_tdxBool _bPersoInFix, enum tdeObjectTreeInit_ _eObjectInit)
{
	/* si il y a des variables designers*/
	if (M_GetDsgMem(p_stMind)!=NULL)
	{
		unsigned char ucDsgVarId;
		for (ucDsgVarId=0;ucDsgVarId<M_GetNbDsgVar(p_stMind);ucDsgVarId++)
		{
 
/* ANNECY MT - 11/09/98 {*/
#if !defined(ACTIVE_EDITOR)	/* {*/
			tdeObjectTreeInit eFlags=M_GetDsgVarInitType(p_stMind,ucDsgVarId);
 
			/* update type of reinit (OTI_WhenGameStart can be used only with actor in Fix)*/
			if (!_bPersoInFix && (eFlags == OTI_WhenGameStart))
				M_GetDsgVarInitType(p_stMind,ucDsgVarId)=OTI_MapLoaded;
#endif /* ACTIVE_EDITOR }			*/
/* END ANNECY MT }*/
 
			/* for model : default values*/
			/* so that perso are initialized only once in model */
			if (!AI_M_ucGetSecondPassDone(AI_M_p_stGetAIModel(p_stMind)) )
			{
				fn_vSecondPassOfDsgVar(p_stMind,ucDsgVarId,CHOOSE_MODEL_DSGVAR);
			}
			
			/* for perso : special values*/
			if (M_GetDsgMemBufferInit(p_stMind)!=NULL)
			{
				fn_vSecondPassOfDsgVar(p_stMind,ucDsgVarId,CHOOSE_PERSO_DSGVAR);
			}
		}
		if (_bPersoInFix)
			fn_vReinitDesignerVariablesWithFlags(p_stMind, _eObjectInit);
		else
			fn_vReinitDesignerVariablesWithFlags(p_stMind, OTI_WhenGameStart);
	}
}
 
 
void fn_vSecondPassOfMacro(AI_tdxHandleToMind p_stMind, tdstMacro *p_stMacro)
{
	fn_vSecondPassOfTree(p_stMind, M_GetMacroInitTree(p_stMacro));
}
 
void fn_vSecondPassOfListMacro(AI_tdxHandleToMind p_stMind)
{
	unsigned char i;
	tdstListOfMacro *p_stListOfMacro = AI_M_p_stGetListOfMacroAIModel(AI_M_p_stGetAIModel(p_stMind));
	if ( p_stListOfMacro )
	for (i = 0; i < M_GetNbMacro(p_stListOfMacro); i++)
		fn_vSecondPassOfMacro(p_stMind, M_GetMacroN(p_stListOfMacro, i));
}
 
/* Comport init in model and for perso*/
void fn_vSecondPassOfComport(AI_tdxHandleToMind p_stMind,tdstIntelligence *p_stIntelligence)
{
  if (p_stIntelligence!=NULL)
  {
	tdstScriptAI *p_stScriptAI=*(p_stIntelligence->p_p_stScriptAI);
    unsigned long ulComportInit=0;
	long lKey;
 
    if (p_stScriptAI!=NULL)
	{
	  /* so that init comport is initialized only once in model */
	  if (!AI_M_ucGetSecondPassDone(AI_M_p_stGetAIModel(p_stMind)) )
	  {
        ulComportInit=M_GetScriptAINoComportInitDefault(p_stScriptAI);
 
		if (ulComportInit!=0)
		{
			lKey=ulComportInit;
            M_TestLinkTableValue(p_stMind,lKey,"Error in ComportInit In Model (.RUL or .RFX)");
			ulComportInit=(unsigned long) M_GetComportLinkValueWithKey(lKey);
		}
		else
			ulComportInit = (unsigned long)M_GetScriptAIComport(p_stScriptAI);
		M_GetScriptAINoComportInitDefault(p_stScriptAI)=ulComportInit;
	  }
	}
 
    /* init comport for perso*/
	ulComportInit=M_GetNoComportInit(p_stIntelligence);
	if (ulComportInit==0)
	{
       ulComportInit=M_GetScriptAINoComportInitDefault(p_stScriptAI);  
    }
	else
	{
 	  lKey=ulComportInit;
      M_TestLinkTableValue(p_stMind,lKey,"Error in ComportInit In Perso (.CAR)");
	  ulComportInit=(unsigned long) M_GetComportLinkValueWithKey(lKey);
	  if (ulComportInit==0)
		  ulComportInit=M_GetScriptAINoComportInitDefault(p_stScriptAI);  
	}
	M_GetNoComportInit(p_stIntelligence)=ulComportInit;
	fn_vReinitComport(p_stIntelligence);
  }
}
#endif /* AI_USE_SCRIPT */
 
 
#ifndef _FIRE_DEADCODE_U64_ /* Added by RUC */
void fn_vSecondPassOfMindLoading(AI_tdxHandleToMind p_stMind,ACP_tdxBool _bPersoInFix, enum tdeObjectTreeInit_ _eObjectInit)
{
#if defined(AI_USE_SCRIPT)
   if (p_stMind!=NULL)
   {
	 tdstIntelligence *p_stReflexOrIntelligence;
 
#if defined(AI_LOGFILE) 
    fpAILogFile=NULL;
    fpAIUnusedComportLogFile=NULL;
    if (!AI_M_ucGetSecondPassDone(AI_M_p_stGetAIModel(p_stMind)) )
	{
	  fpAILogFile=fopen(AI_ANIM_LOGFILE,"a");
	  fpAIUnusedComportLogFile=fopen(AI_UNUSEDCOMPORT_LOGFILE,"a");
	}
#endif
 
 
#if defined(ACTIVE_AIDEBUG)   /*** DR ***/
	fn_v_SetCurrentMind( p_stMind );
	AI_M_SetDoingIntel(p_stMind, 1);
#endif /*ACTIVE_AIDEBUG*/
 
	/* Second pass for array of references */
	if((p_stMind->p_stAIModel->CFast_dst_RefTreeArray) && (!AI_M_ucGetSecondPassDone(AI_M_p_stGetAIModel(p_stMind))))
	{
		struct tdstTreeInterpret_	stTree;
	    M_GetNodeInterpret(&stTree)=p_stMind->p_stAIModel->CFast_dst_RefTreeArray;
		M_SetNbNodeInterpret(&stTree,p_stMind->p_stAIModel->uwNbNode);
		fn_vSecondPassOfTree(p_stMind, &stTree);
	}
 
	 if ((p_stReflexOrIntelligence=AI_M_p_stGetIntelligence(p_stMind)) != NULL)
	 {
	   /* for nodes*/
	   /* so that init Script is initialized only once in model */
	   if (!AI_M_ucGetSecondPassDone(AI_M_p_stGetAIModel(p_stMind)) )
	   {
	  	 #if defined(AI_LOGFILE) 
		 if (fpAILogFile)
		 {
			fprintf(fpAILogFile,"\n.RUL of %s :\n",AI_M_szGetPersoName(p_stMind));
		 }
		 #endif
	     fn_vSecondPassOfScriptAI(p_stMind,M_GetScriptAI(p_stReflexOrIntelligence));
	   }
	   /* for ComportInit*/
	   fn_vSecondPassOfComport(p_stMind,p_stReflexOrIntelligence);
 
	 }
	
#if defined(ACTIVE_AIDEBUG)   /*** DR ***/
	 AI_M_SetDoingIntel(p_stMind, 0);
#endif /*ACTIVE_AIDEBUG*/
	 if ((p_stReflexOrIntelligence=AI_M_p_stGetReflex(p_stMind)) != NULL)
	 {
	   /* for nodes*/
	   /* so that init Script is initialized only once in model */
	   if (!AI_M_ucGetSecondPassDone(AI_M_p_stGetAIModel(p_stMind)) )
	   {
	  	 #if defined(AI_LOGFILE) 
		 if (fpAILogFile)
		 {
			fprintf(fpAILogFile,"\n.RFX of %s :\n",AI_M_szGetPersoName(p_stMind));
		 }
		 #endif
	     fn_vSecondPassOfScriptAI(p_stMind,M_GetScriptAI(p_stReflexOrIntelligence));
	   }
 
		/* for ComportInit*/
	    fn_vSecondPassOfComport(p_stMind,p_stReflexOrIntelligence);
	 }
    
	/* so that init Script is initialized only once in model */
	if (!AI_M_ucGetSecondPassDone(AI_M_p_stGetAIModel(p_stMind)) )
	{
		/* for references in macros*/
		fn_vSecondPassOfListMacro(p_stMind);
	}

	 /* for DsgVar type perso*/
	 fn_vSecondPassOfDsgMem(p_stMind,_bPersoInFix, _eObjectInit);
 
	 /* SAI*/
/*     fn_vInsertDsgVarInSAI(p_stMind);*/
 
	 /* hyper important : must be the last line of this function*/
	 AI_M_SetSecondPassDone(AI_M_p_stGetAIModel(p_stMind),1);
	 
#if defined(AI_LOGFILE) 
	if (fpAILogFile)
	{
		fclose(fpAILogFile);
		fpAILogFile=NULL;
	}
#endif
   }
   
#endif /* AI_USE_SCRIPT */
}
#endif /* _FIRE_DEADCODE_U64_ */ /* Added by RUC */
 
 
 
void fn_vReinitAIComport(AI_tdxHandleToMind p_stMind)
{
#if defined(ACTIVE_AIDEBUG)
		fn_v_SetCurrentMind(p_stMind);
#endif
 
  /* BEWARE : THIS IS THE ULTRA OPERATOR */
  fn_vSetUltraOperatorPerso(NULL,NULL);
  
  if (p_stMind!=NULL)
  {
     tdstIntelligence *p_stReflexOrIntelligence;
 
	  /* reinit comport intelligence*/
#if defined(ACTIVE_AIDEBUG)   /*** DR ***/
	 AI_M_SetDoingIntel(p_stMind, 1);
#endif /*ACTIVE_AIDEBUG*/
	 if ((p_stReflexOrIntelligence=AI_M_p_stGetIntelligence(p_stMind))!=NULL)
	 {
       	fn_vReinitComport(p_stReflexOrIntelligence);
	 }
 
	 /* reinit comport reflex*/
#if defined(ACTIVE_AIDEBUG)   /*** DR ***/
	 AI_M_SetDoingIntel(p_stMind, 0);
#endif /*ACTIVE_AIDEBUG	 */
	 if ((p_stReflexOrIntelligence=AI_M_p_stGetReflex(p_stMind))!=NULL) 
	 {
	   fn_vReinitComport(p_stReflexOrIntelligence);
	 }
//XB 05/08/99
#ifndef D_THROW_CFAST_AI
//End XB
	 p_stMind->CFast_lCmpMetaAction = 0; 
	 p_stMind->CFast_lRfxMetaAction = 0; 
	 p_stMind->CFast_lCmpMetaActionForMacro = 0; 
	 p_stMind->CFast_lRfxMetaActionForMacro = 0; 
//XB 05/08/99
#endif /* D_THROW_CFAST_AI */
//End XB
  }
}
 
void fn_vReinitAI(AI_tdxHandleToMind p_stMind)
{
  if (p_stMind!=NULL)
  {
    /* reinit AI comport*/
    fn_vReinitAIComport(p_stMind);
 
    /* reinit AI variable designer*/
    ReinitDesignerVariables(p_stMind);
  }
}
 
/* POTICHE*/
void fn_vFirstInitAI(AI_tdxHandleToMind p_stMind)
{
  if (p_stMind!=NULL)
  {
    /* reinit AI comport*/
    fn_vReinitAIComport(p_stMind);
 
    /* reinit AI variable designer*/
    FirstInitDesignerVariables(p_stMind);
  }
}
void fn_vReinitAIComportWithFlags(AI_tdxHandleToMind p_stMind,tdeObjectTreeInit eObjIniType)
{
  eObjIniType=eObjIniType;
  fn_vReinitAIComport(p_stMind);
}
 
/* for the moment */
void fn_vReinitAIWithFlags(AI_tdxHandleToMind p_stMind,tdeObjectTreeInit eObjIniType)
{
  if (p_stMind!=NULL)
  {
	/* reinit AI comport*/
    fn_vReinitAIComportWithFlags(p_stMind,eObjIniType);
 
	/* reinit AI variable designer*/
	fn_vReinitDesignerVariablesWithFlags(p_stMind,eObjIniType);
  }
}
 
 
/****************************************************************************************/
/* for always                                                                           */
/****************************************************************************************/
#include "specif/ActTable.h"
char *fn_p_cSimulateAllocDsgMemBuffer(char **p_ptr,unsigned long ulSize)
{
  char *p_cDsgMemBuffer=NULL;
  p_cDsgMemBuffer=(char*) (*p_ptr);
  (*p_ptr)+=ulSize*sizeof(char);
 
  memset(p_cDsgMemBuffer,0,ulSize);
  return(p_cDsgMemBuffer);
}
 
tdstDsgMem *fn_p_stSimulateAllocDsgMem(char **p_ptr,tdstDsgVar **p_p_stDsgVar,unsigned long ulSize)
{
  tdstDsgMem *p_stDsgMem=NULL;
  p_stDsgMem=(tdstDsgMem*) (*p_ptr);
  memset(*p_ptr,0,sizeof(tdstDsgMem));
  (*p_ptr)+=sizeof(tdstDsgMem);
 
  /* link DsgMem to its model : dont forget it*/
  p_stDsgMem->p_p_stDsgVar=p_p_stDsgVar;
  
  /* no specific values by default */
  p_stDsgMem->p_cDsgMemBufferInit=NULL; 
  
  /* zone which stores current DsgVarValues : Set during 2nd pass*/
  p_stDsgMem->p_cDsgMemBuffer=fn_p_cSimulateAllocDsgMemBuffer(p_ptr,ulSize);
  return(p_stDsgMem);
}
 
 
/* XB 20/05/1999 */
#ifndef D_THROW_COMPLEX_ACTION_TABLE
tdstActionTableEntry *fn_p_stSimulateAllocActionTableEntry(char **p_ptr,unsigned char ucActionTableNbEntry)
{
  tdstActionTableEntry *p_stActionTableEntry=NULL;
  p_stActionTableEntry=(tdstActionTableEntry*) (*p_ptr);
  memset(*p_ptr,0,ucActionTableNbEntry*sizeof(tdstActionTableEntry));
  (*p_ptr)+=(ucActionTableNbEntry*sizeof(tdstActionTableEntry));
  return(p_stActionTableEntry);
}
#endif /* D_THROW_COMPLEX_ACTION_TABLE */
/* End XB 20/05/1999 */
 
tdstActionTable *fn_p_stSimulateAllocActionTable(char **p_ptr,unsigned char ucActionTableNbEntry)
{
/* ANNECY MT - 18/09/98 { now, this function also initializes the ActionTable*/
  tdstActionTable *p_stActionTable=NULL;
  tdstActionTableEntry *p_stEntry=NULL;
/* XB 20/05/1999 */
#ifndef D_THROW_COMPLEX_ACTION_TABLE
  unsigned char ucNEntry;
#endif /* D_THROW_COMPLEX_ACTION_TABLE */
/* End XB 20/05/1999 */
 
/* XB 21/05/1999 */
	if(ucActionTableNbEntry!=0)
	{
  p_stActionTable=(tdstActionTable*) (*p_ptr);
  memset(*p_ptr,0,sizeof(tdstActionTable));
  (*p_ptr)+=sizeof(tdstActionTable);
	}
	else
	{
		return NULL;
	}
/* End XB 21/05/1999 */
 
/* XB 20/05/1999 */
#ifndef D_THROW_COMPLEX_ACTION_TABLE
  M_TableNbEntries(p_stActionTable)=ucActionTableNbEntry;
  M_TableEntry(p_stActionTable)=fn_p_stSimulateAllocActionTableEntry(p_ptr,ucActionTableNbEntry);
 
  p_stActionTable->ucNbEntriesUsed=0;
  p_stActionTable->ucCurrentEntry=0;
  /**/
  for (ucNEntry=0,p_stEntry=M_TableEntry(p_stActionTable);ucNEntry<ucActionTableNbEntry;ucNEntry++,p_stEntry++)
  {
	p_stEntry -> bUseDefaultActionReturn	= g_ucUseDefaultActionReturn;
	p_stEntry -> ucNewActionReturn			= g_ucNewActionReturn;
  }
#else /* D_THROW_COMPLEX_ACTION_TABLE */
	p_stEntry = &(p_stActionTable->stEntry);

	p_stEntry->bUseDefaultActionReturn=g_ucUseDefaultActionReturn;
	p_stEntry->ucNewActionReturn=g_ucNewActionReturn;

	memset(&(p_stEntry->stActionParam),0,sizeof(p_stEntry->stActionParam));
#endif /* D_THROW_COMPLEX_ACTION_TABLE */
/* End XB 20/05/1999 */

  return(p_stActionTable);
/* END ANNECY MT }*/
}
 
tdstIntelligence *fn_p_stSimulateAllocIntelligence(char **p_ptr,tdstScriptAI **p_p_stScriptAI,unsigned char ucActionTableNbEntry)
{
   tdstIntelligence *p_stIntelligence=NULL;
 
   if (M_GetScriptAINbComport(*p_p_stScriptAI)!=0)
   {
     p_stIntelligence=(tdstIntelligence *) (*p_ptr);
	 memset(*p_ptr,0,sizeof(tdstIntelligence));
	 (*p_ptr)+=sizeof(tdstIntelligence);
   
     /* link intelligence to its model*/
     p_stIntelligence->p_p_stScriptAI=p_p_stScriptAI; /* faire macro*/
 
	 /* initialise with default comport*/
     M_GetNoComportInit(p_stIntelligence)=M_GetScriptAINoComportInitDefault(*p_p_stScriptAI);
 
     M_ActionTable(p_stIntelligence)=fn_p_stSimulateAllocActionTable(p_ptr,ucActionTableNbEntry);
/* ANNECY MT - 18/09/98 { fn_p_stSimulateAllocActionTable() also initializes the ActionTable*/
     /*fn_vInitActionTable(p_stIntelligence);*/
/* END ANNECY MT }*/
   }
 
   return(p_stIntelligence);
}
 
void fn_vSimulateMindAllocationFromAnotherMind(AI_tdxHandleToMind p_stMindSrc,AI_tdxHandleToMind p_stMindDst)
{
	if ( (p_stMindSrc!=NULL) && (p_stMindDst!=NULL) )
	{
		AI_tdstAIModel *p_stLoadedAIModel;
		AI_tdstMind *p_stLoadedMind=p_stMindDst;
		tdstScriptAI **p_p_stScriptAI=NULL;
		tdstIntelligence *p_stIntelligenceOrReflex=NULL;
		
		char *ptr=(char*) (p_stMindDst+1);
		
		/* AIModel*/
		p_stLoadedAIModel=AI_M_p_stGetAIModel(p_stMindSrc);
		AI_M_SetAIModel(p_stLoadedMind,p_stLoadedAIModel);
		
#if defined(ACTIVE_EDITOR)
		AI_M_ucErrorFlag(p_stLoadedMind)=0;           
#endif
		
#if defined(ACTIVE_AIDEBUG)
		AIDebug_M_InitTrace( p_stLoadedMind );
		AIDebug_M_InitBuffer( p_stLoadedMind );
#endif /*ACTIVE_AIDEBUG*/
		
		/*    fn_vSecondPassOfMindLoading(p_stMindSrc);*/
		
		/* simul alloc intelligence and link it with its script*/
		p_p_stScriptAI=&AI_M_p_stGetIntelligenceScriptAIModel(p_stLoadedAIModel);
		if (*p_p_stScriptAI!=NULL)
		{
			AI_M_SetIntelligence(p_stLoadedMind,
				fn_p_stSimulateAllocIntelligence(&ptr,
				p_p_stScriptAI,
				M_GetScriptAIActionTableNbEntry(*p_p_stScriptAI)
				)
				);
			p_stIntelligenceOrReflex=AI_M_p_stGetIntelligence(p_stMindSrc);
			if (p_stIntelligenceOrReflex!=NULL)
			{
				M_GetNoComportInit(AI_M_p_stGetIntelligence(p_stLoadedMind))=M_GetNoComportInit(p_stIntelligenceOrReflex);
			}
		}
		else
		{
			AI_M_SetIntelligence(p_stLoadedMind,NULL);
		}
		
		p_stIntelligenceOrReflex=AI_M_p_stGetIntelligence(p_stMindSrc);
		if (p_stIntelligenceOrReflex!=NULL)
		{
			M_GetNoComportInit(AI_M_p_stGetIntelligence(p_stLoadedMind))=M_GetNoComportInit(p_stIntelligenceOrReflex);
		}
		
		/* simul reflex (same structure as intelligence and link it with its script)*/
		p_p_stScriptAI=&AI_M_p_stGetReflexScriptAIModel(p_stLoadedAIModel);
		if (*p_p_stScriptAI!=NULL)
		{
			AI_M_SetReflex(p_stLoadedMind,
				fn_p_stSimulateAllocIntelligence(&ptr,
				p_p_stScriptAI,
				M_GetScriptAIActionTableNbEntry(*p_p_stScriptAI)
				)
				);
			
			p_stIntelligenceOrReflex=AI_M_p_stGetReflex(p_stMindSrc);
			if (p_stIntelligenceOrReflex!=NULL)
			{
				M_GetNoComportInit(AI_M_p_stGetReflex(p_stLoadedMind))=M_GetNoComportInit(p_stIntelligenceOrReflex);
			}
		}  
		else
		{
			AI_M_SetReflex(p_stLoadedMind,NULL);
		}
		
		
		/* simul alloc dsgvar*/
		M_GetDsgMem(p_stLoadedMind)=NULL;
		if ( AI_M_p_stGetDsgVar(p_stLoadedMind)!=NULL)
		{
			if (M_GetDsgVarSize(p_stLoadedMind)!=0)
			{
				AI_M_p_stGetDsgMem(p_stLoadedMind)=fn_p_stSimulateAllocDsgMem(&ptr,&AI_M_p_stGetDsgVar(p_stLoadedMind),M_GetDsgVarSize(p_stLoadedMind) );
				M_GetDsgVar(p_stLoadedMind)=M_GetDsgVar(p_stMindSrc);
				
				/* dsgvar init*/
				if (M_GetDsgMemBufferInit(p_stMindSrc)!=NULL)
				{
					M_GetDsgMemBufferInit(p_stLoadedMind)=fn_p_cSimulateAllocDsgMemBuffer(&ptr,M_GetDsgVarSize(p_stLoadedMind));
					
					/* copy it from the model */
					memcpy(M_GetDsgMemBufferInit(p_stLoadedMind),M_GetDsgMemBufferInit(p_stMindSrc),M_GetDsgVarSize(p_stLoadedMind));
				}
				
			}
		}  
		
		/* reinit comport and dsgvar*/
/* ANNECY MT - 18/09/98 {*/
		/*fn_vReinitAI(p_stLoadedMind);*/
		/**/
		p_stIntelligenceOrReflex=AI_M_p_stGetIntelligence(p_stLoadedMind);
		if(p_stIntelligenceOrReflex)
		{
			M_GetCurrentComport(p_stIntelligenceOrReflex) = (tdstComport *)M_GetNoComportInit(p_stIntelligenceOrReflex);
			M_GetPrevComport(p_stIntelligenceOrReflex) = M_GetCurrentComport(p_stIntelligenceOrReflex);
		}
		/**/
		p_stIntelligenceOrReflex=AI_M_p_stGetReflex(p_stLoadedMind);
		if(p_stIntelligenceOrReflex)
		{
			M_GetCurrentComport(p_stIntelligenceOrReflex) = (tdstComport *)M_GetNoComportInit(p_stIntelligenceOrReflex);
			M_GetPrevComport(p_stIntelligenceOrReflex) = M_GetCurrentComport(p_stIntelligenceOrReflex);
		}
		/**/
		if (M_GetDsgMem(p_stLoadedMind)!=NULL)
		{
			/* copy current values*/
			if (M_GetDsgMemBufferInit(p_stLoadedMind)==NULL)
			{
				/* from init values in model */
				memcpy(M_GetDsgMemBuffer(p_stLoadedMind),M_GetDsgMemDefaultInit(p_stLoadedMind),M_GetDsgVarSize(p_stLoadedMind));
			}
			else
			{
				/* from init values in perso*/
				memcpy(M_GetDsgMemBuffer(p_stLoadedMind),M_GetDsgMemBufferInit(p_stLoadedMind),M_GetDsgVarSize(p_stLoadedMind));
			}
		}
//XB 05/08/99
#ifndef D_THROW_CFAST_AI
//End XB
	  p_stLoadedMind->CFast_lCmpMetaAction = 0; 
	  p_stLoadedMind->CFast_lRfxMetaAction = 0; 
	  p_stLoadedMind->CFast_lCmpMetaActionForMacro = 0; 
	  p_stLoadedMind->CFast_lRfxMetaActionForMacro = 0; 
//XB 05/08/99
#endif /* D_THROW_CFAST_AI */
//End XB
/* END ANNECY MT }*/
  }
}
 
unsigned long fn_ulGetSizeOfMindWithoutAIModel(AI_tdxHandleToMind p_stMind)
{
  unsigned long ulSize=0;
  
  if (p_stMind!=NULL)
  {
	 tdstIntelligence *p_stIntelligenceOrReflex;
 
     /* Mind structure*/
	 ulSize+=sizeof(AI_tdstMind);
 
	 /* Intelligence structure*/
	 p_stIntelligenceOrReflex=AI_M_p_stGetIntelligence(p_stMind);
	 if (p_stIntelligenceOrReflex!=NULL)
	 {
	   ulSize+=sizeof(tdstIntelligence);
	   ulSize+=sizeof(tdstActionTable);
	   ulSize+=sizeof(tdstActionTableEntry)*M_ActionTableNbEntries(p_stIntelligenceOrReflex);
	 }
 
     /* Reflex structure*/
	 p_stIntelligenceOrReflex=AI_M_p_stGetReflex(p_stMind);
	 if (p_stIntelligenceOrReflex!=NULL)
	 {
	   ulSize+=sizeof(tdstIntelligence);
	   ulSize+=sizeof(tdstActionTable);
	   ulSize+=sizeof(tdstActionTableEntry)*M_ActionTableNbEntries(p_stIntelligenceOrReflex);
	 }
 
     /* DsgMem*/
	 if ( AI_M_p_stGetDsgVar(p_stMind)!=NULL)
	 {
		if (M_GetDsgVarSize(p_stMind)!=0)
		{
			ulSize+=sizeof(tdstDsgMem);
			ulSize+=M_GetDsgVarSize(p_stMind);
			if (M_GetDsgMemBufferInit(p_stMind)!=NULL)
			{
              ulSize+=M_GetDsgVarSize(p_stMind);
			}
		}
	 }
  }
  return(ulSize);
}
 
 
#ifndef _FIRE_DEADCODE_U64_ /* Added by RUC */
unsigned long fn_ulGetSizeOfMindWithAIModel(AI_tdxHandleToMind p_stMind)
{
    unsigned long ulSize=0;
	
	if (p_stMind!=NULL)
	{
		AI_tdstAIModel *p_stModel=AI_M_p_stGetAIModel(p_stMind);
		if (p_stModel!=NULL)
		{
			tdstScriptAI *p_stIntelligenceOrReflexScriptAI;
			long n=2;
			
			/* Model*/
			ulSize+=sizeof(AI_tdstAIModel);
			
			/* Intelligence and reflex*/
			while (n)
			{
				if (n==2)
				{
					p_stIntelligenceOrReflexScriptAI=AI_M_p_stGetIntelligenceScriptAIModel(p_stModel);
				}
				else if (n==1)
				{
					p_stIntelligenceOrReflexScriptAI=AI_M_p_stGetReflexScriptAIModel(p_stModel);
				}
				else
				{
					p_stIntelligenceOrReflexScriptAI=NULL;
				}
				
				if (p_stIntelligenceOrReflexScriptAI!=NULL)
				{
					unsigned long i,j,k;
					ulSize+=sizeof(tdstScriptAI);
					
					for (i=0;i<M_GetScriptAINbComport(p_stIntelligenceOrReflexScriptAI);i++)
					{
						tdstComport *p_stComport=M_GetScriptAIComportN(p_stIntelligenceOrReflexScriptAI,i);
						if (p_stComport!=NULL)
						{
							ulSize+=sizeof(tdstComport);
							
							for (j=0;j<M_GetComportNbRules(p_stComport);j++)
							{
								tdstTreeInterpret *p_stRule=M_GetComportRuleN(p_stComport,j);
								if (p_stRule!=NULL)
								{
									ulSize+=sizeof(tdstTreeInterpret);
									
									for(k=0;k<M_GetNbNodeInterpret(p_stRule);k++)
									{
										tdstNodeInterpret *p_stNode=M_GetNodeInterpretN(p_stRule,k);
										if (p_stNode!=NULL)
										{ 
											ulSize+=sizeof(tdstNodeInterpret);
											
											if (M_GetTypeInterpret(p_stNode) == E_ti_String)
											{
												if (M_szStringInterpret(p_stNode) != NULL)
												{
													ulSize+=strlen(M_szStringInterpret(p_stNode))+1;
												}
											}
											else if (M_GetTypeInterpret(p_stNode) == E_ti_ConstantVector)
											{
												if (M_p_stVectorInterpret(p_stNode) != NULL)
												{
													ulSize+=sizeof(MTH3D_tdstVector);
												}
											}
										}
									}
								}
							}
						}
					}
					n--;
				}
 
				/* Dsgvar*/
                /* To finish*/
			}
		}
	}
	return(fn_ulGetSizeOfMindWithoutAIModel(p_stMind)+ulSize);
}
#endif /* _FIRE_DEADCODE_U64_ */ /* Added by RUC */
 
 
 
#if defined(AI_USE_SCRIPT)
void fn_vInitAIDebugWindow(void)
{
	SMALL_RECT stDebugWindowSize;
	COORD stDebugWindowSize1;
	ACP_tdxBool bError;
	
	AllocConsole();
	
	stDebugWindowSize.Top=0;
	stDebugWindowSize.Bottom=50;
	stDebugWindowSize.Left=0;
	stDebugWindowSize.Right=20;
	
	stDebugWindowSize1.X=20;
	stDebugWindowSize1.Y=50;
	
	bError=SetConsoleScreenBufferSize(
		GetStdHandle(STD_OUTPUT_HANDLE),	/* handle of console screen buffer */
		stDebugWindowSize1 	/* new size in character rows and cols.  */
		);
	
	bError=SetConsoleWindowInfo(
		GetStdHandle(STD_OUTPUT_HANDLE),	/* handle of console screen buffer */
		TRUE,	/* coordinate type flag */
		&stDebugWindowSize 	/* address of new window rectangle */
		);
	
	SetConsoleTitle("Debug Window");
}
 
void fn_vPrintAIDebug(char *text)
{
	short i;
	
	WriteConsole(
		GetStdHandle(STD_OUTPUT_HANDLE),	/* handle to a console screen buffer */
		text,	/* pointer to buffer to write from */
		strlen(text),	/* number of characters to write */
		(LPDWORD)&i,	/* pointer to number of characters written */
		NULL 	/* reserved */
		);
}
#endif /* AI_USE_SCRIPT */


/* ANNECY MT - 30/03/99 { PC Protection Code */
#ifndef U64	/* { */

/************************************************/
/* Fonctions pour l'utilisation des protections */
/************************************************/


/* ANNECY OA - 04/08/99 { */
/* Lettre du CDROM */
#if defined(__cplusplus)
extern "C"
{
#endif
extern char g_cCDROM;
#if defined(__cplusplus)
}
#endif



/* Initialise le handler des fonctions */
void fn_vInitLoaderHandler(tdstLoaderHandler *stLoader)
{
#if !defined(PRESS_DEMO)
#ifdef PTC_SYSTEM_ACTIVED
	#define M_GET_FUNC_ADDR(num) ((PTC_ga_stImportedFunctions[(num)].dwAddress ^ *((DWORD*)(PTC_ga_stImportedFunctions[(num)].szName))))
#else
	#define M_GET_FUNC_ADDR(num) (NULL)
#endif
	*((long *)&stLoader->SetErrorMode) = M_GET_FUNC_ADDR(PTC_C_SetErrorModeIndex);
	*((long *)&stLoader->CreateFile) = M_GET_FUNC_ADDR(PTC_C_CreateFileIndex);
	*((long *)&stLoader->GetFileInformationByHandle) = M_GET_FUNC_ADDR(PTC_C_GetFileInformationByHandleIndex);
	*((long *)&stLoader->CloseHandle) = M_GET_FUNC_ADDR(PTC_C_CloseHandleIndex);
	*((long *)&stLoader->GetDriveType) = M_GET_FUNC_ADDR(PTC_C_GetDriveTypeIndex);
	*((long *)&stLoader->GetVolumeInformation) = M_GET_FUNC_ADDR(PTC_C_GetVolumeInformationIndex);
	*((long *)&stLoader->GetDiskFreeSpace) = M_GET_FUNC_ADDR(PTC_C_GetDiskFreeSpaceIndex);
	*((long *)&stLoader->SetFileAttributes) = M_GET_FUNC_ADDR(PTC_C_SetFileAttributsIndex);
	*((long *)&stLoader->GetFileAttributes) = M_GET_FUNC_ADDR(PTC_C_GetFileAttributsIndex);
	*((long *)&stLoader->SetFileTime) = M_GET_FUNC_ADDR(PTC_C_SetFileTimeIndex);
	*((long *)&stLoader->GetFileTime) = M_GET_FUNC_ADDR(PTC_C_GetFileTimeIndex);
	*((long *)&stLoader->GetFileSize) = M_GET_FUNC_ADDR(PTC_C_GetFileSizeIndex);
#ifdef PTC_SYSTEM_ACTIVED
	*((long *)&stLoader->SearchExportedFunctionInEveryDLL) = (long)PTC_fn_dwSearchExportedFunctionInEveryDLL;
	*((long *)&stLoader->SearchFunctionInImportedTableOfExe) = (long)PTC_fn_dwSearchFunctionInImportedTableOfExe;
#else
	*((long *)&stLoader->SearchExportedFunctionInEveryDLL) = NULL;
	*((long *)&stLoader->SearchFunctionInImportedTableOfExe) = NULL;
#endif
#endif /* PRESS_DEMO */
}

/* Pointeur de fonctions pour les fonctions dans les donnees */
typedef long (*ptrFunction)(char *_szFileName, tdstLoaderHandler *stHandler);
/* END ANNECY OA } */


unsigned char fn_ucSetDsgVarArray(void *pMyVarAddr,unsigned char ucIndex,tdstGetSetParam *p_stGetSetParam);
unsigned char fn_ucSetDsgVarInteger(void *pMyVarAddr,unsigned char ucIndex,tdstGetSetParam *p_stGetSetParam);
unsigned char fn_ucGetDsgVarInteger(void *pMyVarAddr,unsigned char ucIndex,tdstGetSetParam *p_stGetSetParam);

/* -----------------19/05/99 16:24-------------------
 * for every model
 * --------------------------------------------------*/
#define AI_C_DsgMemNumberForType            0


/* -----------------19/05/99 16:24-------------------
 * for Protect Key model
 * --------------------------------------------------*/
#define AI_C_DsgMemNumberForInitKey         1
#define AI_C_DsgMemNumberOfKey              2
#define AI_C_DsgMemNumberForProtectKey      3

/* 
 * Copy protect keys in Model after binary loading 
 */

#if !defined(PRESS_DEMO)
void fn_vInitDesignerVariablesWithProtectKeyInModel(AI_tdxHandleToMind p_stMind)
{
    char *ptrNumberForType = NULL;

	if (p_stMind)
	{
		unsigned char ucElement;
		tdstGetSetParam stGSParam;

#ifdef _DEBUG
        assert(M_GetNbDsgVar(p_stMind) > AI_C_DsgMemNumberForType);
        //assert(fn_GetDsgVarType(M_GetDsgVarType(p_stMind,AI_C_DsgMemNumberForInitKey))==E_vt_Integer);
#endif /* _DEBUG */

        ptrNumberForType = M_GetDsgVarAddrDefault(p_stMind,AI_C_DsgMemNumberForType);
        if (fn_ucGetDsgVarInteger(ptrNumberForType,0,&stGSParam)==C_VALID_GET)
        {
            long lType = M_GetSetParam_lValue(&stGSParam);
            if (lType==0)
            {
                /* -----------------19/05/99 16:32-------------------
                 * protect key model
                 * --------------------------------------------------*/
                char *ptrInitKeyArray = NULL;
                char *ptrProtectKeyArray = NULL;
                char *ptrNumberOfKey = NULL;

#ifdef _DEBUG
                assert(M_GetNbDsgVar(p_stMind) > AI_C_DsgMemNumberOfKey);
                assert(fn_GetDsgVarType(M_GetDsgVarType(p_stMind,AI_C_DsgMemNumberOfKey))==E_vt_Integer);

                assert(M_GetNbDsgVar(p_stMind) > AI_C_DsgMemNumberForInitKey);
                assert(fn_GetDsgVarType(M_GetDsgVarType(p_stMind,AI_C_DsgMemNumberForInitKey))==E_vt_Array);

                assert(M_GetNbDsgVar(p_stMind) > AI_C_DsgMemNumberForProtectKey);
                assert(fn_GetDsgVarType(M_GetDsgVarType(p_stMind,AI_C_DsgMemNumberForProtectKey))==E_vt_Array);
#endif

                ptrInitKeyArray    = M_GetDsgVarAddrDefault(p_stMind,AI_C_DsgMemNumberForInitKey);
                ptrProtectKeyArray = M_GetDsgVarAddrDefault(p_stMind,AI_C_DsgMemNumberForProtectKey);

                for (ucElement = 0 ; ucElement < SNA_g_dwNumberOfRelocationTableLoaded ; ucElement++ )
                {
                    M_Full_GetSetParam_Integer(&stGSParam,SNA_g_a_dwInitKeyRelocationTableLoaded[ucElement]);
                    fn_ucSetDsgVarArray (ptrInitKeyArray , ucElement ,&stGSParam);

                    M_Full_GetSetParam_Integer(&stGSParam,SNA_g_a_dwProtectKeyRelocationTableLoaded[ucElement]);
                    fn_ucSetDsgVarArray (ptrProtectKeyArray , ucElement ,&stGSParam);
                }

                ptrNumberOfKey = M_GetDsgVarAddrDefault(p_stMind,AI_C_DsgMemNumberOfKey);
                M_Full_GetSetParam_Integer(&stGSParam,SNA_g_dwNumberOfRelocationTableLoaded);
                fn_ucSetDsgVarInteger (ptrNumberOfKey , 0 , &stGSParam);
            }
        }
	}
}


/* ANNECY OA - 21/07/99 { */
/* -----------------19/05/99 16:24-------------------
 * for Computed Datas model
 * --------------------------------------------------*/
#define AI_C_DsgMemNumberForCode         1
#define AI_C_DsgMemNumberForConsigne     2
#define AI_C_DsgMemNumberForParameter    3
#define AI_C_DsgMemNumberForResult       4
#define AI_C_DsgMemNumberForCDROM		 5

/*
 * execute code in Designer variable after binary loading
 */
void fn_vInitDesignerVariablesWithComputedDatas(AI_tdxHandleToMind p_stMind)
{
	if (p_stMind)
	{
		tdstGetSetParam stGSParam;
		char *ptrNumberForType = M_GetDsgVarAddrInit(p_stMind, AI_C_DsgMemNumberForType);
        
        if (fn_ucGetDsgVarInteger(ptrNumberForType, 0, &stGSParam) == C_VALID_GET)
        {
            long lType = M_GetSetParam_lValue(&stGSParam);

			/* Modele a executer ? */
            if (lType==2)
            {
				tdstLoaderHandler stLoader;
				char *pcComputeDataCode = (char *)((tdstArray *)(M_GetDsgVarAddrInit(p_stMind, AI_C_DsgMemNumberForCode)))->d_ArrayElement;
				char *pcParameter = (char *)((tdstArray *)(M_GetDsgVarAddrInit(p_stMind, AI_C_DsgMemNumberForParameter)))->d_ArrayElement;
				char *pcConsigne = M_GetDsgVarAddrInit(p_stMind, AI_C_DsgMemNumberForConsigne);
				char *pcResult = M_GetDsgVarAddrInit(p_stMind, AI_C_DsgMemNumberForResult);
				char *pcCDROM  = M_GetDsgVarAddrInit(p_stMind, AI_C_DsgMemNumberForCDROM);
				long *plCryptage = (long *)pcComputeDataCode;
				long lResult;
				long lCryptKey;
				long lMask;
				
#ifdef _DEBUG
				assert(M_GetNbDsgVar(p_stMind) > AI_C_DsgMemNumberForResult);
				assert(fn_GetDsgVarType(M_GetDsgVarType(p_stMind,AI_C_DsgMemNumberForResult))==E_vt_Integer);
#endif /* _DEBUG */


#ifdef _DEBUG
				lMask = 0x81EC8B55;
#else
				lMask = 0x4401;
#endif


				/* Decryptage du code */
				plCryptage = (long *)pcComputeDataCode;
				lCryptKey = ~*plCryptage & lMask;
				/* Nouveau systeme de cryptage
				lCryptKey = *plCryptage;
				++plCryptage;
				*/
				while (plCryptage < (long *)pcConsigne)
				{
					long lNextCryptKey = *plCryptage;
					*plCryptage ^= lCryptKey;
					lCryptKey = lNextCryptKey;
					++plCryptage;
				}

				fn_vInitLoaderHandler(&stLoader);

				/* Decryptage du parametre */
				plCryptage = (long *)pcParameter;
				while (plCryptage < (long *)pcResult)
				{
					long lNextCryptKey = *plCryptage;
					*plCryptage ^= lCryptKey;
					lCryptKey = lNextCryptKey;
					++plCryptage;
				}

				/* lecteur du CDROM en parametre ? */
				fn_ucGetDsgVarInteger(pcCDROM,0,&stGSParam);
				if (M_GetSetParam_lValue(&stGSParam))
				{
					*pcParameter = g_cCDROM;
				}
				
				/* Execution de la fonction */
				lResult = ((ptrFunction)pcComputeDataCode)(pcParameter, &stLoader);				

				/* Cryptage du code */
				while (pcComputeDataCode < pcConsigne)
				{
					*pcComputeDataCode = PTC_fn_lGetRandom();;
					++pcComputeDataCode;
				}

				/* Preparation du resultat */
				M_Full_GetSetParam_Integer(&stGSParam, lResult);

				/* Cryptage du parametre */
				while (pcParameter < pcResult)
				{
					*pcParameter = PTC_fn_lGetRandom();
					++pcParameter;
				}

				/* Stockage du resultat */
				fn_ucSetDsgVarInteger (pcResult, 0, &stGSParam);
			}
		}
	}
}
#endif /* PRESS_DEMO */

/* END ANNECY OA } */

#ifndef RETAIL /* { */

#ifdef PTC_SYSTEM_ACTIVED	/* { */

/* ANNECY OA - 04/08/99 { */
/*************************************************************************/
/* Fonctions pour l'inclusion des protections pendant de la binarisation */
/*************************************************************************/
/* Ligne de commande pour passer par ici : -level:learn_30 -bin:2 -mem:2 -dsc:2  */


/* Taille max du code en long... */
#define M_MAX_CODE_SIZE	200

/* Taille max du parametre en long */
#define M_MAX_PARAMETER_SIZE	100

typedef struct tdstProtectionsInit_
{
	ptrFunction function;
	long		result;
	char		parameter[M_MAX_PARAMETER_SIZE];
	char		CDROM;
} tdstProtectionsInit;


#include "Protections.cxx"


long fn_lCodeSize(ptrFunction function)
{
	long lIndex = 0;

	while (lIndex < 50 && g_ListOfProtectionFunctions[lIndex] != function)		lIndex++;

	if (lIndex < 50)
	{
		return (long)g_ListOfProtectionFunctions[lIndex+1] - (long)g_ListOfProtectionFunctions[lIndex];
	}
	return -1;
}
/* END ANNECY OA } */


/* ANNECY OA - 23/07/99 { */
/*
 * Copy code in Designer variable during binarisation
 */
void fn_vInitDesignerVariablesWithCode(struct tdstEngineObject_ *p_stObject, AI_tdxHandleToMind p_stMind)
{
	MS_tdxHandleToStandardGame h_StdGame = p_stObject -> h_StandardGame;

	if (p_stMind)
	{
		tdstGetSetParam stGSParam;
	    char *pcNumberForType = M_GetDsgVarAddrInit(p_stMind, AI_C_DsgMemNumberForType);
        
        if (fn_ucGetDsgVarInteger(pcNumberForType, 0, &stGSParam) == C_VALID_GET)
        {
            long lType = M_GetSetParam_lValue(&stGSParam);

			if (lType >= 100)
            {
				/* Recherche des variables utiles */
				char *pcComputeDataCode = (char *)((tdstArray *)(M_GetDsgVarAddrInit(p_stMind, AI_C_DsgMemNumberForCode)))->d_ArrayElement;
				char *pcParameter = (char *)((tdstArray *)(M_GetDsgVarAddrInit(p_stMind, AI_C_DsgMemNumberForParameter)))->d_ArrayElement;
				char *pcResult = M_GetDsgVarAddrInit(p_stMind, AI_C_DsgMemNumberForResult);
				char *pcConsigne = M_GetDsgVarAddrInit(p_stMind, AI_C_DsgMemNumberForConsigne);
				long *plCryptage = (long *)pcComputeDataCode;
				//long lCodeSize = fn_lCodeSize(lType%100);
				long lCodeSize = fn_lCodeSize(g_ProtectionFunctions[lType%100].function);
				long lCryptKey;
				long lMask;


				/* Sous-couche du code :)) */
				plCryptage = (long *)pcComputeDataCode;
				while (plCryptage < (long *)pcConsigne)
				{
					*plCryptage = PTC_fn_lGetRandom();
					++plCryptage;
				}

				/* Sous-couche du parametre :)) */
				plCryptage = (long *)pcParameter;
				while (plCryptage < (long *)pcResult)
				{
					*plCryptage = PTC_fn_lGetRandom();
					++plCryptage;
				}


				/* Copie de code */
				assert((lCodeSize>>2) < M_MAX_CODE_SIZE);
				memcpy(pcComputeDataCode, g_ProtectionFunctions[lType%100].function, lCodeSize);

				/* Test le point communs entre tous les premmiers entier des fonctions, utile pour le cryptage
				{
					int cmp = *((int *)(g_ProtectionFunctions[0].function));
					int i;
					char buffer[200];
					for (i=1; i < 15; ++i)
					{
						cmp &= *((int *)(g_ProtectionFunctions[i].function));
					}
					sprintf(buffer, "cmp = %X", cmp);
					OutputDebugString(buffer);
					abort();
				}
				*/

				/* Copie du parametre */
				strcpy(pcParameter, g_ProtectionFunctions[lType%100].parameter);

				/* Test de la fonction de protection
				{
					tdstLoaderHandler stLoader;
					long lResult;
					*pcParameter = g_cCDROM;
					fn_vInitLoaderHandler(&stLoader);
					lResult = g_ProtectionFunctions[lType%100].function(pcParameter, &stLoader);
				}
				*/

				/* Copie de la consigne */
				M_Full_GetSetParam_Integer(&stGSParam, g_ProtectionFunctions[lType%100].result);
				fn_ucSetDsgVarInteger (pcConsigne, 0, &stGSParam);


				/* Nettoyage */
				if ((lType >= 100) && (lType <= 199))
				{
					/* Modele Actif, le type est mis a 2 */
					M_Full_GetSetParam_Integer(&stGSParam, 2);
					fn_ucSetDsgVarInteger (pcNumberForType, 0, &stGSParam);
				}
				else if ((lType >= 200) && (lType <= 299))
				{
					/* Modele Passif, le type est mis a 0 */
					M_Full_GetSetParam_Integer(&stGSParam, 0);
					fn_ucSetDsgVarInteger (pcNumberForType, 0, &stGSParam);

					/* et le bit de protection est desactive */
					h_StdGame->ulCustomBits &= ~GAM_C_CustBitProtection;
				}

#ifdef _DEBUG
				lMask = 0x81EC8B55;
#else
				lMask = 0x4401;
#endif


				/* Cryptage du code */
				plCryptage = (long *)pcComputeDataCode;
				lCryptKey = PTC_fn_lGetRandom() & lMask;
				/* Nouveau systeme de cryptage
				lCryptKey = *plCryptage;
				++plCryptage;
				*/
				while (plCryptage < (long *)pcConsigne)
				{
					*plCryptage ^= lCryptKey;
					lCryptKey = *plCryptage;
					++plCryptage;
				}

				/* Cryptage du parametre */
				plCryptage = (long *)pcParameter;
				while (plCryptage < (long *)pcResult)
				{
					*plCryptage ^= lCryptKey;
					lCryptKey = *plCryptage;
					++plCryptage;
				}
			}
		}
	}
}
/* END ANNECY OA } */


/* -----------------19/05/99 16:24-------------------
 * for CheckSum model
 * --------------------------------------------------*/
#define AI_C_DsgMemNumberForBeginAddress    2
#define AI_C_DsgMemNumberForSize            1
#define AI_C_DsgMemNumberForEndAddress      3
#define AI_C_DsgMemNumberForChecksum        4
void fn_vInitDesignerVariablesWithChecksumInModel(struct tdstEngineObject_ *p_stObject, AI_tdxHandleToMind p_stMind)
{
/* ANNECY OA - 04/08/99 { */
	MS_tdxHandleToStandardGame h_StdGame = p_stObject -> h_StandardGame;
/* END ANNECY OA } */
    char *ptrNumberForType = NULL;

	if (p_stMind)
	{
		unsigned char ucElement;
		tdstGetSetParam stGSParam;

#ifdef _DEBUG
        assert(M_GetNbDsgVar(p_stMind) > AI_C_DsgMemNumberForType);
        //assert(fn_GetDsgVarType(M_GetDsgVarType(p_stMind,AI_C_DsgMemNumberForInitKey))==E_vt_Integer);
#endif /* _DEBUG */

        ptrNumberForType = M_GetDsgVarAddrDefault(p_stMind,AI_C_DsgMemNumberForType);
        if (fn_ucGetDsgVarInteger(ptrNumberForType,0,&stGSParam)==C_VALID_GET)
        {
            long lType = M_GetSetParam_lValue(&stGSParam);
            if (lType==1)
            {
                /* -----------------19/05/99 16:32-------------------
                 * checksum model
                 * --------------------------------------------------*/
                char        *ptrBeginArray      = NULL;
                char        *ptrEndArray        = NULL;
                char        *ptrChecksum        = NULL;
                char        *ptrNumberForSize   = NULL;
                DWORD       *p_dwBeginAddress   = PTC_g_dwBeginLabelAddress;
                DWORD       *p_dwEndAddress     = PTC_g_dwEndLabelAddress;
                DWORD		*p_dwCheckSum		= PTC_g_dwChecksum;
				long		lChecksumBegin		= 0;
				long		lChecksumEnd		= 0;
				long		lChecksumChecksum	= 0;
#ifdef _DEBUG
                assert(M_GetNbDsgVar(p_stMind) > AI_C_DsgMemNumberForSize);
                assert(fn_GetDsgVarType(M_GetDsgVarType(p_stMind,AI_C_DsgMemNumberForSize))==E_vt_Integer);

                assert(M_GetNbDsgVar(p_stMind) > AI_C_DsgMemNumberForBeginAddress);
                assert(fn_GetDsgVarType(M_GetDsgVarType(p_stMind,AI_C_DsgMemNumberForBeginAddress))==E_vt_Array);

                assert(M_GetNbDsgVar(p_stMind) > AI_C_DsgMemNumberForEndAddress);
                assert(fn_GetDsgVarType(M_GetDsgVarType(p_stMind,AI_C_DsgMemNumberForEndAddress))==E_vt_Array);

                assert(M_GetNbDsgVar(p_stMind) > AI_C_DsgMemNumberForChecksum);
                assert(fn_GetDsgVarType(M_GetDsgVarType(p_stMind,AI_C_DsgMemNumberForChecksum))==E_vt_Array);
#endif /* _DEBUG */

                ptrBeginArray    = M_GetDsgVarAddrDefault(p_stMind,AI_C_DsgMemNumberForBeginAddress);
                ptrEndArray      = M_GetDsgVarAddrDefault(p_stMind,AI_C_DsgMemNumberForEndAddress);
                ptrChecksum      = M_GetDsgVarAddrDefault(p_stMind,AI_C_DsgMemNumberForChecksum);

                for (ucElement = 0 ; *p_dwBeginAddress && *p_dwEndAddress ; ucElement++,p_dwBeginAddress++,p_dwEndAddress++,p_dwCheckSum++)
                {
                    M_Full_GetSetParam_Integer(&stGSParam,*p_dwBeginAddress);
                    fn_ucSetDsgVarArray (ptrBeginArray , ucElement ,&stGSParam);

                    M_Full_GetSetParam_Integer(&stGSParam,*p_dwEndAddress);
                    fn_ucSetDsgVarArray (ptrEndArray , ucElement ,&stGSParam);

                    M_Full_GetSetParam_Integer(&stGSParam,*p_dwCheckSum);
                    fn_ucSetDsgVarArray (ptrChecksum , ucElement ,&stGSParam);

					lChecksumBegin		+= (*(long*)p_dwBeginAddress)	* (*(long*)p_dwBeginAddress);
					lChecksumEnd		+= (*(long*)p_dwEndAddress)		* (*(long*)p_dwEndAddress);
					lChecksumChecksum	+= (*(long*)p_dwCheckSum)		* (*(long*)p_dwCheckSum);
                }

				//
                M_Full_GetSetParam_Integer(&stGSParam,lChecksumBegin);
                fn_ucSetDsgVarArray (ptrBeginArray , ucElement ,&stGSParam);

                M_Full_GetSetParam_Integer(&stGSParam,lChecksumEnd);
                fn_ucSetDsgVarArray (ptrEndArray , ucElement ,&stGSParam);

                M_Full_GetSetParam_Integer(&stGSParam,lChecksumChecksum);
                fn_ucSetDsgVarArray (ptrChecksum , ucElement ,&stGSParam);
				//

				ucElement++;
                ptrNumberForSize = M_GetDsgVarAddrDefault(p_stMind,AI_C_DsgMemNumberForSize);
                M_Full_GetSetParam_Integer(&stGSParam,ucElement);
                fn_ucSetDsgVarInteger (ptrNumberForSize , 0 , &stGSParam);


/* ANNECY OA - 04/08/99 { */
				/* Nettoyage : le type est mis a 0 */
				M_Full_GetSetParam_Integer(&stGSParam, 0);
				fn_ucSetDsgVarInteger (ptrNumberForType, 0, &stGSParam);

				/* et le bit de protection est desactive */
				h_StdGame->ulCustomBits &= ~GAM_C_CustBitProtection;
/* END ANNECY OA } */
            }
        }
	}
}
#endif /* PTC_SYSTEM_ACTIVED } */

#endif /* RETAIL } */

#endif /* } U64 */
/* END ANNECY MT } */
