#include "BuildSettings.h" // scheffnow - This is the renamed NK.c file
#include "InternalSettings.h" // where the more esoteric/programmerly things from BS.h got moved. NK 05-07-17

#include "events.h"
#include "globals.c"
#include "animals.c"
#include "sea_ai\sea.c"
#include "ships\ships.c"
#include "Encounters\Encounters.c"
#include "worldmap\worldmap.c"
#include "locations\locations.c"
#include "Loc_ai\LAi_init.c"
#include "store\goods.h"
#include "cannons\cannons.c"
#include "nations\nations.c"
#include "particles.c"
#include "initinterface.c"
#include "characters\characters.c"
#include "interface\interface.h"
#include "store\storeutilite.c"
#include "dialog.c"
#include "quests\quests.c"
#include "islands\islands.c"
#include "reload.c"
#include "situations.c"
#include "battle_interface\loginterface.c"
#include "calendar.c"
#include "teleport.c"
#include "utils.c"
#include "ITEMS\items.h"
#include "ITEMS\itemLogic.c"
#include "ITEMS\items_utilite.c"
#include "sound\alias.c" // KK
#include "weather\WhrWeather.c"
#include "controls\controls.c"
#include "landencounters\landencounters.c"
#include "NK.c" // 05-07-03 NK for misc functions
#include "Reinit.c" // NK
#include "models\models.c" // scheffnow
// NK do this with loadsegment - #include "models\initModels.c" //scheffnow
#include "Characters\init\monks.c" // scheffnow
#include "kam_generalfunctions.c"	// added after build 11 by KAM
#include "kam_shipberthing_ship.c"	// added after build 11 by KAM
#include "CCCFunctions.c" // ccc
#include "CCCdirectsail.c" // ccc Jan07, directsail code
#include "elrapido.c" // El Rapido
#include "MAXIMUS_Functions.c" // MAXIMUS
#include "KB_routines.c"  // KBlack - to accomodate functions from other mods - initially for tuning ships mod
#include "Periods.c" // KK

#include "BuildSettings.c" // Inez/NK BS frontend


extern void wdmInitWorldMap();
extern void InitGoods();
extern void InitStores();
// OK, I'm putting the function in store.h rather than using loadsegment. 05-07-12 - extern void StoreInit();
extern void InitItems();
extern void InitCharactersTables();
extern void InitCharactersNames();
extern void InitCharactersNamesRu(); // added by MAXIMUS
extern void CreateCharacters();
extern void ExecuteConsole(); // NK

extern void BothQuestComplete(string sQuestName); // KK
extern void QuestComplete(string sQuestName); // KK
extern void StartStoryLine(); // KK

// NK  so you see the defs that are in Utils.c -->
native float Bring2RangeNoCheck(float fMin1, float fMax1, float fMin2, float fMax2, float fValue);
native float Bring2Range(float fMin1, float fMax1, float fMin2, float fMax2, float fValue);
/*float Bring2Range(float fMin1, float fMax1, float fMin2, float fMax2, float fValue)
{
	if(fValue < fMin2) { fValue = fMin2; }
	if(fValue > fMax2) { fValue = fMax2; }
	float fDelta = (fValue - fMin2) / (fMax2 - fMin2);
	return fMin1 + fDelta * (fMax1 - fMin1);
}*/
native float Degree2Radian(float fDegree);
native float Clampf(float fValue);
/*float Clampf(float fClamp)
{
	if(fClamp > 1.0) return 1.0;
	if(fClamp < 0.0) return 0.0;
	return fClamp;
}*/
// NK <--
native int RDTSC_B();
native int RDTSC_E(int iRDTSC);
//int onesec; // NK for speedtests.

#libriary "script_libriary_test"


#event_handler(NEW_GAME_EVENT,"NewGame");
#event_handler(GAME_OVER_EVENT,"GameOverE");
#event_handler("Control Activation","ProcessControls");
#event_handler("MainMenuKey","ProcessMainMenuKey");
#event_handler("InterfaceKey","ProcessInterfaceKey");
#event_handler("CameraPosAng","ProcessCameraPosAng");
// NK 05-07-10 for now do with normal controls. - #event_handler("Cheat","ProcessCheat");
#event_handler("Control Activation","ProcessCheat");
#event_handler("SeaDogs_ClearSaveData", "ClearLocationsSaveData");

// KK -->
bool bboth_reaction_loaded = false;
bool bquests_reaction_loaded = false;
bool bsl_utils_loaded = false;
ref ResurrectingOfficiant;
bool bSuppressResurrection = false;
// <-- KK

// PB: Tortuga Ladies -->
ref TortugaDame1;
ref TortugaDame2;
ref TortugaDame3;
// PB: Tortuga Ladies <--

void ProcessCheat()
{
	//int tmpLangFileID = LanguageOpenFile("interface_strings.txt");
	string sCheatName;
	ref mc;
	int rcPassengerID;
	ref rcPassenger;
	sCheatName = GetEventData();
	mc = GetMainCharacter();
	// NK 05-07-10 switch to using normal control activation -->
	if(ENABLE_CHEATMODE && HasSubStr(sCheatName, "Cheat"))
	{
		sCheatName = strcut(sCheatName, 5, strlen(sCheatName)-1);
		// NK <--
		switch(sCheatName)
		{
			case "God":
				if(LAi_IsImmortal(GetMainCharacter()))
				{
					LAi_SetImmortal(GetMainCharacter(), false);
					Log_SetStringToLog(TranslateString("","God mode") + " " + XI_ConvertString("OFF"));
				}else{

					LAi_SetImmortal(GetMainCharacter(), true);
					Log_SetStringToLog(TranslateString("","God mode") + " " + XI_ConvertString("ON"));
				}
			break;
			case "ShotGun":
				if(globalSGMode != false)
				{
					globalSGMode = false;
					Log_SetStringToLog(TranslateString("","Shotgun mode") + " " + XI_ConvertString("OFF"));
				}else{
					globalSGMode = true;
					Log_SetStringToLog(TranslateString("","Shotgun mode") + " " + XI_ConvertString("ON"));
				}
			break;

			case "Gold":
				mc.money = sti(mc.money) + 100000;
				mc.wealth = sti(mc.wealth) + 10000;
				Log_SetStringToLog("+ 100000 " + XI_ConvertString("Gold"));
				Log_SetStringToLog("+ 10000 " + XI_ConvertString("Wealth"));
			break;
			case "Skill":
				mc.skill.freeskill = sti(mc.skill.freeskill) + 50;
				Log_SetStringToLog("+ 50" + XI_ConvertString("SP"));
			break;
			/*case "Reputation":
				mc.reputation = REPUTATION_NEUTRAL;
				Log_SetStringToLog("Reputation Set to NEUTRAL");
			break;*/
			case "Morale":

			break;
			case "Encounters":
				if(CheckAttribute(mc,"worldmapencountersoff") == 0)
				{
					mc.worldmapencountersoff = "1";
					Log_SetStringToLog(TranslateString("","Worldmap encounters") + " " + XI_ConvertString("OFF"));
				}
				else
				{
					if(mc.worldmapencountersoff == "1")
					{
						mc.worldmapencountersoff = "0";
						Log_SetStringToLog(TranslateString("","Worldmap encounters") + " " + XI_ConvertString("ON"));
					}
					else
					{
						mc.worldmapencountersoff = "1";
						Log_SetStringToLog(TranslateString("","Worldmap encounters") + " " + XI_ConvertString("OFF"));
					}
				}
			break;
			case "MainCharacter":
				mc.model	= "Danielle";
				mc.sex = "woman";
				mc.FaceId = 30;
				mc.model.animation = "woman";
				mc.model.height = WOMAN_HEIGHT; // KK
			break;
			case "soundoff":
				SendMessage(&Sound,"ll",MSG_SOUND_SET_ENABLED,0);
				Log_SetStringToLog(XI_ConvertString("Sound") + " " + XI_ConvertString("OFF"));
			break;

	/* ==========     Additional cheat handlers added for cheats by RC, 04.nov.2003     ========== */
			case "LevelUp":
				/*mc.skill.freeskill = sti(mc.skill.freeskill) + 2;
				mc.rank = sti(mc.rank) + 1;*/
				mc.experience = CalculateExperienceFromRank(sti(mc.rank)+1);
				/*mc.perks.FreePoints = sti(mc.perks.FreePoints) + 1;
				LAi_SetHP(mc,LAi_GetCharacterMaxHP(mc) + 5.0,LAi_GetCharacterMaxHP(mc) + 5.0);
				Log_SetStringToLog("Level Up!");*/
				AddCharacterExpNS(&mc, 1); // NK do it via actual call 05-07-10
			break;

			case "FakeLevelUp":
				mc.skill.freeskill = sti(mc.skill.freeskill) + ADD_SKILLPOINTS_PERLEVEL; // TIH changed to user configurable setting Nov14'06
				mc.perks.FreePoints = sti(mc.perks.FreePoints) + 1;
				ChangeHPBonus(&mc, 5);
				ResetHP(&mc); // NK 05-07-10
				//LAi_SetHP(mc,LAi_GetCharacterMaxHP(mc) + 5.0,LAi_GetCharacterMaxHP(mc) + 5.0);
				Log_SetStringToLog(TranslateString("","Fake Level Up") + "!");
			break;

			case "Reputation":
				if (sti(mc.reputation) >= 0 && sti(mc.reputation) <= 10)
				{
					mc.reputation = 15;
					Log_SetStringToLog(XI_ConvertString("Reputation") + " " + XI_ConvertString("set to") + " " + GetTranslatedReputationForSex(mc, "Bloody Terror")); // PB: Display fix
					break;
				}
				if (sti(mc.reputation) >= 11 && sti(mc.reputation) <= 20) {
					mc.reputation = 25;
					Log_SetStringToLog(XI_ConvertString("Reputation") + " " + XI_ConvertString("set to") + " " + GetTranslatedReputationForSex(mc, "Swindler")); // PB: Display fix
					break;
				}
				if (sti(mc.reputation) >= 21 && sti(mc.reputation) <= 30) {
					mc.reputation = 35;
					Log_SetStringToLog(XI_ConvertString("Reputation") + " " + XI_ConvertString("set to") + " " + GetTranslatedReputationForSex(mc, "Rascal")); // PB: Display fix
					break;
				}
				if (sti(mc.reputation) >= 31 && sti(mc.reputation) <= 40) {
					mc.reputation = 45;
					Log_SetStringToLog(XI_ConvertString("Reputation") + " " + XI_ConvertString("set to") + " " + GetTranslatedReputationForSex(mc, "Neutral")); // PB: Display fix
					break;
				}
				if (sti(mc.reputation) >= 41 && sti(mc.reputation) <= 50) {
					mc.reputation = 55;
					Log_SetStringToLog(XI_ConvertString("Reputation") + " " + XI_ConvertString("set to") + " " + GetTranslatedReputationForSex(mc, "Bloke")); // PB: Display fix
					break;
				}
				if (sti(mc.reputation) >= 51 && sti(mc.reputation) <= 60) {
					mc.reputation = 65;
					Log_SetStringToLog(XI_ConvertString("Reputation") + " " + XI_ConvertString("set to") + " " + GetTranslatedReputationForSex(mc, "Matey")); // PB: Display fix
					break;
				}
				if (sti(mc.reputation) >= 61 && sti(mc.reputation) <= 70) {
					mc.reputation = 75;
					Log_SetStringToLog(XI_ConvertString("Reputation") + " " + XI_ConvertString("set to") + " " + GetTranslatedReputationForSex(mc, "Dashing")); // PB: Display fix
					break;
				}
				if (sti(mc.reputation) >= 71 && sti(mc.reputation) <= 80) {
					mc.reputation = 85;
					Log_SetStringToLog(XI_ConvertString("Reputation") + " " + XI_ConvertString("set to") + " " + GetTranslatedReputationForSex(mc, "Hero")); // PB: Display fix
					break;
				}
				if (sti(mc.reputation) >= 81 && sti(mc.reputation) <= 90) {
					mc.reputation = 5;
					Log_SetStringToLog(XI_ConvertString("Reputation") + " " + XI_ConvertString("set to") + " " + GetTranslatedReputationForSex(mc, "Horror of the High Seas")); // PB: Display fix
					break;
				}
			break;

			case "Officer1FakeLevelUp":
				rcPassengerID = GetOfficersIndex(mc, sti(1));
				if (sti(rcPassengerID) > -1)
				{
					rcPassenger = GetCharacter(sti(rcPassengerID));

					rcPassenger.skill.freeskill = sti(rcPassenger.skill.freeskill) + ADD_SKILLPOINTS_PERLEVEL; // TIH changed to user configurable setting Nov14'06
					rcPassenger.perks.FreePoints = sti(rcPassenger.perks.FreePoints) + 1;
					LAi_SetHP(rcPassenger,LAi_GetCharacterMaxHP(rcPassenger) + 5.0,LAi_GetCharacterMaxHP(rcPassenger) + 5.0);
					Log_SetStringToLog(TranslateString("","Fake Level Up") + " " + XI_ConvertString("for") + " " + rcPassenger.name + " " + rcPassenger.lastname + "!");
				}
				else
				{
					Log_SetStringToLog(TranslateString("","Error updating passenger, is passenger") + " 1 " + XI_ConvertString("missing?"));
				}
			break;

			case "Officer2FakeLevelUp":
				rcPassengerID = GetOfficersIndex(mc, sti(2));
				if (sti(rcPassengerID) > -1)
				{
					rcPassenger = GetCharacter(sti(rcPassengerID));

					rcPassenger.skill.freeskill = sti(rcPassenger.skill.freeskill) + ADD_SKILLPOINTS_PERLEVEL; // TIH changed to user configurable setting Nov14'06
					rcPassenger.perks.FreePoints = sti(rcPassenger.perks.FreePoints) + 1;
					LAi_SetHP(rcPassenger,LAi_GetCharacterMaxHP(rcPassenger) + 5.0,LAi_GetCharacterMaxHP(rcPassenger) + 5.0);
					Log_SetStringToLog(TranslateString("","Fake Level Up") + " " + XI_ConvertString("for") + " " + rcPassenger.name + " " + rcPassenger.lastname + "!");
				}
				else
				{
					Log_SetStringToLog(TranslateString("","Error updating passenger, is passenger") + " 2 " + XI_ConvertString("missing?"));
				}
			break;

			case "Officer3FakeLevelUp":
				rcPassengerID = GetOfficersIndex(mc, sti(3));
				if (sti(rcPassengerID) > -1)
				{
					rcPassenger = GetCharacter(sti(rcPassengerID));

					rcPassenger.skill.freeskill = sti(rcPassenger.skill.freeskill) + ADD_SKILLPOINTS_PERLEVEL; // TIH changed to user configurable setting Nov14'06
					rcPassenger.perks.FreePoints = sti(rcPassenger.perks.FreePoints) + 1;
					LAi_SetHP(rcPassenger,LAi_GetCharacterMaxHP(rcPassenger) + 5.0,LAi_GetCharacterMaxHP(rcPassenger) + 5.0);
					Log_SetStringToLog(TranslateString("","Fake Level Up") + " " + XI_ConvertString("for") + " " + rcPassenger.name + " " + rcPassenger.lastname + "!");
				}
				else
				{
					Log_SetStringToLog(TranslateString("","Error updating passenger, is passenger") + " 3 " + XI_ConvertString("missing?"));
				}
			break;
	/* ==========     End of editing by RC, 04.nov.2003     ========== */
		}
	}
	//LanguageCloseFile(tmpLangFileID);
}

object Camera;

void ProcessCameraPosAng()
{
	Camera.Pos.x = GetEventData();
	Camera.Pos.y = GetEventData();
	Camera.Pos.z = GetEventData();

	Camera.Ang.x = GetEventData();
	Camera.Ang.y = GetEventData();
	Camera.Ang.z = GetEventData();
}

void proc_break_video()
{
	trace("proc_break_video()");
	InterfaceStates.videoIdx = -1;
	Event("ievntEndVideo");
}

void Main()
{
//	LocationTestProcess();
//	return;
	Trace("Gauging: StartGauging");
	// NK speedtest calculate number of ticks in one second: 05-05-02
	/*int iRDTSC_main = RDTSC_B();
	SystemDelay(1000);
	onesec = RDTSC_E(iRDTSC_main);*/
	// NK <--

	if (SKIP_LOGOVIDEO == 1) Event("DoInfoShower", "sl", "game prepare", true); // KK

	LayerCreate("realize", 1);
	LayerCreate("sea_realize", 1);
	LayerCreate("iRealize", 1);
	LayerCreate("fader_realize", 1);
	LayerCreate("inf_realize", 1);

	ReloadProgressStart();
	ControlsInit(GetTargetPlatform(),true);
	nTeleportLocation = 1;
	sTeleportLocName = "Falaise_de_fleur_port_01";
	sTeleportLocName = "Oxbay_port";

	BS_Reinit();//MAXIMUS & KK

// KK -->
	if (SKIP_LOGOVIDEO == 0) {
		SetEventHandler("Control Activation","proc_break_video",0);
		InterfaceStates.Launched = false;
		SetEventHandler(EVENT_END_VIDEO,"Main_LogoVideo",0);
		InterfaceStates.videoIdx = 0;
		Event(EVENT_END_VIDEO);
		ReloadProgressEnd();
	} else {
		SetEventHandler("frame","Main_Start",1);
	}
// <-- KK
}

void Main_LogoVideo()
{

	int i = sti(InterfaceStates.videoIdx);
	trace("Main_LogoVideo() " + i);
	switch(i)
	{

	case 0:
		{
			InterfaceStates.videoIdx = 1;
			StartPostVideo("WaltDisneyLogo",1);
			return;
		}
	break;

	case 1:
		{
			InterfaceStates.videoIdx = 2;
			StartPostVideo("BethesdaLogo",1);
			return;
		}
	break;

	case 2:
		{
			InterfaceStates.videoIdx = 3;
			StartPostVideo("AkellaLogo",1);
			return;
		}
	break;


	/*case 3:
		{
			InterfaceStates.videoIdx = 4;
			StartPostVideo("intro",1);
			return;
		}
	break;*/

	}

	DelEventHandler(EVENT_END_VIDEO,"Main_LogoVideo");
	DeleteClass(&aviVideoObj);
	Event("DoInfoShower","sl","game prepare",true);
	SetEventHandler("frame","Main_Start",1);
}
//*/

void Main_Start()
//void Main()
{
	ReloadProgressStart();


	if (SKIP_LOGOVIDEO == 0) DelEventHandler("Control Activation","proc_break_video"); // KK
	DelEventHandler("frame","Main_Start");

	if( GetTargetPlatform()=="pc" )	ControlsInit(GetTargetPlatform(),false);
/*
	ControlsInit(GetTargetPlatform(),false);

	nTeleportLocation = 1;
	sTeleportLocName = "Falaise_de_fleur_port_01";
	sTeleportLocName = "Oxbay_port";

	NationsInit();
	EncountersInit();
	CannonsInit();
	ShipsInit();
	IslandsInit();
	WeatherInit();
	InitPerks();

	if(LoadSegment("store\initGoods.c"))
	{
		InitGoods();
		UnloadSegment("store\initGoods.c");
	}

	if(LoadSegment("Interface\BaseInterface.c"))
	{
		InitBaseInterfaces_main();
		InitBaseInterfaces();
		UnloadSegment("Interface\BaseInterface.c");
	}

	if(LoadSegment("Characters\Characters_names.c"))
	{
		InitCharactersNames();
		UnloadSegment("Characters\Characters_names.c");
	}

*/

	ReloadProgressUpdate();

	InitStoryLines(); // KK

	aref ardate = GetStorylineStartParams(FindCurrentStoryline());
	Environment.date.hour = ardate.date.hour;
	Environment.date.min = ardate.date.min;
	Environment.date.sec = ardate.date.sec;
	Environment.time = stf(ardate.date.hour) + stf(ardate.date.min)/60.0 + stf(ardate.date.sec)/3600.0;
	Environment.date.year = ardate.date.year;
	Environment.date.month = ardate.date.month;
	Environment.date.day = ardate.date.day;

	Trace("Gauging: initgame start");
	InitGame();
	Trace("Gauging: initgame done");
	ReloadProgressUpdate();

// KK -->
	CheckStorylines();

	/*Environment.date.hour = worldMap.date.hour;
	Environment.date.min = worldMap.date.min;
	Environment.date.sec = worldMap.date.sec;
	Environment.time = stf(worldMap.date.hour) + stf(worldMap.date.min)/60.0 + stf(worldMap.date.sec)/3600.0;
	Environment.date.year = worldMap.date.year;
	Environment.date.month = worldMap.date.month;	//Was "w rldMap."  Typo? Garbled? ccc mar20
	Environment.date.day = worldMap.date.day;*/
// <-- KK


	InterfaceStates.Buttons.Load.enable = true;

	Event("DoInfoShower","sl","game prepare",false);

	GetInterfaceParameters(); // added by MAXIMUS
	GetLanguageParameters(); // added by MAXIMUS
	LaunchMainMenu();
	//LaunchLoadGame();

	//SetMainCharacterIndex(1);
	//LoadMainCharacterInFirstLocation("Oxbay_town", "", "");

	ReloadProgressEnd();
}

void SaveGame()
{
	DelEventHandler("evntSave","SaveGame");
	string saveName = GetEventData();//MAXIMUS: looks like these changes are resolving troubles with save -[partially stolen from AOP]->
	string saveData = GetEventData();

	aref arTmp;
	if(!FindClass(&arTmp,"fader"))
	{
		SaveEngineState(saveName);
		ISetSaveData(saveName,saveData);
	}

	PostEvent("DoInfoShower",1,"sl","save game",false);
	ClearScreenShoter();//MAXIMUS: looks like these changes are resolving troubles with save <-[partially stolen from AOP]-
	if(HasSubStr(saveName,"-="+PlayerProfile.name+" QuickSave=-"))
	{
		if(FindFile(DEFAULT_PATH, "*", "-="+PlayerProfile.name+" QuickSave=-")=="") { Log_SetStringToLog(TranslateString("","...error quicksaving!")); }
		else { Log_SetStringToLog(TranslateString("","...done!")); }
	}
}

void LoadGame()
{
	string saveName = GetEventData();

	DeleteEntities();
	ClearEvents();
	ClearPostEvents();

	CreateEntity(&LanguageObject,"obj_strservice");
	CreateEntity(&reload_fader, "fader");
	SendMessage(&reload_fader, "ls", FADER_PICTURE, FindReloadPicture("loading_game.tga")); // KK
	SendMessage(&reload_fader, "lfl", FADER_IN, RELOAD_TIME_FADE_IN, true);
	ReloadProgressStart();
	Characters[0].savegamename = saveName;
	SetEventHandler("frame","LoadGame_continue",1);
}

void LoadGame_continue()
{
	DelEventHandler("frame","LoadGame_continue");
	LoadEngineState(Characters[0].savegamename);
	traceandlog("Done loading");
	// NK experimental check KNB cannons state
	/*ref pchar = GetMainCharacter();
	if(!CheckAttribute(pchar, "knbcannons") || sti(pchar.knbcannons) != USE_REAL_CANNONS)
	{
		Reinit(false, true);
	}*/
	// NK <--
//	ClearScreenShoter();//MAXIMUS: used for QuickSave
}

void InterfaceDoExit()
{
	DelEventHandler("frame","InterfaceDoExit");
	InterfaceStates.Launched=false;
	if(sti(InterfaceStates.doUnFreeze)==true)
	{
		SendMessage(&GameInterface,"l",MSG_INTERFACE_RELEASE);
		if(!IsEntity(&aviVideoObj))
		{
			if( bSeaActive && !bAbordageStarted )
			{
				LayerFreeze("sea_realize",false);
				LayerFreeze("sea_execute",false);
			}
			else
			{
				LayerFreeze("realize",false);
				LayerFreeze("execute",false);
			}
		}
		DeleteAttribute(&GameInterface,"");
	}
	switch(interfaceResultCommand)
	{
		case RC_INTERFACE_FORTCAPTURE_EXIT:
			ReloadAfterFortCapture();
			break;

		case RC_INTERFACE_DO_NOTHING:
			break;
		case RC_INTERFACE_MAIN_MENU_EXIT:
			break;
		/* dead Aug27'06
		case RC_INTERFACE_DO_NEW_GAME:
			InterfaceStates.doUnFreeze = false;
			DeleteEntities();
			//DeleteSeaEnvironment();
			musicName = "";
			oldMusicName = "";
			ResetSoundScheme();
			StopSound(0,0);
			ReleaseSound(0);
			ClearEvents();
			ClearPostEvents();

			if(LoadSegment("Interface\BaseInterface.c"))
			{
				InitBaseInterfaces_main();
				InitBaseInterfaces();
				UnloadSegment("Interface\BaseInterface.c");
			}


			LaunchSelectCharacter();

			//SetEventHandler("frame","NewGame",1);
			break;
		*/
		case RC_INTERFACE_DO_LOAD_GAME:
			//LoadGame();
// KK -->
			if (bboth_reaction_loaded) {
				UnloadSegment(GetStorylineDir(FindCurrentStoryline()) + "quests\both_reaction.c");
				bboth_reaction_loaded = false;
			}
			if (bquests_reaction_loaded) {
				UnloadSegment(GetStorylineDir(FindCurrentStoryline()) + "quests\quests_reaction.c");
				bquests_reaction_loaded = false;
			}
			if (bsl_utils_loaded) {
				UnloadSegment(GetStorylineDir(FindCurrentStoryline()) + "SL_utils.c");
				bsl_utils_loaded = false;
			}
// <-- KK
			LaunchLoadGame();
			break;
		case RC_INTERFACE_DO_SAVE_GAME:
			LaunchSaveGame();
			break;

		case RC_INTERFACE_DO_OPTIONS:
			LaunchOptionScreen();
			break;
		case RC_INTERFACE_DO_CONTROLS:
			LaunchControlsScreen();
			break;
// added by MAXIMUS -->
		case RC_INTERFACE_DO_ABOUT_BUILD:
			LaunchAboutBuildScreen();
			break;
// added by MAXIMUS <--
		case RC_INTERFACE_DO_CREDITS:
			break;
		case RC_INTERFACE_DO_RESUME_GAME:
			break;
		case RC_INTERFACE_RANSACK_MAIN_EXIT:
			Return2SeaAfterAbordage();
			//wdmCreateMap(0.0,0.0,0.0);
			break;
		// boal Cabin 09.09.03 -->
		case RC_INTERFACE_CABIN_MAIN_EXIT:
			Return2SeaAfterDeck(); // KK
			break;
		// boal Cabin 09.09.03 <--

		// MAXIMUS deck -->
		case RC_INTERFACE_DECK_MAIN_EXIT:
			Return2SeaAfterDeck();
			break;
		case RC_INTERFACE_CREW_MAIN_EXIT:
			Return2SeaAfterDeck(); // KK
			break;
		// MAXIMUS deck <--

		case RC_INTERFACE_CHARACTER_SELECT_EXIT:
			DeleteEntities();
			ClearEvents();
			SetEventHandler("frame","NewGame",1);
			InterfaceStates.doUnFreeze = false;
			break;
// KK -->
		case RC_INTERFACE_DO_START:
			if (bboth_reaction_loaded) {
				UnloadSegment(GetStorylineDir(FindCurrentStoryline()) + "quests\both_reaction.c");
				bboth_reaction_loaded = false;
			}
			if (bquests_reaction_loaded) {
				UnloadSegment(GetStorylineDir(FindCurrentStoryline()) + "quests\quests_reaction.c");
				bquests_reaction_loaded = false;
			}
			if (bsl_utils_loaded) {
				UnloadSegment(GetStorylineDir(FindCurrentStoryline()) + "SL_utils.c");
				bsl_utils_loaded = false;
			}
			RefreshStorylines();
			LaunchSelectStoryline();
			break;

		case RC_INTERFACE_DO_CUSTOMIZATION:
			LaunchCustomization();
			break;
// <-- KK
	}
}

void EngineLayersOffOn(bool on)
{
	//LayerSetRealize("realize",on);
	//LayerSetExecute("execute",on);
	on = !on;
	LayerFreeze("realize",on);
	LayerFreeze("execute",on);
	if(!bSeaActive && !bAbordageStarted) { // KK
		LayerFreeze("sea_realize",on);
		LayerFreeze("sea_execute",on);
	}
	//LayerFreeze("sun_trace",on);
	//LayerFreeze("sea_reflection",on);
	//LayerFreeze("shadow",on);
	//LayerFreeze("ship_cannon_trace",on);
	//LayerFreeze("hull_trace",on);
	//LayerFreeze("mast_ship_trace",on);
	//LayerFreeze("sails_trace",on);
}

string seadogs_saveFrom = "";

void OnSave()
{
	Set_inDialog_Attributes();//MAXIMUS: VERY strange, but it's needed
	seadogs_saveFrom = "";
	if(IsEntity(&worldMap) != 0)
	{
		seadogs_saveFrom = "world map";		//Was "seadogs_sav From"  ccc mar20
	}
	else
	{
		int ldLoc = FindLoadedLocation();
//		if (ldloc >= MAX_LOCATIONS) { ldloc = MAX_LOCATIONS; }
		if(ldLoc>=0 && ldLoc<nLocationsNum)// changed by MAXIMUS: was - if(ldLoc >= 0)
		{
			seadogs_saveFrom = "location";
			SendMessage(&Locations[ldLoc], "l", MSG_LOCATION_SETCHRPOSITIONS);
			LAi_SaveInfo();
			PostEvent("SeaDogs_ClearSaveData", 200, "a", &Locations[ldLoc]);
		}
		else { Trace("OnSave() -> unknow character location"); }
	}
}

void ClearLocationsSaveData()
{
	aref loc = GetEventData();
	SendMessage(loc, "l", MSG_LOCATION_CLRCHRPOSITIONS);
}

int actLoadFlag = 0;
void OnLoad()
{
	actLoadFlag = 1;


	//NationsInit();
	ResetSound();

	//CreateClass("dummy");

	if(LoadSegment("Interface\BaseInterface.c"))
	{
		//InitBaseInterfaces_main();
		InitBaseInterfaces();
		UnloadSegment("Interface\BaseInterface.c");
	}

	ReloadProgressUpdate();

// KK -->
	if (FindFile("PROGRAM\" + GetStorylineDir(FindCurrentStoryline()), "*.c", "SL_utils.c") != "") {
		bsl_utils_loaded = LoadSegment(GetStorylineDir(FindCurrentStoryline()) + "SL_utils.c");
	}

	bboth_reaction_loaded = LoadSegment(GetStorylineDir(FindCurrentStoryline()) + "quests\both_reaction.c");
	bquests_reaction_loaded = LoadSegment(GetStorylineDir(FindCurrentStoryline()) + "quests\quests_reaction.c");
	if (!bboth_reaction_loaded) {
		trace("ERROR: both_reaction.c not loaded!!!");
		return;
	}
	if (!bquests_reaction_loaded) {
		trace("ERROR: quests_reaction.c not loaded!!!");
		return;
	}

	ReloadProgressUpdate();
// <-- KK

	DialogsInit();
	//IslandsInit();
	//LocationInit();

	ReloadProgressUpdate();

	InitCharacterEvents();
	ReloadProgressUpdate();
	QuestsInit();
	ReloadProgressUpdate();
	InitTeleport();
	ReloadProgressUpdate();
	InitParticles();
	ReloadProgressUpdate();
	//ImportFuncTest();


	InterfaceStates.Buttons.Resume.enable = true;
	InterfaceStates.Buttons.Save.enable = true;
	InterfaceStates.Buttons.Load.enable = true;

	if(seadogs_saveFrom == "location")
	{
		ref mainchar;
		mainchar = GetMainCharacter();
		LoadMainCharacterInFirstLocation(mainchar.location, "reload", "", mainchar.location.from_sea); // KK
		int ldLoc = FindLoadedLocation();
		if(ldLoc >= 0)
		{
			SendMessage(&Locations[ldLoc], "l", MSG_LOCATION_TLPCHRPOSITIONS);
		}
	}else{
		if(seadogs_saveFrom == "world map")
		{
			wdmLoadSavedMap();
		}else{
			Trace("Unknow seadogs_saveFrom == " + seadogs_saveFrom);
		}
	}

	//ReloadEndFade();
	EngineLayersOffOn(true);
	//NewGame();
	DialogRun = false;
	InterfaceStates.Launched = false;

	ReloadProgressUpdate();

	PerkLoad();

	ReloadProgressUpdate();
	LoadGameOptions();

	ReloadProgressEnd();

	actLoadFlag = 0;
}

void NewGame()
{
	GetLanguageParameters();
	Trace("Gauging: start new game");
	DeleteEntities();
	DelEventHandler("frame","NewGame");

	CreateEntity(&LanguageObject,"obj_strservice");
	CreateEntity(&reload_fader, "fader");
	SendMessage(&reload_fader, "ls", FADER_PICTURE, FindReloadPicture("new_game.tga")); // KK
	SendMessage(&reload_fader, "lfl", FADER_IN, RELOAD_TIME_FADE_IN, true);

	SetEventHandler("frame","NewGame_continue",1);
}

void NewGame_continue()
{
	ReloadProgressStart();
	// NK only fully create characters _here_  05-04-07 to speed game start
	/*bool tmpbool = LogsToggle;
	LogsToggle = true;*/
	// PB CharactersInit();
	/*LogsToggle = tmpbool*/
	/*if(LoadSegment("characters\characters_init.c"))
	{
		bool tmpbool = LogsToggle;
		LogsToggle = true;
		CreateCharacters(); // NK add bool 05-04-07 to speed game start
		LogsToggle = tmpbool
		UnloadSegment("characters\characters_init.c");
	}*/
	// NK <--

	DelEventHandler("frame","NewGame_continue");

	if(LoadSegment("Interface\BaseInterface.c"))
	{
		InitBaseInterfaces();
		Trace("Gauging: ng iface");
		UnloadSegment("Interface\BaseInterface.c");
	}

// KK -->
	aref ardate = GetStorylineStartParams(FindCurrentStoryline());
	Environment.date.hour = ardate.date.hour;
	Environment.date.min = ardate.date.min;
	Environment.date.sec = ardate.date.sec;
	Environment.time = stf(ardate.date.hour) + stf(ardate.date.min)/60.0 + stf(ardate.date.sec)/3600.0;
	Environment.date.year = ardate.date.year;
	Environment.date.month = ardate.date.month;
	Environment.date.day = ardate.date.day;

	InitPeriods();
	SetCurrentPeriod(GetPeriodFromYear(sti(ardate.date.year)));
	trace("Gauging: periods");
// <-- KK

// PB -->
	NationsInit();
	trace("Gauging: nations");
	CharactersInit();
// <-- PB

	Trace("Gauging: ng initgame start");
	InitGame();
	Trace("Gauging: ng initgame stop");

	InterfaceStates.Buttons.Resume.enable = true;
	InterfaceStates.Buttons.Save.enable = true;
	InterfaceStates.Buttons.Load.enable = true;
	//PlayMusic("MW battle2.mp3");

// KK -->
	ref PChar = GetMainCharacter();

	if (FindFile("PROGRAM\" + GetStorylineDir(FindCurrentStoryline()), "*.c", "SL_utils.c") != "") {
		bsl_utils_loaded = LoadSegment(GetStorylineDir(FindCurrentStoryline()) + "SL_utils.c");
	}

	bboth_reaction_loaded = LoadSegment(GetStorylineDir(FindCurrentStoryline()) + "quests\both_reaction.c");
	bquests_reaction_loaded = LoadSegment(GetStorylineDir(FindCurrentStoryline()) + "quests\quests_reaction.c");
	if (!bboth_reaction_loaded) {
		trace("ERROR: both_reaction.c not loaded!!!");
		return;
	}
	if (!bquests_reaction_loaded) {
		trace("ERROR: quests_reaction.c not loaded!!!");
		return;
	}

	// do reinit up here 05-04-24
	Trace("Gauging: start reinit");
	Reinit(true, false); // 05-04-06 now do while still loading so we get nice reloadprogress update stuff...
	Trace("Gauging: reinit stop");

	ReloadProgressUpdate();

	InitRelations();
	trace("Gauging: initial relations");
	InitGroups();
	trace("Gauging: characters groups");

	ReloadProgressUpdate();
	Trace("Gauging: load mch in first");

	if (LoadSegment(GetStorylineDir(FindCurrentStoryline()) + "StartStoryline.c")) {
		StartStoryLine();
		UnloadSegment(GetStorylineDir(FindCurrentStoryline()) + "StartStoryline.c");
	}
// <-- KK

	Trace("Gauging: done load mch in first");
	ReloadProgressUpdate(); // NK

	CleanStorylineObject(); // KK

	ReloadProgressEnd();
}

/*
void NewGame()
{
	DeleteEntities();
	Environment.date.hour = 14.0;
	Environment.date.min = 0.0;
	Environment.date.sec = 0.0;
	Environment.time = 14.0;
	Environment.date.year = 1690;			//changed by KAM
	Environment.date.month = 8;
	Environment.date.day = 15;

	DelEventHandler("frame","NewGame");
	if(LoadSegment("Interface\BaseInterface.c"))
	{
		InitBaseInterfaces();
		UnloadSegment("Interface\BaseInterface.c");
	}
	InitGame();

	InterfaceStates.Buttons.Resume.enable = true;
	InterfaceStates.Buttons.Save.enable = true;
	InterfaceStates.Buttons.Load.enable = true;
	//PlayMusic("MW battle2.mp3");
	sTeleportLocName = "Oxbay_port";
	LoadMainCharacterInFirstLocation(sTeleportLocName, "reload2", sTeleportLocName);

}
*/
void InitGame()
{
	LayerCreate("realize", 1);
	LayerCreate("sea_realize", 1);
	LayerCreate("iRealize", 1);
	LayerCreate("fader_realize", 1);
	LayerCreate("inf_realize", 1);
	Trace("Gauging: createlayers");
	if(LoadSegment("store\initStore.c"))
	{
		InitStores();
		Trace("Gauging: stores");
		UnloadSegment("store\initStore.c");
	}
	InitSound();
	Trace("Gauging: sound");

	ReloadProgressUpdate();

	DeleteSeaEnvironment();
	Trace("Gauging: delete sea env");
	//CharactersInit();
	if(LoadSegment("worldmap\worldmap_init.c"))
	{
		wdmInitWorldMap();
		Trace("Gauging: wdmap");
		UnloadSegment("worldmap\worldmap_init.c");
	}
	IslandsInit();
	Trace("Gauging: islands");
	ReloadProgressUpdate();
	//return;
	LocationInit();
	Trace("Gauging: locations");
	ReloadProgressUpdate();
	DialogsInit();
	Trace("Gauging: dialogs");
	ReloadProgressUpdate();
	InitTeleport();
	Trace("Gauging: teleport");
	ReloadProgressUpdate();
	InitParticles();
	Trace("Gauging: particles");
	ReloadProgressUpdate();

	if(LoadSegment("items\initItems.c"))
	{
		InitItems();
		Trace("Gauging: items");
		UnloadSegment("items\initItems.c");
	}

	ReloadProgressUpdate();
	/*bool tmp = LogsToggle;
	LogsToggle = false;
	CharactersInit(false);
	LogsToggle = tmp;*/
	Trace("Gauging: char");
	ReloadProgressUpdate();
	QuestsInit();
	Trace("Gauging: quests");
	ReloadProgressUpdate();
	SeaAIGroupsInit();
	Trace("Gauging: sea ai groups");
	ReloadProgressUpdate();
	InitQuestMapEncounters();
	Trace("Gauging: questmapenc");
	ReloadProgressUpdate();
	InitLandRandomEncounters();
	Trace("Gauging: landenc");
	ReloadProgressUpdate();
// KK -->
	InitTownTable(true);
	trace("Gauging: towns");
	ReloadProgressUpdate();

	SetInitialWeather();
// <-- KK

	// KK SetNextWeather("Blue Sky");
	//SetNextWeather("Violet Sky");


	ResetQuestMovie();

	ReloadProgressUpdate();

	LoadGameOptions();
	Trace("Gauging: load options");

	Alias_Init(); // KK

	ReloadProgressUpdate();
	InfoShowSetting();
	Trace("Gauging: infoshow");
}

// NK make ranged sidestep 05-07-21 -->
#event_handler("sidestep_event", "SideStep_Proc");
void SideStepControl(float mag, bool onoff)
{
	//trace("Sidestep control, mag " + mag + ", onoff is " + onoff);
	ref pchar = GetMainCharacter();
	if(onoff)
	{
		if(!CheckAttribute(pchar, "sidestep"))
		{
			//trace("no sidestep yet");
			pchar.sidestep = mag;
			event("sidestep_event", "l", GetMainCharacterIndex());
		}
	}
	else
	{
		//trace("deleting sidestep");
		DeleteAttribute(&pchar, "sidestep");
	}
}

void SideStep_Proc()
{
	int idx = GetEventData();
	ref chr = GetCharacter(idx);
	if(sti(InterfaceStates.Launched) || dialogRun)
	{
		DeleteAttribute(&chr, "sidestep")
	}
	else
	{
		if(CheckAttribute(chr, "sidestep"))
		{
			Sidestep(&chr, stf(chr.sidestep), SIDESTEP_CHECK);
			postevent("sidestep_event", SIDESTEP_DELAY, "l", idx);
		}
	}
}
// NK <--

bool ShowScreen = true;
int counter = 0;
string key_cpcode = ""; // KK
void ProcessControls()
{
	string ControlName;
	ControlName = GetEventData();
	//trace("ProcessControls() : " + ControlName);
	//if(ControlName == "WhrPrevWeather")	{ Whr_LoadNextWeather(-1); }
	//if(ControlName == "WhrNextWeather")	{ Whr_LoadNextWeather(1); }
	//if(ControlName == "WhrUpdateWeather")	{ Whr_UpdateWeather(true); } // NK 04-09-21 add bool to Whr_UpdateWeather

	if (ControlName == "NK_Key_") return; // KK
	if (bDisableAllCommands) return; // KK

	//int tmpLangFileID = LanguageOpenFile("interface_strings.txt");

	if(ControlName == "Help") RunHelpChooser();

	ref PChar = GetMainCharacter(); // NK moved here
	if(bKeyboardEnabled) // NK keyboard 05-07-21
	{
		//trace("KB enabled, control is " + ControlName);
		bool keydone = false;
		bool update = true;
		string key = getsymbol(ControlName, strlen(ControlName)-1);
		if(hassubstr(ControlName, "NK_Key_")) 
		{
			KB_AddCharacter(key);
			keydone = true;
		}
// KK -->
		if (HasSubStr(ControlName, "NK_NP_")) {
			if (bKeyboardAlt == false) {
				KB_AddCharacter(key);
			} else {
				key_cpcode = key_cpcode + key;
			}
			keydone = true;
		}
// <-- KK
		if(!keydone)
		{
			switch(ControlName)
			{
// KK -->
				case "NK_KB_Shift_on": bKeyboardShift = !bKeyboardShift; keydone = true; break;
				case "NK_KB_Shift_off": bKeyboardShift = !bKeyboardShift; keydone = true; break;
				case "NK_KB_caps": bKeyboardShift = !bKeyboardShift; keydone = true; break;
				case "NK_KB_Control_on": bKeyboardControl = true; keydone = true; break;// MAXIMUS
				case "NK_KB_Control_off": bKeyboardControl = false; keydone = true; break;// MAXIMUS
				case "NK_KB_Alt_on":
					bKeyboardAlt = true;
					keydone = true;
				break;
				case "NK_KB_Alt_off":
					bKeyboardAlt = false;
					if (key_cpcode != "") {
					  if (strlen(key_cpcode) > 3) key_cpcode = strcut(key_cpcode, strlen(key_cpcode) - 4, strlen(key_cpcode) - 1);
					  int cpcode = sti(key_cpcode);
					  Event("Control Activation", "s", "NK_Key_" + ChrFromCode(cpcode));
						key_cpcode = "";
					}
					keydone = true;
				break;
// <-- KK
				case "NK_KB_back": KB_RemoveCharacter(); keydone = true; break;
				case "NK_KB_esc": KeyboardString = ""; event("KB_End"); update = false; break;
				case "NK_KB_enter": event("KB_End"); update = false; break;
			}
		}
		if(update) event("KB_update");
		//LanguageCloseFile(tmpLangFileID); // KK
		return;
	}

// TIH --> moved chunk out of switch case limbo to here 7-7-06
	string leftAnimation, rightAnimation;
	if(StraifCharacter(PChar))
	{
		if(LAi_IsFightMode(PChar))
		{
			leftAnimation = "straif_weapon_left";
			rightAnimation = "straif_weapon_right";
		}
		else
		{
			leftAnimation = "straif_left";
			rightAnimation = "straif_right";
		}
	}
// TIH <-- moved chunk

	switch(ControlName)
	{
		// Scheffnow -->
		case "SCHEFFNOW_RUSH":
			if(dialogRun || dialogSelf || CheckAttribute(PChar,"paused")) break;//MAXIMUS
			if(ENABLE_RUSHMOD == 1) 
			{
				if(CheckCharacterPerk(GetMainCharacter(),"Rush"))
				{
					ActivateCharacterPerk(GetMainCharacter(),"Rush");
				}
			}
		break;
		// scheffnow <--

		// NK -->
		// 05-07-13 Pause
		case "NK_Pause":
			if(!CheckAttribute(PChar, "paused")) { LaunchAdvancedMenu(); }//MAXIMUS: unused now, so will be used for PAUSE ;)
			else { PostEvent("exitCancel", 0); }
		break;

		// 05-07-13 separate dialog key
		case "NK_DialogStart":
			if(CORPSEMODE!=2) break;//MAXIMUS: only CORPSEMODE = 2 makes a lootable corpses
			if(dialogRun || dialogSelf || CheckAttribute(PChar,"paused")) break;//MAXIMUS
			//int tmpNameFileID = LanguageOpenFile("characters_names.txt");

			// if(bSeaActive && !bAbordageStarted) use that?
			if(FindLoadedLocation() != -1 && !sti(Interfacestates.Launched))
			{
				int tmpi = SendMessage(GetMainCharacter(),"ls",MSG_CHARACTER_EX_MSG,"FindDialogCharacter");
// changed by MAXIMUS [now we are looting corpses without dialog file] -->
				ref chCorpse, lcn;
				//aref chCorpse;
// added by MAXIMUS 21.07.2006 [corpses without any items and money will not be looted] -->
				aref testItems;
				string itmName = "";
				int it;
// added by MAXIMUS 21.07.2006 [corpses without any items and money will not be looted] <--
				// TIH: Do once, not copy/pasted many times Sep3'06
				if(tmpi<0) { tmpi = LAi_FindNearestVisCharacter(PChar, 20); }
				if(tmpi>=0)
				{					
					chCorpse = GetCharacter(tmpi);
					if(CheckAttribute(chCorpse,"corpse")==true)
					{
						if(chCorpse.dialog.filename == "corpse_dialog.c")
						// PB: To enable talking to corpses that don't have corpse_dialog.c set
						{
							// changed by MAXIMUS 21.07.2006 [corpses without any items and money will not be looted] -->
							if(!CheckAttribute(chCorpse,"Money")) chCorpse.Money = 0;
							DeleteAttribute(chCorpse,"Items.bladeX4");
							makearef(testItems,chCorpse.items);
							for(it=0; it<GetAttributesNum(testItems); it++)
							{
								itmName = GetAttributeName(GetAttributeN(testItems,it));
								if(GetCharacterItem(chCorpse,itmName)==0) DeleteAttribute(chCorpse,"Items."+itmName);
							}
							if(GetAttributesNum(testItems)==0 && sti(chCorpse.Money)==0) Log_SetStringToLog(TranslateString("","NoItems"));
							else
							{
								PlaySound("OBJECTS\shipcharge\sail_damage1.wav");
								bDeadExchange = true;
								LaunchCharacterItemChange(chCorpse);
							}
							// changed by MAXIMUS 21.07.2006 [corpses without any items will not be looted] <--
							lcn = &Locations[FindLocation(chCorpse.location)];
						//	if(CheckAttribute(lcn,"building") || CORPSEMODE < 2)
							if(CheckAttribute(lcn,"building") || CORPSEMODE < 3) // TIH lootable corpses adjustment Sep2'06
							{
								LAi_SetImmortal(chCorpse, false);
								ChangeCharacterAddressGroup(chCorpse, "None", "", "");
								PostEvent("RemoveCorpse", 100, "i", chCorpse);
							}
						}
						else
						{
							PChar.forcedlg = true;
							Event("dlgReady","l",tmpi);
						}
					}
				}
				// TIH <--
// changed by MAXIMUS [now we are looting corpses without dialog file] <--
			}

			//LanguageCloseFile(tmpNameFileID);

		break;

		case "ScreenCleaning":
			if(dialogRun || dialogSelf || CheckAttribute(PChar,"paused")) break;//MAXIMUS
			if(ShowScreen)
			{
				Log_SetActiveAction("Nothing");
				BLI_RefreshCommandMenu();
				BLI_DisableShow();
				SendMessage(&ILogAndActions,"ll",LI_SET_VISIBLE,false);
				ShowScreen = false;
			}
			else
			{
				BLI_RefreshCommandMenu();
				BLI_EnableShow();
				SendMessage(&ILogAndActions,"ll",LI_SET_VISIBLE,true);
				ShowScreen = true;
			}
		break;

		case "NK_Re-init": Reinit(false, true); break;

		case "NK_AlwaysRunToggle":
			AlwaysRunToggle = !AlwaysRunToggle;
			BeginChangeCharacterActions(GetMainCharacter()); // NK 04-09-17 have it change now.
			SetDefaultNormWalk(GetMainCharacter());
			SetDefaultFight(GetMainCharacter());
			EndChangeCharacterActions(GetMainCharacter()); // NK ditto
			if(AlwaysRunToggle) Log_SetStringToLog(TranslateString("","Always run is now on"));
			else Log_SetStringToLog(TranslateString("","Always run is now off"));
		break;

		case "NK_LogsToggle":
			LogsToggle = !LogsToggle;
			if(LogsToggle) Log_SetStringToLog(TranslateString("","Various logs are now on")); //bugfix 04-08-28
			else Log_SetStringToLog(TranslateString("","Various logs are now off"));
		break;

		case "executeconsole":
			if(LoadSegment("console.c"))
			{
				ExecuteConsole();
				UnloadSegment("console.c");
			}
		break;
// added by MAXIMUS [for new C-III models, which have an animated sidestep] -->
		case "Sidestep_left_on":
			if(StraifCharacter(PChar) && CheckAttribute(PChar,"location") && FindLocation(PChar.location)!=-1) 
			{
				CharacterPlayAction(PChar, leftAnimation); 
				SideStepControl(-STRAIF_DIST, true);
				PostEvent("Lai_EndAction", 250, "i", PChar);
			}
			else 
			{ 
				if(FindLoadedLocation()!=-1) SideStepControl(-SIDESTEP_DIST, true);
			}
		break;
		case "Sidestep_right_on":
			if(StraifCharacter(PChar) && CheckAttribute(PChar,"location") && FindLocation(PChar.location)!=-1) 
			{
				CharacterPlayAction(PChar, rightAnimation); 
				SideStepControl(STRAIF_DIST, true);
				PostEvent("Lai_EndAction", 250, "i", PChar);
			}
			else 
			{ 
				if(FindLoadedLocation() != -1) SideStepControl(SIDESTEP_DIST, true);
			}
		break;
		case "Sidestep_left_off": 
			if(!StraifCharacter(PChar)) SideStepControl(SIDESTEP_DIST, false);
		break;
		case "Sidestep_right_off": 
			if(!StraifCharacter(PChar)) SideStepControl(SIDESTEP_DIST, false);
		break;
// added by MAXIMUS [for new C-III models, which have an animated sidestep] -->

		// PB: Equip button -->
		case "Equip":
			if(dialogRun || dialogSelf || CheckAttribute(PChar,"paused")) break;//MAXIMUS
			// NK last edit 28-05-06; PB last edit 05-10-06
			// set up strings
			string logstr = "";
			string errstr = "";

			// blade
			string olditm = GetCharacterEquipByGroup(&PChar, BLADE_ITEM_TYPE);
			string newitm = FindCharacterItemByGroup(&PChar, BLADE_ITEM_TYPE);

			// TIH --> fixed equipping of swords for NON blade damage mod toggle Aug29'06
			// using quality is not needed, and gets in the way if you had a higher quality low sword equipped
			// even though you had a low quality higher sword in your inventory
			// if BLADEDAMAGE_ENABLED is ON, then it uses quality checks
			
			//int olditmqual = GetItemQualityByID(olditm); // TIH quality now checked when finding a valid new item
			//int newitmqual = GetItemQualityByID(newitm);
			if(newitm != olditm && newitm != "")
			{
				switch(GetItemQualityByID(newitm))
				{
					case 0: logstr += TranslateString("","a badly worn") + " "; break;
					case 1: logstr += TranslateString("","a worn") + " "; break;
					case 2: logstr += TranslateString("","an average") + " "; break;
					case 3: logstr += TranslateString("","a good") + " "; break;
					case 4: logstr += TranslateString("","a fine") + " "; break;
					case 5: logstr += TranslateString("","an excellent") + " "; break;
					// default:
					logstr += TranslateString("","a") + " ";
				}
				logstr += GetItemNameByID(newitm);
				EquipCharacterByItem(&PChar, newitm);
			}
			if(newitm == "" || newitm == "bladeX4")
			{
				errstr = XI_ConvertString("a sword");
			}

			/* older method
			int olditmqual = GetItemQualityByID(olditm);
			int newitmqual = GetItemQualityByID(newitm);
			bool shownoqual = false;
			if(newitmqual == -1)
			{
				newitmqual = 5;
				shownoqual = true;
			}
			if(newitm != olditm && newitmqual >= olditmqual && newitmqual != 0) // PB: Don't ever auto-equip broken blades
			{
				if(shownoqual)
				{
					if(newitm != "bladeX4") {logstr += XI_ConvertString("a")+" ";}
					shownoqual = false;
				}
				else
				{
					switch(newitmqual)
					{
						case 0: logstr += TranslateString("","a broken") + " "; break; // This line should never be used
						case 1: logstr += TranslateString("","a worn") + " "; break;
						case 2: logstr += TranslateString("","an average") + " "; break;
						case 3: logstr += TranslateString("","a good") + " "; break;
						case 4: logstr += TranslateString("","a fine") + " "; break;
						case 5: logstr += TranslateString("","an excellent") + " "; break;
					}
				}
				logstr += GetItemNameByID(newitm);
				EquipCharacterByItem(&PChar, newitm);
			}
			if(newitm == "" || newitm == "bladeX4") { errstr = XI_ConvertString("a sword"); }
			*/
			// TIH <--

			// gun
			olditm = GetCharacterEquipByGroup(&PChar, GUN_ITEM_TYPE);
			newitm = FindCharacterItemByGroup(&PChar, GUN_ITEM_TYPE);

			// TIH --> fixed equipping of guns Aug24'06
			// using quality is not needed, and gets in the way if you had a higher quality low gun equipped 
			// even though you had a low quality higher gun in your inventory
			if(newitm != olditm && newitm != "")
			{
				if(logstr != "") logstr += " " + XI_ConvertString("and") + " ";
				switch(GetItemQualityByID(newitm))
				{
					case 0: logstr += TranslateString("","a badly worn") + " "; break;
					case 1: logstr += TranslateString("","a worn") + " "; break;
					case 2: logstr += TranslateString("","an average") + " "; break;
					case 3: logstr += TranslateString("","a good") + " "; break;
					case 4: logstr += TranslateString("","a fine") + " "; break;
					case 5: logstr += TranslateString("","an excellent") + " "; break;
					// default:
					logstr += TranslateString("","a") + " ";
				}
				logstr += GetItemNameByID(newitm);
				EquipCharacterByItem(&PChar, newitm);
			}
			if(newitm == "")
			{
				if(errstr != "") errstr += " " + XI_ConvertString("or") + " ";
				errstr += XI_ConvertString("a gun");
			}
			// TIH <--
			/* older method, which sort of broke a bit
			olditmqual = GetItemQualityByID(olditm);
			newitmqual = GetItemQualityByID(newitm);

			if(newitmqual == -1)
			{
				newitmqual = 5;
				shownoqual = true;
			}

			if(newitm != olditm && newitmqual >= olditmqual)
			{
				if(logstr != "") logstr += " " + XI_ConvertString("and") + " ";

				if(shownoqual)
				{logstr += XI_ConvertString("a")+" ";}
				else
				{
					switch(newitmqual)
					{
						case 0: logstr += TranslateString("","a badly worn") + " "; break;
						case 1: logstr += TranslateString("","a worn") + " "; break;
						case 2: logstr += TranslateString("","an average") + " "; break;
						case 3: logstr += TranslateString("","a good") + " "; break;
						case 4: logstr += TranslateString("","a fine") + " "; break;
						case 5: logstr += TranslateString("","an excellent") + " "; break;
					}
				}

				logstr += GetItemNameByID(newitm);
				EquipCharacterByItem(&PChar, newitm);
			}
			else
			{
				if(newitm == "")
				{
					if(errstr != "") errstr += " " + XI_ConvertString("or") + " ";
					errstr += XI_ConvertString("a gun");
				}
			}
			*/

			// glass
			olditm = GetCharacterEquipByGroup(&PChar, SPYGLASS_ITEM_TYPE);
			newitm = FindCharacterItemByGroup(&PChar, SPYGLASS_ITEM_TYPE);

			if(newitm != olditm && newitm != "")
			{
				if(logstr != "") logstr += " " + XI_ConvertString("and") + " ";
				logstr += XI_ConvertString("a")+" " + GetItemNameByID(newitm);
				EquipCharacterByItem(&PChar, newitm);
			}
			if(newitm == "")
			{
				if(errstr != "") errstr += " " + XI_ConvertString("or") + " ";
				errstr += XI_ConvertString("a spyglass");
			}

			// armor
			olditm = GetCharacterEquipByGroup(&PChar, ARMOR_ITEM_TYPE);
			newitm = FindCharacterItemByGroup(&PChar, ARMOR_ITEM_TYPE);
			if(olditm != newitm && newitm != "" && newitm != "cheaparmor")
			{
				if(logstr != "") logstr += " " + XI_ConvertString("and") + " ";
				logstr += GetItemNameByID(newitm);
				EquipCharacterByItem(&PChar, newitm);
			}
			if(newitm == "")
			{
				if(errstr != "") errstr += " " + XI_ConvertString("or") + " ";
				errstr += XI_ConvertString("any armor");
			}
		
		if (ENABLE_AMMOMOD)
		{// TIH --> mod toggle Jul15'06
		//JRH ammo mod start
			// powderflask
			olditm = GetCharacterEquipByGroup(&PChar, FLASK_ITEM_TYPE);
			newitm = FindCharacterItemByGroup(&PChar, FLASK_ITEM_TYPE);

			if(newitm != olditm && newitm != "")
			{
				if(logstr != "") logstr += " " + XI_ConvertString("and") + " ";
				logstr += XI_ConvertString("a Powder Flask");
				EquipCharacterByItem(&PChar, newitm);
			}
			if(newitm == "")
			{
				if(errstr != "") errstr += " " + XI_ConvertString("or") + " ";
				errstr += XI_ConvertString("s"+"a powder flask");
			}

			// ammopouch
			olditm = GetCharacterEquipByGroup(&PChar, POUCH_ITEM_TYPE);
			newitm = FindCharacterItemByGroup(&PChar, POUCH_ITEM_TYPE);

			if(newitm != olditm && newitm != "")
			{
				if(logstr != "") logstr += " " + XI_ConvertString("and") + " ";
				logstr += XI_ConvertString("an Ammunition Pouch");
				EquipCharacterByItem(&PChar, newitm);
			}
			if(newitm == "")
			{
				if(errstr != "") errstr += " " + XI_ConvertString("or") + " ";
				errstr += XI_ConvertString("s"+"an ammunition pouch");
			}
		//JRH ammo mod end
		}// TIH <-- mod toggle

			// output
			if(logstr != "") { Logit(TranslateString("","You equipped") + " " + logstr + "."); }
			if(errstr != "") { Logit(TranslateString("","You don't have") + " " + errstr + " " + TranslateString("","to equip") + "."); }
		break;
		// PB: Equip button <--

		// El Rapido Rapid Raid -->
		case "Rapid_Raid":
			if(dialogRun || dialogSelf || CheckAttribute(PChar,"paused")) break;//MAXIMUS
			PlaySound("OBJECTS\raid.wav");
			if(Pchar.nation != FRANCE)
			{
				Rapid_Raid("soldiers", "none", 10, FRANCE, "friend", "enemy","A French infantry unit suddenly appears and attacks you!", "French Musketeer", 8, 4, 120, 360, 9, 9, 0, 80, 4, 20);
			}
			else
			{
				Rapid_Raid("soldiers", "none", 10, SPAIN, "friend", "enemy","Several Conquistadores attack you!", "Conquistador", 9, 5, 180, 400, 14, 6, 0, 100, 4, 30);
			}
		break;
		// El Rapido Rapid Raid <--
			
		// NK <--
		// TIH -->
		case "TIH_FireDrill":
			// ccc firedrill properly added under its own key now -tih
			if(dialogRun || dialogSelf || CheckAttribute(PChar,"paused")) break;//MAXIMUS
			ref mch = GetMainCharacter();

			// ccc firedrill
 			if( bSeaActive && !bAbordageStarted && FIREDAMAGE>1) // checks if you are in sailing mode MAR18
			{
				if (ENABLE_FIREDRILL == 1)
				{
					Log_SetStringToLog(TranslateString("","All hands execute fire drill ! NOW !!")); // just a screenmessage
					if (FD_REQUIRE_DEFENSE == 0 || CheckOfficersPerk(mch,"BasicBattleState"))
					// starts firedrill only if you have shipdefense ability
					// or this check is turned off in BS.h -tih
					{
						mch.firedrill = 1; // adds attribute to player as "marker" that firedrill is ordered
						PlaySound("clear_for_action"); // just soundeffect
						PlaySound("objects\abordage\abordage_loosing.wav");
						Ship_SetSailState(GetMainCharacterIndex(), 0.0); // smoldering sails jettisoned MAR18 NK uses index not ref. 05-04-20
	    				if(GUN_DOUSING==1)
	     				{
	     					Ship_ChangeCharge(mch, sti(mch.Ship.Cannons.Charge.Type));
							// cartridges jettisoned MAR18
							Log_SetStringToLog(TranslateString("","Sails and cartridges jettisoned.")); // MAR18
						}
					}
					else
					{
						Log_SetStringToLog(TranslateString("","Captain, what's a firedrawl?"));	// just a screenmessage
						Log_SetStringToLog(TranslateString("","Your crew seems to lack the SHIP DEFENSE ability..."));	// just a screenmessage
						PlaySound("VOICE\" + LanguageGetLanguage() + "\Eng_m_b_079.wav");	// just soundeffect
					}
				}
			}
			// ccc firedrill end, original potion-use mod put with its original key -tih
		break;
		// TIH <--

		// boal -->
		case "BOAL_UsePotion":

			// NK 04-09-08 to allow toggle between using min or max potion
			/*aref arItm;
			int itmIdx;
			itmIdx = FindPotionFromChr(PChar, &arItm, 0);
			while(itmIdx>=0)
			{
				if(CheckAttribute(arItm,"potion.health"))
				{
					DoCharacterUsedItem(PChar,arItm.id);
					Log_SetStringToLog("Use potion");
					break;
				}
				itmIdx = FindPotionFromChr(PChar, &arItm, itmIdx+1);
			}*/
			if(dialogRun || dialogSelf || CheckAttribute(PChar,"paused")) break;//MAXIMUS
			int idx = -1;
			if(USEMAXPOTION_ONKEYPRESS)
			{
				MaxHealthPotionForCharacter(PChar, &idx);
			}
			else
			{
				MinHealthPotionForCharacter(PChar, &idx);
			}
			if(idx != -1)
			{
				DoCharacterUsedItem(PChar, Items[idx].id);
				Log_SetStringToLog(TranslateString("","Used potion"));
			}
			// NK <--
		break;

		case "BOAL_Control":
			// NK basetime 05-04-25 -->
			//Log_SetStringToLog("TestF11");
			if(dialogRun || dialogSelf || CheckAttribute(PChar,"paused")) break;//MAXIMUS
			float basetime = 1.0;
			if(CheckAttribute(PChar,"basetime")) basetime = stf(PChar.basetime);
			if(IsPerkIntoList("TimeSpeed"))
			{
				SetTimeScale(basetime);
				DelPerkFromActiveList("TimeSpeed");
				Log_SetStringToLog(XI_ConvertString("Time") + " " + "x1");
				PChar.timeaccel1030 = "30";
			}
			else
			{
				SetTimeScale(3.0 * basetime);
				Log_SetStringToLog(XI_ConvertString("Time") + " " + "x3");
				AddPerkToActiveList("TimeSpeed");
				PChar.timeaccel1030 = "30";
			}
		break;
		
		case "BOAL_Control0":
			if(dialogRun || dialogSelf || CheckAttribute(PChar,"paused")) break;//MAXIMUS
			float basetime0 = 1.0;
			if(CheckAttribute(PChar,"basetime")) basetime0 = stf(PChar.basetime);
			//Log_SetStringToLog("TestF11");
			// NK Fixed 04-09-08 to actually toggle.
			if(!IsPerkIntoList("TimeSpeed")) { AddPerkToActiveList("TimeSpeed"); }
			if(!CheckAttribute(PChar, "timeaccel1030")) PChar.timeaccel1030 = "30";
			if(PChar.timeaccel1030 != "30")
			{
				PChar.timeaccel1030 = "30";
				SetTimeScale(30.0 * basetime0);
				Log_SetStringToLog(XI_ConvertString("Time") + " " + "x30");
			}
			else
			{
				PChar.timeaccel1030 = "10";
				SetTimeScale(10.0 * basetime0);
				Log_SetStringToLog(XI_ConvertString("Time") + " " + "x10");
			}
			// NK basetime <--
		break;

		case "BOAL_Control2":
			/*if(PChar.nation == ENGLAND)
			{
				PChar.nation = PIRATE;
			}
			else
			{
				PChar.nation = ENGLAND;
			}*/
			//Log_SetStringToLog("Set Nation to " + PChar nation);
			//DeleteAttribute(PChar, "quest.generate_kill_quest");
			//int num = FindNearCharacters(PChar, 1, 1, 90, 0.50, true, false);
			// = GetCharacter(num);



/*
		int num = FindNearCharacters(Pchar, 1.0, -1.0, 30.0, 0.1, false, false);
			// checks if there are other people around the initial target. 2.5 is the checkradius

		for(int j = 0; j <= num; j++)	// the following loop runs for each near character
		{
			int indx = sti(chrFindNearCharacters[j].index);	// defines near character as idx
			ref findC;
			findC = GetCharacter(indx);	// necessary? to get object for next line
			Log_SetStringToLog("90: " + findC.name + " " + findC.lastname);

		}

*/

/*
			// For DoLocWrite!
			float magup = 0;
			if(CheckAttribute(PChar, "lwmagup")) magup = stf(PChar.lwmagup);
			magup += 0.1;
			PChar.lwmagup = magup;
			Logit("LOCWRITE: Up magnitude is now " + floattostring(magup, 2));
			// <--
*/
// changed by MAXIMUS [just for fun] -->
			int res = SendMessage(GetMainCharacter(),"ls",MSG_CHARACTER_EX_MSG,"FindDialogCharacter");//LAi_FindNearestVisCharacter(PChar, 20);
			ref findCh;
			if (res>0)//if(res != -1)
			{
				findCh = GetCharacter(res);
				if(!CheckAttribute(findCh, "corpse"))
				{
					res = findCh.chr_ai.hp;
					LaunchOfficer(findCh);
				//Log_SetStringToLog(XI_ConvertString("You see") + " " + findCh.name + " " + findCh.lastname + " " + XI_ConvertString("Fencing") + " " + findCh.skill.Fencing + " " + XI_ConvertString("HP") + " " + res );
// changed by MAXIMUS [just for fun] <--
				}
			}
		break;
	}
// boal <--


// dchaley -->
// TIH quicksave disabled Aug24'06
	if (ControlName == "DCH_Quicksave") { DoQuickSave(); }
	if (ControlName == "DCH_Quickload") { DoQuickLoad(); }
/* Code disabled because the quicksave process creates corrupted games which are now causing serious issues
// this code will be worked on and revisited in build 14... until then, do not uncomment it without it being
// completely fixed of all its evil ways !!!
	switch ( ControlName )
	{
		case "DCH_Quicksave":
		if(!bSeaActive && !bAbordageStarted)
		{ProcessQuicksave();}
		else
		{LogIt(TranslateString(κκ,"You can't save while sailing or boarding!"));}
		break;
		case "DCH_Quickload": ProcessQuickload(); break;
	}
*/
// dchaley <--
	

// ccc special weapons, equip by hotkey  
	
	if(!bSeaActive || bAbordageStarted)
	{
		switch(ControlName)
		{
		case "BI_ChargeCannonballs":
		// PB: Equip [Regular Blade]
			if(CheckCharacterItem(Pchar,FindCharacterItemByGroup(&PChar, BLADE_ITEM_TYPE)))
			{
				EquipCharacterByItem(&PChar, FindCharacterItemByGroup(&PChar, BLADE_ITEM_TYPE));
				Logit(TranslateString("","You equiped a") + " "+GetItemNameByID(FindCharacterItemByGroup(&PChar, BLADE_ITEM_TYPE))+".");
			}
			else
			{Logit(TranslateString("","You don't have a regular blade to equip."));}
			break;

		case "BI_ChargeGrapes":
		// PB: Equip [Regular Gun]
			if(CheckCharacterItem(Pchar,FindCharacterItemByGroup(&PChar, GUN_ITEM_TYPE)))
			{
				EquipCharacterByItem(&PChar, FindCharacterItemByGroup(&PChar, GUN_ITEM_TYPE));
				Logit(TranslateString("","You equiped a") + " "+GetItemNameByID(FindCharacterItemByGroup(&PChar, GUN_ITEM_TYPE))+".");
			}
			else
			{Logit(TranslateString("","You don't have a regular gun to equip."));}
			break;

		case "BI_ChargeKnippels":
		// PB: Equip [Cobblestone]
			if(CheckCharacterItem(Pchar,"pistolrock"))
			{
				EquipCharacterByItem(&PChar, "pistolrock");
				Logit(TranslateString("","You equiped a cobblestone."));
			}
			else
			{Logit(TranslateString("","You don't have a cobblestone to equip."));}
			break;

		case "BI_ChargeBombs":
		// PB: Equip [Sandbag]
			if(CheckCharacterItem(Pchar,"bladeX2"))
			{
				EquipCharacterByItem(&PChar, "bladeX2");
				Logit(TranslateString("","You equiped a sandbag."));
			}
			else
			{Logit(TranslateString("","You don't have a sandbag to equip."));}
			break;

		// PB: More fast equip keys -->
		case "BI_ChargeKey5":
		// PB: Equip [Etherbottle]
			if(CheckCharacterItem(Pchar,"pistolgas"))
			{
				EquipCharacterByItem(&PChar, "pistolgas");
				Logit(TranslateString("","You equiped an etherbottle."));
			}
			else
			{Logit(TranslateString("","You don't have an etherbottle to equip."));}
			break;

		case "BI_ChargeKey6":
		// PB: Equip [Thief's Knife]
			if(CheckCharacterItem(Pchar,"bladeX3"))
			{
				EquipCharacterByItem(&PChar, "bladeX3");
				Logit(TranslateString("","You equiped a thief's knife."));
			}
			else
			{Logit(TranslateString("","You don't have a thief's knife to equip."));}
			break;

		case "BI_ChargeKey7":
		// PB: Equip [Poisoned Throwingknife]
			if(CheckCharacterItem(Pchar,"pistolpdart"))
			{
				EquipCharacterByItem(&PChar, "pistolpdart");
				Logit(TranslateString("","You equiped a poisoned throwingknife."));
			}
			else
			{Logit(TranslateString("","You don't have a poisoned throwingknife to equip."));}
			break;

		case "BI_ChargeKey8":
		// PB: Equip [Stinkpot]
			if(CheckCharacterItem(Pchar,"pistolstink"))
			{
				EquipCharacterByItem(&PChar, "pistolstink");
				Logit(TranslateString("","You equiped a stinkpot."));
			}
			else
			{Logit(TranslateString("","You don't have a stinkpot to equip."));}
			break;

		case "BI_ChargeKey9":
		// PB: Equip [Grenade]
			if(CheckCharacterItem(Pchar,"pistolgrenade"))
			{
				EquipCharacterByItem(&PChar, "pistolgrenade");
				Logit(TranslateString("","You equiped a grenade."));
			}
			else
			{Logit(TranslateString("","You don't have a grenade to equip."));}
			break;

		case "BI_ChargeKey0":
		// PB: Equip [Your Trusty Fists]
			if(CheckCharacterItem(Pchar,"bladeX4"))
			{
				EquipCharacterByItem(&PChar, "bladeX4");
				Logit(TranslateString("","You equiped your trusty fists."));
			}
			else
			{Logit(TranslateString("","What the heck? You don't have your trusty fists???"));}
			break;
		// PB <--
		}
	}	
	ProcessCCCkeys(ControlName);  // ccc Jan07, for Directsail and mines
// ccc end


	
	if(bSeaActive && !bAbordageStarted)
	{
		switch(ControlName)
		{
			case "MainMenu": ProcessMainMenuKey();	break;
			case "MainMenuDouble": ProcessMainMenuKey(); break;
			case "Interface": ProcessInterfaceKey();break;

			case "Sea_CameraSwitch": SeaCameras_Switch(); break;
			case "Ship_Fire": Ship_DoFire(); break;

			case "Aimed_Ship_Fire": Ship_DoAimedFire(); break;	// LDH - allows manual aiming if AUTO_AIMED_FIRE is on.
			//case "Tele": Sea_ReloadStart(); break;
		}
	}
	else
	{
		switch(ControlName)
		{
			case "MainMenu": ProcessMainMenuKey();	break;
			case "MainMenuDouble": ProcessMainMenuKey(); break;
			case "Interface": ProcessInterfaceKey();break;
			case "Tele":
				StartQuickTeleport();
				break;
			case "TeleBack": Teleport(-1); break;
			case "Action":
				//DumpAttributes(loadedLocation/*loadedLocation.reload.reload1.x*/);
				//trace("Y: " + loadedLocation.reload.reload1.y);
				//trace("Z: " + loadedLocation.reload.reload1.z);
			break;
		}
	}


	/*switch(ControlName)
	{
		counter++;
		if(counter > 3) counter = 0;
		case "CameraSwitch":
			switch(counter)
			{
			case 0: SetDayTime(DAY_TIME_NIGHT); break;
			case 1: SetDayTime(DAY_TIME_MORNING); break;
			case 2: SetDayTime(DAY_TIME_DAY); break;
			case 3: SetDayTime(DAY_TIME_EVENING); break;
			}
		break;
	}*/
	//LanguageCloseFile(tmpLangFileID);
}

// added by MAXIMUS -->
bool StraifCharacter(ref chr)
{
	if(!CheckAttribute(chr,"model")) return false;
	if(GetModelIndex(chr.model)==-1) return false;
	aref ourModel; makearef(ourModel,Models[GetModelIndex(chr.model)]);
	if(CheckAttribute(ourModel,"status") && ourModel.status=="C_III")
	{
		return true;
	}
	return false;
}

#event_handler("Lai_EndAction", "Lai_ReturnNormal");
void Lai_ReturnNormal()
{
	aref chr = GetEventData();
	CharacterPlayAction(chr, "");
	SideStepControl(-STRAIF_DIST, false);
	SideStepControl(STRAIF_DIST, false);
}
#event_handler("RemoveCorpse", "Lai_KillCorpse");
void Lai_KillCorpse()
{
	aref chCorpse = GetEventData();
	Lai_KillCharacter(chCorpse);
}
// added by MAXIMUS <--

void Teleport(int step)
{
	nTeleportLocation = nTeleportLocation + step;
	if(nTeleportLocation >=	nLocationsNum) nTeleportLocation = 1;
	if(nTeleportLocation <=	0) nTeleportLocation = nLocationsNum - 1;

	sTeleportLocName = Locations[nTeleportLocation].id;
	Trace("Teleport to '" + sTeleportLocName + "'");

	ReleaseSound(0);
	ClearEvents();
	ClearPostEvents();
	DeleteEntities();
	SetEventHandler("frame","NewGame",1);
}

void ProcessMainMenuKey()
{
	LaunchMainMenu();
}

void ProcessInterfaceKey()
{
	if(bSeaActive && !bAbordageStarted)
	{
		if( CheckAttribute(&BattleInterface,"ComState") && sti(BattleInterface.ComState) != 0 )
			{return;}
	}
	else
	{
		if( SendMessage(GetMainCharacter(),"ls",MSG_CHARACTER_EX_MSG,"IsFightMode") != 0 )
			{return;}
		if( CheckAttribute(&objLandInterface,"ComState") && sti(objLandInterface.ComState) != 0 )
			{return;}
	}
	if( IsEntity(&worldMap) ) return;
//	LaunchSelectMenu(); // MAXIMUS interface MOD
	LaunchCharacter(GetMainCharacter()); // MAXIMUS interface MOD
}

//ccc survival ->
void GameOverE()
{
	//int tmpLangFileID = LanguageOpenFile("interface_strings.txt");
	ref mc;
	mc = GetMainCharacter();
	if(rand(100) + (makeint(mc.skill.Sneak)*3) > DEATHRATE)	// BF mar05
	{	//ccc new survival section
// KK
		if (HasSubStr(mc.ship.type, "Tartane") == true || mc.ship.type == "Gunboat") {
			GameOverOrg("sea");
			DeleteSeaEnvironment();
			//LanguageCloseFile(tmpLangFileID);
			return;
		}
// <-- KK
		Event("DoInfoShower","sl","MainMenuLaunch",true);	//TIH - black out the screen to hide uglyjunk
		LAi_SetCurHPMax(mc);
		mc.ship.type = "Tartane1";
		Ship_CreateForCharacter(mc, 0, "Lifeboat");	// ccc apr03
// KK -->
		SetCharacterGoods(mc, GOOD_BALLS, 0);
		SetCharacterGoods(mc, GOOD_GRAPES, 0);
		SetCharacterGoods(mc, GOOD_KNIPPELS, 0);
		AddCharacterGoods(mc, GOOD_WHEAT, 2);
		AddCharacterGoods(mc, GOOD_RUM, 2);
// <-- KK
		mc.lifeboatlaunch = true;	//TIH - better check for when they sank
		Sea_ReloadStart();
		PostEvent("DoInfoShower",100,"s","");	//TIH - clears black screen
		PlaySound("ship_sinking");		//ccc mar20 // KK
		Log_SetStringToLog(TranslateString("","You manage to launch a boat in the last moment."));	//ccc mar20
		Log_SetStringToLog(TranslateString("","With a few mates you escape from disaster."));	//ccc mar20

	}
	else
	{	//ccc call original GameOver function
		GameOverOrg("sea");
		DeleteSeaEnvironment();
	}
	//LanguageCloseFile(tmpLangFileID);
}

void GameOver(string sName)
{
	if (bSuppressResurrection) return; // KK

	//int tmpLangFileID = LanguageOpenFile("interface_strings.txt");
	string loc = ""; // KK
	ref mc = GetMainCharacter(); // KK

// TIH --> process cleanup 7-7-06

	//ccc call original GameOver function / BF mar05
	if (rand(100) + (makeint(mc.skill.Sneak)*3) < DEATHRATE) {
		GameOverOrg(sName);
		//LanguageCloseFile(tmpLangFileID);
		return;
	}

	// TIH if die during boarding, you are DEAD
	if (sName == "boarding") {
		GameOverOrg(sName);
		//LanguageCloseFile(tmpLangFileID);
		return;
	}

	// TIH if mutiny, you are put to sea
	if (sName == "mutiny") {
		PlaySound("VOICE\"+LanguageGetLanguage()+"\Dut_m_a_054.wav");		//ccc mar20
		Log_SetStringToLog(XI_ConvertString("MUTINY") + "!");		//ccc mar20
		Log_SetStringToLog(TranslateString("","'Cap'n, we are giving you and your cronies this boat."));		//ccc mar20
		Log_SetStringToLog(TranslateString("","If you're careful, you just might make it."));		//ccc mar20
		Log_SetStringToLog(TranslateString("","But given your past performance you'll all starve!'"));		//ccc mar20
		GameOverE();
		//LanguageCloseFile(tmpLangFileID);
		return;
	}

	//MAXIMUS - if you die during fight with your crew
	if(CheckAttribute(mc,"mutiny"))
	{
		GameOverOrg("mutiny");
		DeleteAttribute(mc,"mutiny");
		//LanguageCloseFile(tmpLangFileID);
		return;
	}

	// TIH died in land fight, so you are resurrected somewhere
	//ccc new survival section
	string islandID;
// KK -->
	string TownID;
	int TownNation;

	Lai_SetActorType(mc);
	LAi_type_actor_Reset(mc);
	Lai_SetPlayerType(mc);
// <-- KK
	//PlaySound("trep\skeleton\skeleton01.wav");	//ccc mar20 // TIH dont need this 7-7-06
	//StartVideo("artefact");	//ccc mar20 // TIH dont need this 7-7-06

// KK -->
	if (GetCharacterShipType(mc) != SHIP_NOTUSED) loc = GetCharacterShipLocation(mc);
	if (CheckAttribute(Locations[FindLocation(loc)], "type") && Locations[FindLocation(loc)].type != "port" && CheckAttribute(Locations[FindLocation(loc)], "id") && !HasSubStr(Locations[FindLocation(loc)].id,"port")) loc = mc.location;//MAXIMUS
	TownID = GetBestTown(loc);
	IslandID = GetIslandIDFromTown(TownID);
	TownNation = GetTownNation(TownID);

	if (mc.location.from_sea == "Muelle_shore_02")
	{
		mc.location.from_sea = "Muelle_port";
		PlaceFleetNearShore(mc.location.from_sea);
	}
// <-- KK

	//apply damage and losses
	// TIH --> new damage and losses code 7-8-06
	//mc.chr_ai.hp_max = makeint(sti(mc.chr_ai.hp_max) * 0.9);
	//mc.ship.hp = makeint(sti(mc.ship.hp) * rand(6)/10)+50;
	//mc.Ship.crew.quantity = makeint(sti(mc.Ship.crew.quantity) * rand(6)/10)+5;
	//mc.money = makeint(sti(mc.money) * rand(4)/10);
	// TIH <--

	string gun = GetCharacterEquipByGroup(&mc, GUN_ITEM_TYPE);
	RemoveCharacterEquip(mc, GUN_ITEM_TYPE);
	TakeItemFromCharacter(mc, gun);

	// PB: Keep you fists when you die -->
		if(GetCharacterEquipByGroup(&mc, BLADE_ITEM_TYPE) !="bladeX4")
		{
			string blade = GetCharacterEquipByGroup(&mc, BLADE_ITEM_TYPE);
			RemoveCharacterEquip(mc, BLADE_ITEM_TYPE);
			TakeItemFromCharacter(mc, blade);
		}
	// PB: Keep you fists when you die <--

	//JRH loose pf, ap, pb or ab
		string flask = GetCharacterEquipByGroup(&mc, FLASK_ITEM_TYPE);
		string pouch = GetCharacterEquipByGroup(&mc, POUCH_ITEM_TYPE);

		if(CheckCharacterItem(mc,"powderbarrel") > 0)
		{
			TakeNItems(mc,"powderbarrel",-1);
		}
		else
		{
			if(CheckAttribute(mc,"equip."+FLASK_ITEM_TYPE))
			{
				RemoveCharacterEquip(mc, FLASK_ITEM_TYPE);
				TakeItemFromCharacter(mc, flask);
			}
			else
			{
				//do nothing
			}
		}
		if(CheckCharacterItem(mc,"ammobag") > 0)
		{
			TakeNItems(mc,"ammobag",-1);
		}
		else
		{
			if(CheckAttribute(mc,"equip."+POUCH_ITEM_TYPE))
			{
				RemoveCharacterEquip(mc, POUCH_ITEM_TYPE);
				TakeItemFromCharacter(mc, pouch);
			}
			else
			{
				//do nothing
			}
		}
	//JRH

	// TIH --> slight reordering of process - Jul10'06
	// lose crew and money first before the time span
	mc.Ship.crew.quantity = makeint(sti(mc.Ship.crew.quantity) * (5 + rand(3))/10);// 20-50% loss
	mc.money = makeint(sti(mc.money) * (4 + rand(5))/10);// 10-60% loss

	// figure their dmgs here, before the time span, then we adjust dmgs AFTER the time span
	int degradedHP = makeint(sti(mc.ship.hp) * (5 + rand(3))/10);// 20-50% loss
	int degradedSP = makeint(sti(mc.ship.sp) * (5 + rand(3))/10);// 20-50% loss

	// time span moved here as to apply to both tavern girl and NO tavern girl
	WaitDate("", 0,0,4,0,0);// 4 days

	// damage is applied after time span so hull and sails dont get auto-repaired during 4 days
	mc.ship.hp = degradedHP;// 20-50% loss
	mc.ship.sp = degradedSP;// 20-50% loss
	// TIH <--

// KK -->
	//start bedroomscene
	WaitDate("", 0,0,4,0,0);
	ResurrectingOfficiant = GetTownOfficiant(TownID);
	if (GetActualNationRelation2MainCharacter(TownNation) == RELATION_ENEMY && CheckAttribute(ResurrectingOfficiant, "resurrection.shore") == true && FindLocation(ResurrectingOfficiant.resurrection.shore) > 0) {
		mc.location.from_sea = ResurrectingOfficiant.resurrection.shore;
		PlaceFleetNearShore(mc.location.from_sea);
	}
	ChangeCharacterAddressGroup(ResurrectingOfficiant, ResurrectingOfficiant.resurrection.location, "goto", "goto3");
	mc.quest.ResurrectionEvent.win_condition.l1 = "location";
	mc.quest.ResurrectionEvent.win_condition.l1.location = ResurrectingOfficiant.resurrection.location;
	mc.quest.ResurrectionEvent.win_condition = "ResurrectionEvent";
	DoReloadCharacterToLocation(ResurrectingOfficiant.resurrection.location, "goto", "goto2");
	mc.NoSave.Resurrection = 1;
	Locations[FindLocation(loc)].reload.l1.disable = 1;
	Log_SetStringToLog(TranslateString("","You regain consciousness after a long feverish sleep"));
	PlaySound("AMBIENT\SHOP\sigh2.wav");
// <-- KK
	//LanguageCloseFile(tmpLangFileID);
// TIH <-- process cleaning
}

void GameOverOrg(string sName)	//ccc original GameOver function
{
	ref mc;
	int nSelect;
	string sFileName;
	//ResetSoundScheme();
	//PauseAllSounds();
		ResetSound();
		EngineLayersOffOn(false);

	mc = GetMainCharacter();

		ClearEvents();
		ClearPostEvents();
		DeleteEntities();

		if(sti(InterfaceStates.Launched)) {
			UnloadSegment(Interfaces[CurrentInterface].SectionName);
		}

		if(LoadSegment("Interface\BaseInterface.c"))
		{
			InitBaseInterfaces();
			UnloadSegment("Interface\BaseInterface.c");
		}
		InitSound();

		SetEventHandler(EVENT_END_VIDEO,"LaunchMainMenu_afterVideo",0);


		switch(sName)
		{
		case "sea":
			nSelect = rand(1);
			sFileName = "skeleton_on_beach";
			switch(nSelect)
			{
				case 0: sFileName = "skeleton_on_beach"; break;
				case 1: sFileName = "undersea"; break;
			}
			StartPostVideo(sFileName,1);
		break;

		case "boarding":
			StartPostVideo("skeleton_on_beach",1);
		break;

		case "land":
			StartPostVideo("blaze_land_dead",1);
		break;

		case "mutiny":
			StartPostVideo("blaze_mutiny_dead",1);
		break;
		}
		InterfaceStates.Buttons.Resume.enable = false;
		InterfaceStates.Buttons.Save.enable = false;
}
//ccc survival <-
