#include "battle_interface\msg_control.h"
#include "sea_ai\script_defines.h"
#include "battle_interface\landinterface.c"
#include "battle_interface\ispyglass.c"
#include "battle_interface\reload_tables.c"
#include "battle_interface\utils.c"
#include "battle_interface\ActivePerksShow.c"
#include "battle_interface\procGetSailTextureData.c"		// the function procGetSailTextureData() is now moved into a separate file

#define BI_ICONS_SHIPS_TEXTURE_NAME "battle_interface\icons.tga"

#define BI_ICONS_ST_NONE		0
#define BI_ICONS_ST_MYSHIPS		1
#define BI_ICONS_ST_COMMAND		2
#define BI_ICONS_ST_TARGETING	3

int bi_icons_ShowType;
int bi_icons_CommandMode;

int bi_idxSelectedPicture;

object BattleInterface;

bool bDisableSailTo = false;

bool bDisableMapEnter = false;

bool bReloadCanBe = false;
bool bMapEnter = false;
bool bSailTo=false;
bool bAttack=false;
bool bDefend=false;

bool bEnableIslandSailTo=false;

bool bDisableAllCommands = false; // KK

int BI_intRetValue;
int BI_retComValue;
int BI_ChargeState[5];
float BI_g_fRetVal;

int BI_intNRetValue[4];

object BI_objRetValue;
object objShipPointer;

#event_handler("DoSailHole","ProcessSailDamage");
#event_handler("evntRandomSailDmg","ProcessRandomSailDmg");
#event_handler("NextDay","ProcessDayRepair");
#event_handler("GetSailTextureData","procGetSailTextureData");
#event_handler("GetRiggingData","procGetRiggingData");
#event_handler("EventMastFall","procMastFall");
#event_handler("evntBISelectShip","procBISelectShip");

#event_handler(SHIP_CREATE,"BI_CreateShip");

void InitBattleInterface()
{
	ref chMain = GetMainCharacter();

	// LDH add time display to screen 17Sep06
	if (DISPLAY_SEA_TIME || CheckCharacterEquipByGroup(chMain, CLOCK_ITEM_TYPE) != "") // PB: Clocks
	{
		chMain.CurrentTime = 0.0;
		chMain.BaseCurrentTime = 0.0;
		chMain.TimeSeconds = 0;
		PostEvent("DisplaySeaTimeEvent",250);
	}

	BI_InitializeCommands();
	bi_icons_CommandMode = 0;
	BattleInterface.SelCharacter = -1;
	bi_idxSelectedPicture = -1;
	BattleInterface.boardRadius = 50;
	BattleInterface.freeDistance = MIN_ENEMY_DISTANCE_TO_DISABLE_MAP_ENTER;

	SetParameterData();
	BattleInterface.blindSpeed = 0.003;
	BattleInterface.MaxWind = 30.0;
	BattleInterface.MaxShipSpeed = 20.0;

	BattleInterface.ShowNavigator = InterfaceStates.BattleShow.Navigator; // KK
	BattleInterface.ShowCommands = InterfaceStates.BattleShow.Command;
	CreateEntity(&BattleInterface,"battle_interface");
	DeleteAttribute(&BattleInterface,"CommandTextures");
	DeleteAttribute(&BattleInterface,"CommandShowParam");
	LayerAddObject(SEA_EXECUTE,&BattleInterface,-1);
	LayerAddObject(SEA_REALIZE,&BattleInterface,-1);

	SetEventHandler(SHIP_DELETE,"BI_DeleteShip",0);
	SetEventHandler(SHIP_DEAD,"BI_DeadShip",0);

	SetEventHandler("BI_CommandEndChecking","BI_CommandEndChecking",0);
	SetEventHandler("BI_LaunchCommand","BI_LaunchCommand",0);
	SetEventHandler("BI_GetChargeQuantity","BI_GetChargeQuantity",0);
	SetEventHandler("BI_SetPossibleCommands","BI_SetPossibleCommands",0);
	SetEventHandler("GetCurrentCharge","GetCurrentCharge",0);
	SetEventHandler(BI_EVENT_SET_VISIBLE,"BI_CommandVisible",0);
	SetEventHandler(BI_EVENT_SET_SEA_STATE,"BI_SetSeaState",0);
	SetEventHandler(BI_EVENT_GET_DATA,"BI_GetData",0);
	SetEventHandler(BI_EVENT_CHECK_SHIPSTATE_SHOW,"BI_GetSSShow",0);
	SetEventHandler("evntGetLandData","BI_GetLandData",0);
	SetEventHandler(BI_EVENT_GET_FORT_RELATION,"BI_GetFortRelation",0);
	SetEventHandler(EVENT_CHANGE_COMPANIONS,"RefreshBattleInterface",0);
	SetEventHandler("BI_CallUpdateShip","BI_UpdateShip",0);
	SetEventHandler("frame","BI_Frame",1);
	SetEventHandler("evntPerkAgainUsable","BI_PerkAgainUsable",0);
	SetEventHandler("evntSetUsingAbility","procSetUsingAbility",0);
	SetEventHandler("evntCheckEnableLocator","procCheckEnableLocator",0);
	SetEventHandler("evntCheckEnableShip","procCheckEnableShip",0);
	SetEventHandler("evntGetSRollSpeed","procGetSRollSpeed",0);

	procLoadIntoNew(); // Проинитим таблицу активных перков
	SetEventHandler("Control Activation","BI_ProcessControlPress",0);

	bDisableAllCommands = bQuestDisableAllCommands; // KK

	CreateILogAndActions(LOG_FOR_SEA);
	Log_SetActiveAction("Nothing");
}

ref BI_GetFortRelation()
{
	BI_intRetValue = BI_RELATION_NEUTRAL;
	aref arLoc = GetEventData();
	int chrIdx = Fort_FindCharacter(AISea.Island,"reload",arLoc.name);
	if(chrIdx>=0)
	{
		switch( SeaAI_GetRelation(chrIdx,GetMainCharacterIndex()) )
		{
		case RELATION_FRIEND:	BI_intRetValue = BI_RELATION_FRIEND;	break;
		case RELATION_NEUTRAL:	BI_intRetValue = BI_RELATION_NEUTRAL;	break;
		case RELATION_ENEMY:	BI_intRetValue = BI_RELATION_ENEMY;		break;
		}
	}
	return &BI_intRetValue;
}

ref BI_GetSSShow()
{
	BI_intRetValue = false;
	int charIdx = GetEventData();
	ref mchref = GetMainCharacter();
	switch( GetCharacterEquipByGroup(GetMainCharacter(), SPYGLASS_ITEM_TYPE) )
	{
	case CHEAP_SPYGLASS:	BI_intRetValue = false;	break;
	case COMMON_SPYGLASS:	BI_intRetValue = true;	break;
	case GOOD_SPYGLASS:		BI_intRetValue = true;	break;
	case SUPERIOR_SPYGLASS:	BI_intRetValue = true;	break;
	}
	return &BI_intRetValue;
}

void BI_CommandVisible()
{
	int visibleFlag = GetEventData();
	SendMessage(&BattleInterface,"ll",BI_SET_VISIBLE,visibleFlag);
}

int bi_nReloadTarget=-1;
bool biold_bCanEnterToLand = false;
bool biold_bAbordageShipCanBe = false;
bool biold_bAbordageFortCanBe = false;
bool biold_bReloadCanBe = false;
bool biold_bMapEnter = false;
bool bOldNotEnoughBalls = false;
bool bNotEnoughPowder = false; // TIH new method
bool bOldNotEnoughPowder = false; // TIH new method
//bool outOfGunpowder = false; // TIH depreciated // added by MAXIMUS [gunpowder mod]
void BI_Frame()
{
	bool bYesUpdateCommand = false;
	ref PChar = GetMainCharacter(); // KK

// TIH --> complete rewrite of this action, again Nov12'06

	// TIH --> mod toggle 7-7-06
	if (CANNONPOWDER_MOD && GetCaracterShipCannonsType(PChar) != CANNON_TYPE_NONECANNON) {
		// added by MAXIMUS [gunpowder mod] -->
		int fireGunpowder = 0;
		int ourPwdr = GetCargoGoods(PChar, GOOD_GUNPOWDER);
		ref rCannon; makeref(rCannon,Cannon[GetCaracterShipCannonsType(PChar)]);
		if(CheckAttribute(rCannon,"gunpowder")) fireGunpowder = sti(rCannon.gunpowder);

		// TIH --> Better method that covers all bases of charge status icon Nov12'06
		// - only needs to check arcs until enough powder is ok
		// - arcs are not checked if they have no cannons (otherwise it would always be true for enough gunpowder)
		// - only updates flasher icon when it should
		// - uses a toggle global boolean to insure proper display changes
		// - actually tested and works

		bNotEnoughPowder = true;

		int checkA  	= sti(GetCannonArcCurQty(PChar, 0)) + sti(GetCannonArcCurQty(GetMainCharacter(), 2));
		int checkB  	= sti(GetCannonArcCurQty(PChar, 1));
		int checkC  	= sti(GetCannonArcCurQty(PChar, 3));
		if ( bNotEnoughPowder && checkA >= 1 && ourPwdr >= checkA * fireGunpowder ) { bNotEnoughPowder = false; } // front & rear
		if ( bNotEnoughPowder && checkB >= 1 && ourPwdr >= checkB * fireGunpowder ) { bNotEnoughPowder = false; } // starboard
		if ( bNotEnoughPowder && checkC >= 1 && ourPwdr >= checkC * fireGunpowder ) { bNotEnoughPowder = false; } // port

		/* simply another way to check arcs, but the other above is a bit better, more effecient
		int cannonFrnt  = sti(GetCannonArcCurQty(GetMainCharacter(), 0));
		int cannonRear  = sti(GetCannonArcCurQty(GetMainCharacter(), 2));
		int cannonStar  = sti(GetCannonArcCurQty(GetMainCharacter(), 1));
		int cannonPort  = sti(GetCannonArcCurQty(GetMainCharacter(), 3));
		if ( bNotEnoughPowder && cannonFrnt >= 1 && ourPwdr >= cannonFrnt * fireGunpowder ) { bNotEnoughPowder = false; } // front
		if ( bNotEnoughPowder && cannonRear >= 1 && ourPwdr >= cannonRear * fireGunpowder ) { bNotEnoughPowder = false; } // rear
		if ( bNotEnoughPowder && cannonStar >= 1 && ourPwdr >= cannonStar * fireGunpowder ) { bNotEnoughPowder = false; } // starboard
		if ( bNotEnoughPowder && cannonPort >= 1 && ourPwdr >= cannonPort * fireGunpowder ) { bNotEnoughPowder = false; } // port
		*/

		if(bNotEnoughPowder != bOldNotEnoughPowder)
		{
			bOldNotEnoughPowder = bNotEnoughPowder;
			if (bNotEnoughPowder) 	{ SendMessage(&BattleInterface,"ll",BI_MSG_NOT_ENOUGH_BALLS_FLAG,true); }
			else 					{ SendMessage(&BattleInterface,"ll",BI_MSG_NOT_ENOUGH_BALLS_FLAG,false); }
		}
		else
		{
			if(bNotEnoughBalls != bOldNotEnoughBalls)
			{ 
				bOldNotEnoughBalls = bNotEnoughBalls;
				if(bNotEnoughBalls) { SendMessage(&BattleInterface,"ll",BI_MSG_NOT_ENOUGH_BALLS_FLAG,true); }
				else 				{ SendMessage(&BattleInterface,"ll",BI_MSG_NOT_ENOUGH_BALLS_FLAG,false); }
			}
		}
		// TIH <--

		/* +++ older method which has some ugly issues with it +++
		outOfGunpowder = true;
		if(bNotEnoughBalls!=bOldNotEnoughBalls)
		{
			bOldNotEnoughBalls = bNotEnoughBalls;
			if( ourPwdr>=sti(GetCannonArcCurQty(GetMainCharacter(), 0))*fireGunpowder && ourPwdr>=sti(GetCannonArcCurQty(GetMainCharacter(), 2))*fireGunpowder )
			{
				if(bNotEnoughBalls) SendMessage(&BattleInterface,"ll",BI_MSG_NOT_ENOUGH_BALLS_FLAG,true);
				else SendMessage(&BattleInterface,"ll",BI_MSG_NOT_ENOUGH_BALLS_FLAG,false);
			}
			else outOfGunpowder = true;
		}
		else
		{
			if( ourPwdr>=sti(GetCannonArcCurQty(GetMainCharacter(), 0))*fireGunpowder && ourPwdr>=sti(GetCannonArcCurQty(GetMainCharacter(), 2))*fireGunpowder )
			{
				SendMessage(&BattleInterface,"ll",BI_MSG_NOT_ENOUGH_BALLS_FLAG,false);
				outOfGunpowder = false;
			}
			else
			{
				SendMessage(&BattleInterface,"ll",BI_MSG_NOT_ENOUGH_BALLS_FLAG,true);
				outOfGunpowder = true;
			}
		}
		+++ end of old section +++ */

		// added by MAXIMUS [gunpowder mod] <--
	}
	// TIH <-- mod toggle
	else
	{
		if(bNotEnoughBalls != bOldNotEnoughBalls)
		{
			bOldNotEnoughBalls = bNotEnoughBalls;
			if(bNotEnoughBalls) {
				SendMessage(&BattleInterface,"ll",BI_MSG_NOT_ENOUGH_BALLS_FLAG,true);
			} else {
				SendMessage(&BattleInterface,"ll",BI_MSG_NOT_ENOUGH_BALLS_FLAG,false);
			}
		}
	}

// TIH <-- rewrite

	if(biold_bAbordageShipCanBe!=bAbordageShipCanBe)
	{
		bYesUpdateCommand = true;
		biold_bAbordageShipCanBe = bAbordageShipCanBe;
	}
	if(biold_bAbordageFortCanBe!=bAbordageFortCanBe)
	{
		bYesUpdateCommand = true;
		biold_bAbordageFortCanBe = bAbordageFortCanBe;
	}
	if(biold_bCanEnterToLand!=bCanEnterToLand)
	{
		bYesUpdateCommand = true;
		biold_bCanEnterToLand = bCanEnterToLand;
	}
	if(biold_bReloadCanBe!=bReloadCanBe)
	{
		bYesUpdateCommand = true;
		biold_bReloadCanBe = bReloadCanBe;
	}
	if(biold_bMapEnter!=bMapEnter)
	{
		bYesUpdateCommand = true;
		biold_bMapEnter = bMapEnter;
	}

	if(bYesUpdateCommand)
	{
		BI_SetCommandMode(-1,-1,-1,-1);
		RefreshBattleInterface(); // KK
	}

	Log_SetActiveAction("Nothing"); // KK
	if (bDisableAllCommands) return; // KK

	if(bAbordageShipCanBe)
	{
		Log_SetActiveAction("Board");
		return;
	}
	if(bAbordageFortCanBe)
	{
		Log_SetActiveAction("LandTroops");
		return;
	}
// KK -->
	/*if(bReloadCanBe)
	{
		Log_SetActiveAction("Reload");
		return;
	}*/
// <-- KK
	if(bCanEnterToLand)
	{
		Log_SetActiveAction("Moor");
		return;
	}
	if(bMapEnter)
	{
		Log_SetActiveAction("Map");
		return;
	}
}

void StartBattleInterface()
{
	bi_nReloadTarget = -1;
	bi_icons_ShowType = BI_ICONS_ST_MYSHIPS;
	BI_SetCommandMode(BI_COMMODE_MY_SHIP_SELECT,-1,-1,-1);
	BI_SetIslandData();
	InterfaceSpyGlassInit();
	objShipPointer.textures.friend = "battle_interface\Frendly.tga";
	objShipPointer.textures.enemy = "battle_interface\Enemy.tga";
	CreateEntity(&objShipPointer,"shippointer");
	LayerAddObject(SEA_EXECUTE,&objShipPointer,222222);
	LayerAddObject(SEA_REALIZE,&objShipPointer,222222);
}

void RefreshBattleInterface()
{
	BI_SetCommandMode(0,-1,-1,-1);
// KK -->
	int i;
	ref PChar = GetMainCharacter();
	for (i = 0; i < iNumShips; i++) {
		if (SeaAI_GetRelation(Ships[i], sti(PChar.index)) != RELATION_ENEMY)
			SetCharacterRelationBoth(sti(PChar.index), Ships[i], GetNationRelation(sti(PChar.nation), sti(characters[Ships[i]].nation)));
	}
	if (CheckAttribute(PChar, "seaAI.update.forts")) {
		aref fortattr; makearef(fortattr, PChar.seaAI.update.forts);
		int num = GetAttributesNum(fortattr);
		for (i = 0; i < num; i++) {
			string fortstr = "l" + i;
			int fortidx = sti(fortattr.(fortstr).idx);
			if (fortidx == -1) continue;
			if (SeaAI_GetRelation(fortidx, sti(PChar.index)) != RELATION_ENEMY) {
				SetCharacterRelationBoth(sti(PChar.index), fortidx, GetNationRelation(sti(PChar.nation), sti(characters[fortidx].nation)));
				fortattr.(fortstr).relation = GetNationRelation(sti(PChar.nation), sti(characters[fortidx].nation));
				string sfortidx = fortidx;
				PChar.relation.(sfortidx) = fortattr.(fortstr).relation;
				UpdateRelations();
			}
		}
	}
	UpdateRelations();
// <-- KK
	SendMessage(&BattleInterface,"l",BI_MSG_REFRESH);
	BI_SetCommandMode(BI_COMMODE_MY_SHIP_SELECT,-1,-1,-1);
}

void DeleteBattleInterface()
{
	Log_SetActiveAction("Nothing");
	InterfaceSpyGlassRelease();

	DelEventHandler(SHIP_DELETE, "BI_DeleteShip");
	DelEventHandler(SHIP_DEAD,"BI_DeadShip");
	DelEventHandler("BI_CommandEndChecking", "BI_CommandEndChecking");
	DelEventHandler("BI_LaunchCommand", "BI_LaunchCommand");
	DelEventHandler("BI_GetChargeQuantity","BI_GetChargeQuantity");
	DelEventHandler("BI_SetPossibleCommands","BI_SetPossibleCommands");
	DelEventHandler("GetCurrentCharge","GetCurrentCharge");
	DelEventHandler(BI_EVENT_SET_VISIBLE,"BI_CommandVisible");
	DelEventHandler(BI_EVENT_SET_SEA_STATE,"BI_SetSeaState");
	DelEventHandler(BI_EVENT_GET_DATA,"BI_GetData");
	DelEventHandler(BI_EVENT_CHECK_SHIPSTATE_SHOW,"BI_GetSSShow");
	DelEventHandler("evntGetLandData","BI_GetLandData");
	DelEventHandler(BI_EVENT_GET_FORT_RELATION,"BI_GetFortRelation");
	DelEventHandler(EVENT_CHANGE_COMPANIONS,"RefreshBattleInterface");
	DelEventHandler("BI_CallUpdateShip","BI_UpdateShip");
	DelEventHandler("frame","BI_Frame");
	DelEventHandler("evntPerkAgainUsable","BI_PerkAgainUsable");
	DelEventHandler("evntSetUsingAbility","procSetUsingAbility");
	DelEventHandler("evntCheckEnableLocator","procCheckEnableLocator");
	DelEventHandler("evntCheckEnableShip","procCheckEnableShip");
	DelEventHandler("evntGetSRollSpeed","procGetSRollSpeed");
	DelEventHandler("Control Activation","BI_ProcessControlPress");
	// NK basetime 05-04-25 -->
	ref PChar = GetMainCharacter();
	float basetime = 1.0;
	if(CheckAttribute(PChar,"basetime")) basetime = stf(PChar.basetime);

	// LDH clean up after time display 17Sep06
	if (DISPLAY_SEA_TIME || CheckCharacterEquipByGroup(PChar, CLOCK_ITEM_TYPE) != "") // PB: Clocks
	{
		DeleteAttribute(PChar,"CurrentTime");
		DeleteAttribute(PChar,"BaseCurrentTime");
		DeleteAttribute(PChar,"TimeSeconds");
		ClearAllLogStrings();	// get rid of Eternal Log String
	}

	SetTimeScale(1.0 * basetime);
	// NK <--
	if(IsPerkIntoList("TimeSpeed"))
	{	DelPerkFromActiveList("TimeSpeed");
	}

	bDisableAllCommands = false; // KK

	DeleteClass(&BattleInterface);
	DeleteClass(&objShipPointer);
}

ref BI_CommandEndChecking()
{
	BI_retComValue = 0;
	string comName = GetEventData();

	switch(comName)
	{
		// Hoist Flag MOD -Amokachi
		case "BI_HoistFlag":
			BI_retComValue = 0;
		break;
// KK -->
// KAM, MAXIMUS -->
		case "BI_EnterDeck":
			SetUserIcons(comName);
			BI_retComValue = BI_COMMODE_USER_ICONS;
		break;
		case "BI_EnterTartaneDeck":
			BI_retComValue = 0;
		break;
// <-- KAM, MAXIMUS
		case "BI_Port":
			BI_retComValue = 0;
		break;
		case "BI_Shore":
			BI_retComValue = 0;
		break;
// <-- KK
		case "BI_Moor":
			BI_retComValue = 0;
		break;
		case "BI_SailTo":
			if(bEnableIslandSailTo) {
				BI_retComValue = BI_COMMODE_MY_SHIP_SELECT+BI_COMMODE_NEUTRAL_SHIP_SELECT+BI_COMMODE_FRIEND_SHIP_SELECT+BI_COMMODE_ENEMY_SHIP_SELECT+BI_COMMODE_FRIEND_FORT_SELECT+BI_COMMODE_NEUTRAL_FORT_SELECT+BI_COMMODE_ENEMY_FORT_SELECT+BI_COMMODE_LAND_SELECT+BI_COMMODE_ALLLOCATOR_SELECT;
				BattleInterface.Commands.SailTo.EffectRadius	= -1.0;
			} else {
				BI_retComValue = BI_COMMODE_MY_SHIP_SELECT+BI_COMMODE_NEUTRAL_SHIP_SELECT+BI_COMMODE_FRIEND_SHIP_SELECT+BI_COMMODE_ENEMY_SHIP_SELECT+BI_COMMODE_ALLLOCATOR_SELECT;
				BattleInterface.Commands.SailTo.EffectRadius	= MIN_ENEMY_DISTANCE_TO_DISABLE_MAP_ENTER;
			}
		break;
		case "BI_Board":
			BI_retComValue = 0;
		break;
		case "BI_LandTroops":
			BI_retComValue = 0;
		break;
// KK -->
		case "BI_AttackTown":
			BI_retComValue = 0;
		break;
// <-- KK
		case "BI_Map":
			BI_retComValue = 0;
		break;
		case "BI_Attack":
			BI_retComValue = BI_COMMODE_ENEMY_SHIP_SELECT+BI_COMMODE_ENEMY_FORT_SELECT+BI_COMMODE_ALLLOCATOR_SELECT;
		break;
		case "BI_Defend":
			BI_retComValue = BI_COMMODE_MY_SHIP_SELECT+BI_COMMODE_FRIEND_SHIP_SELECT+BI_COMMODE_FRIEND_FORT_SELECT+BI_COMMODE_ALLLOCATOR_SELECT;
		break;
		case "BI_SailAway":
			BI_retComValue = 0;
		break;
		case "BI_HeaveToDrift":
			BI_retComValue = 0;
		break;
		case "BI_Reload":
			BI_retComValue = 0;
		break;
		case "BI_Charge":
			BI_retComValue = BI_COMMODE_CANNON_CHARGE;
		break;
		case "BI_Speed":
			SetUserIcons(comName); // KK
			BI_retComValue = BI_COMMODE_USER_ICONS;
		break;
		case "BI_CompanionCommand":
			BI_retComValue = BI_COMMODE_MY_SHIP_SELECT+BI_COMMODE_ALLLOCATOR_SELECT;
		break;
		case "BI_Brander":
			BI_retComValue = BI_COMMODE_ENEMY_SHIP_SELECT+BI_COMMODE_ALLLOCATOR_SELECT;
		break;
		case "BI_ImmediateReload":
			BI_retComValue = 0;
		break;
		case "BI_InstantBoarding":
			BI_retComValue = BI_COMMODE_ENEMY_SHIP_SELECT+BI_COMMODE_ALLLOCATOR_SELECT;
		break;
		case "BI_LightRepair":
			BI_retComValue = 0;
		break;
		case "BI_InstantRepair":
			BI_retComValue = 0;
		break;
		case "BI_Turn180":
			BI_retComValue = 0;
		break;
		case "BI_SandbankManeuver":
			BI_retComValue = 0;
		break;
		case "BI_Troopers":
			BI_retComValue = BI_COMMODE_ENEMY_FORT_SELECT+BI_COMMODE_ALLLOCATOR_SELECT;
		break;
		case "BI_Ability":
			BI_retComValue = BI_COMMODE_ABILITY_ICONS;
		break;
		case "BI_ImmDeath":
			BI_retComValue = BI_COMMODE_ENEMY_SHIP_SELECT+BI_COMMODE_ENEMY_FORT_SELECT+BI_COMMODE_ALLLOCATOR_SELECT;
		break;
	}

	return &BI_retComValue;
}

void BI_LaunchCommand()
{
	//int tmpLangFileID = LanguageOpenFile("interface_strings.txt");
	int charIdx = GetEventData();
	string commandName = GetEventData();
	int targetNum = GetEventData();
	string locName = GetEventData();
	ref chRef = GetCharacter(charIdx);
	ref mainChr = GetMainCharacter();
	int cc; // KK

	if( LAi_IsDead(chRef) ) return;

	if(targetNum==-1 && locName=="cancel") commandName = "";

	string alternativeCommand;
	if( CheckAttribute( &BattleInterface, "AbilityIcons."+commandName+".quest" ) )
	{
		alternativeCommand = commandName;
		commandName = "BI_UseItemAbilitie";
	}

	switch(commandName)
	{
	// Hoist Flag MOD -Amokachi
	case "BI_HoistFlag":
		// --> Hoist the flag code fix by Mad-h
		if(!CheckAttribute(mainChr,"franciarel"))	// ccc jan 06, only initial relations are stored 
		{
			mainChr.franciarel = GetRMRelation(mainChr,FRANCE);	// ccc dec 05
			mainChr.spanyolrel = GetRMRelation(mainChr,SPAIN);	// ccc dec 05
			mainChr.portugalrel = GetRMRelation(mainChr,PORTUGAL);	// ccc dec 05
			mainChr.hollandrel = GetRMRelation(mainChr,HOLLAND);		// ccc dec 05
			mainChr.angolrel = GetRMRelation(mainChr,ENGLAND);	// ccc dec 05
			mainChr.pirarel = GetRMRelation(mainChr,PIRATE);	// ccc dec 05
		}

		// store old playernation
		mainChr.orgnation = mainChr.nation;	// ccc dec 05

		// become an evil pirate
		mainChr.nation = PIRATE;
		for(cc = 1; cc < 4; cc++)
		{
			int compIdx = GetCompanionIndex(mainChr, cc); // added by MAXIMUS [checking, if you have companions]
			if(compIdx<0) continue; // added by MAXIMUS [checking, if you have companions]
			if(GetRemovable(GetCharacter(GetCompanionIndex(mainChr, cc))))
			{
				Characters[GetCompanionIndex(mainChr, cc)].nation = mainChr.nation;
			}
		} // NK so comps' nations update
// KK -->
		if (ENABLE_FLAGS == 0) {
			// hostile all nations, ally pirates
			if(GetRMRelation(mainChr, PIRATE) < REL_AMNESTY) SetRMRelation(mainChr, PIRATE, REL_AMNESTY);
			SetRMRelation(mainChr, ENGLAND, REL_WAR);	// ccc dec 05
			SetRMRelation(mainChr, FRANCE, REL_WAR);	// ccc dec 05
			SetRMRelation(mainChr, SPAIN, REL_WAR);	// ccc dec 05
			SetRMRelation(mainChr, PORTUGAL, REL_WAR);	// ccc dec 05
			SetRMRelation(mainChr, HOLLAND, REL_WAR);		// ccc dec 05

			UpdateRelations();
			RefreshBattleInterface();
		} else {
			HoistFlag(PIRATE);
			SetRelationsForFlag(PIRATE);
		}
// <-- KK
		PlaySound("OBJECTS\abordage\abordage_wining.wav");		// ccc dec 05
		Log_SetStringToLog(TranslateString("","You have hoisted a Pirate flag! Argh!"));
		// <-- Hoist the flag code fix by Mad-h
	break;
// KK -->
	case "BI_EnterDeck":
		switch (locName) {
			case "ShipDeck":
				Sea_DeckStartNow(GetCharacterShipQDeck(mainChr));
			break;
			case "Cabin":
				Sea_CabinStartNow();
			break;
			// default:
				Sea_DeckStartNow(locName);
		}
	break;
	case "BI_EnterTartaneDeck":
		Sea_DeckStartNow("ShipDeck1");
	break;
	case "BI_Port":
		bDisableAllCommands = true;
		PostEvent("BI_SetPossibleCommands", 0, "l", -1);
		Sea_ImmediateLandLoad();
	break;
	case "BI_Shore":
		bDisableAllCommands = true;
		PostEvent("BI_SetPossibleCommands", 0, "l", -1);
		Sea_ImmediateLandLoad();
	break;
// <-- KK
	case "BI_Charge":
		int chargeType = -1; // KK
		if (GetCurrentCharge() == 4) break; // KK
		switch(targetNum)
		{
			case 1:
				if (GetCurrentCharge() == 2) break; // KK
				Log_SetStringToLog(XI_ConvertString("Balls"));
				chargeType=GOOD_BALLS;
			break;
			case 2:
				if (GetCurrentCharge() == 3) break; // KK
				Log_SetStringToLog(XI_ConvertString("Grapes"));
				chargeType=GOOD_GRAPES;
			break;
			case 3:
				if (GetCurrentCharge() == 0) break; // KK
				Log_SetStringToLog(XI_ConvertString("Knippels"));
				chargeType=GOOD_KNIPPELS;
			break;
			case 4:
				if (GetCurrentCharge() == 1) break; // KK
				Log_SetStringToLog(XI_ConvertString("Bombs"));
				chargeType=GOOD_BOMBS;
			break;
		}
		Ship_ChangeCharge(chRef, chargeType);
	break;
	case "BI_Map":
		Sea_MapLoad();
	break;
	case "BI_Moor":
// KK -->
		bDisableAllCommands = true;
		PostEvent("BI_SetPossibleCommands", 0, "l", -1);
// <-- KK
		Sea_LandLoad();
	break;
	case "BI_Board":
		Sea_AbordageLoad(SHIP_ABORDAGE,true);
	break;
	case "BI_LandTroops":
		Sea_AbordageLoad(FORT_ABORDAGE, true);
	break;
// KK -->
	case "BI_AttackTown":
		Sea_AbordageLoad(TOWN_ABORDAGE, true);
	break;
// <-- KK
	case "BI_SailAway":
		Ship_SetTaskRunAway(SECONDARY_TASK,charIdx);
	break;
	case "BI_HeaveToDrift":
		Ship_SetTaskDrift(SECONDARY_TASK,charIdx);
	break;
	case "BI_Defend":
		Ship_SetTaskDefend(SECONDARY_TASK,charIdx,GetTargChrIndex(targetNum,locName));
	break;
	case "BI_Attack":
		Ship_SetTaskAttack(SECONDARY_TASK,charIdx,GetTargChrIndex(targetNum,locName));
	break;
	case "BI_Reload":
		if(bi_nReloadTarget!=-1)
		{
			mainChr.shiptransferinterface.calledfrominterface = 0; // NK 05-04-14 to reset back to off.
			LaunchTransferMain(chRef,GetCharacter(bi_nReloadTarget),"");
		}
	break;
	case "BI_SailTo":
		if(targetNum==-1)
		{ // приплыть в локатор с именем locName
			SeaAI_SailToLocator(locName);
		}
		else
		{ // догнать перса с индексом targetNum
			SeaAI_SailToCharacter(targetNum);
		}
	break;
	case "BI_Speed":
		switch(locName)
		{
		case "sail_none":
			Ship_SetSailState(charIdx,0.0);
		break;
		case "sail_midi":
			Ship_SetSailState(charIdx,0.5);
		break;
		case "sail_fast":
			Ship_SetSailState(charIdx,1.0);
		break;
		}
	break;
	case "BI_CompanionCommand":
		BI_SetSpecCommandMode(BI_COMMODE_COMMAND_SELECT,-1,-1,targetNum,1);
		return;
	break;
	case "BI_ImmDeath":
		if(targetNum==-1)
		{ // смерть форта
			targetNum = Fort_FindCharacter(AISea.Island,"reload",locName);
			if(targetNum>=0)
			{
				Fort_SetAbordageMode(GetMainCharacter(), GetCharacter(targetNum));
			}
		}
		else
		{
			ShipDead(targetNum,KILL_BY_BALL,GetMainCharacterIndex());
		}
	break;
	case "BI_Brander":
		ActivateCharacterPerk(GetMainCharacter(),"Brander");
		Ship_SetTaskBrander(SECONDARY_TASK, charIdx, targetNum);
	break;
	case "BI_ImmediateReload":
		ActivateCharacterPerk(GetCharacter(charIdx),"ImmediateReload");
	break;
	case "BI_InstantBoarding":
		ActivateCharacterPerk(GetCharacter(charIdx),"InstantBoarding");
		CharacterPerkOff(GetCharacter(charIdx),"InstantBoarding");
		if(CheckSuccesfullBoard(GetCharacter(charIdx),GetCharacter(targetNum))) {
			Sea_AbordageStartNow(SHIP_ABORDAGE,targetNum,true,true);
		} else {
			Log_SetStringToLog( XI_ConvertString("failed to board") );
			Event("BI_LaunchCommand","lsls", charIdx, "BI_SailTo", targetNum, locName);
			return;
		}
	break;
	case "BI_LightRepair":
		ActivateCharacterPerk(GetCharacter(charIdx),"LightRepair");
		ActivateSpecRepair(GetCharacter(charIdx),0);
	break;
	case "BI_InstantRepair":
		ActivateCharacterPerk(GetCharacter(charIdx),"InstantRepair");
		ActivateSpecRepair(GetCharacter(charIdx),1);
	break;
	case "BI_Turn180":
		ActivateCharacterPerk(GetCharacter(charIdx),"Turn180");
		Ship_Turn180(GetCharacter(charIdx));
	break;
	case "BI_SandbankManeuver":
		ActivateCharacterPerk(GetCharacter(charIdx),"SandbankManeuver");
	break;
	case "BI_Troopers":
		ActivateCharacterPerk(GetMainCharacter(),"Troopers");
	break;
	// items abilities
	case "BI_UseItemAbilitie":
		CompleteQuestName( BattleInterface.AbilityIcons.(alternativeCommand).quest );
	break;
	}

	BI_SetCommandMode(BI_COMMODE_MY_SHIP_SELECT,-1,-1,-1);
//	LanguageCloseFile(tmpLangFileID);
}

void BI_SetIslandData()
{
	if(!CheckAttribute(AISea,"Island")) return;
	int isln = FindIsland(AISea.Island);
	if(isln==-1) return;

	ref atmp;
	atmp = GetIslandByIndex(isln);
	SendMessage(&BattleInterface,"la",BI_MSG_SET_ISLAND,atmp);
}

void BI_UpdateShip()
{
	int charIndex = GetEventData();
	AddShipToInterface(charIndex);
}

void BI_CreateShip()
{
	int charIndex = GetEventData();
	if(charIndex>=0) ClearActiveChrPerks(GetCharacter(charIndex));
	if( IsEntity(&BattleInterface) ) {
		AddShipToInterface(charIndex);
	}
}

void AddShipToInterface(int charIndex)
{
	if(charIndex==-1)
	{
		Trace("ERROR: Invalid character index for create ship");
		return;
	}
	ref chRef = GetCharacter(charIndex);
	int st = GetCharacterShipType(chRef);
	if( st==SHIP_NOTUSED )
	{
		Trace("WARNING!!! Character id = "+chRef.id+" hav`t ship.");
		return;
	}

// LDH -->
	if (CheckAttribute(chRef, "NeedSailDmg"))
	{
		float fDamage = stf(chRef.NeedSailDmg);
		DeleteAttribute(chRef, "NeedSailDmg");
		MakeSailDmg(charIndex, fDamage);	// this applies the damage to SP and makes holes in the sails, moved from AIShip.c
	}
// LDH <--

	// NK 05-04-15 PRS3 data bars
	ref realshipRef = GetShipByType(st);
	ref PChar = GetMainCharacter(); // KK
	int idx, i;
	if(CheckAttribute(chRef,"curshipnum")) {
		idx = sti(chRef.curshipnum);
	}
	else
	{
		for(i = 0; i < MAX_SHIPS_ON_SEA; i++)
		{
			if(Ships[i] == charIndex)
			{
				idx = i;
				chRef.curshipnum = i;
			}
		}
	}
// KK -->
	if (idx < 0) {
		for(i = 0; i < 4; i++)
		{
			if (GetCompanionIndex(PChar, i) >= 0 && GetRemovable(GetCharacter(GetCompanionIndex(PChar, i))))
			{
				if (GetCompanionIndex(PChar, i) == charIndex) {
					idx = i;
					chRef.curshipnum = i;
				}
			}
		}
	}
// <-- KK
	ref shipRef = &ShipStats[idx];
	DeleteAttribute(shipRef,""); // clear out
	aref arshipstats; makearef(arshipstats, chRef.ship.stats);
	CopyAttributes(&shipRef, &realshipRef); // copy base ship over.
	/*trace("*****************************for character " + chRef.id + " with curshipnum " + idx + " we will now dump stats before apply local.");
	DumpAttributes(shipRef);*/
	string tat;
	for(i = 0; i < GetAttributesNum(arshipstats); i++) // overwrite with local stats if exist.
	{
		tat = GetAttributeName(GetAttributeN(arshipstats, i));
		shipRef.(tat) = GetAttributeValue(GetAttributeN(arshipstats, i));
	}
	/*trace("***************And after:");
	DumpAttributes(shipRef);*/
	// NK <--
	int myShip = false;
	int shipRelation = BI_RELATION_NEUTRAL;
	switch( SeaAI_GetRelation(charIndex,GetMainCharacterIndex()) )
	{
	case RELATION_FRIEND:
		shipRelation = BI_RELATION_FRIEND;
		break;
	case RELATION_ENEMY:
		shipRelation = BI_RELATION_ENEMY;
		break;
	}
	// TIH --> new hotwire fix for minimap colors (shows surrenders as grey now properly) Aug24'06
	if ( Characters[charIndex].nation == NEUTRAL_NATION ) { shipRelation = BI_RELATION_NEUTRAL; }
	// TIH <--

	ref mainChRef = GetMainCharacter();
	for(i=0; i<4; i++) // NK i declared above. 05-04-15
	{
		if(GetCompanionIndex(mainChRef,i) == charIndex)
		{
			myShip = true;
		}
	}

	if( CharacterIsDead(chRef) )
	{
		if( !CheckAttribute(chRef,"ship.shipsink") || sti(chRef.ship.shipsink)==false )
			return;
	}

	SendMessage(&BattleInterface,"llaall",BI_IN_CREATE_SHIP,charIndex,chRef,shipRef,myShip,shipRelation);
}

void BI_DeleteShip()
{
	int charIndex = GetEventData();
	if(charIndex==-1)
	{
		Trace("ERROR: Invalid character index");
		return;
	}
	if( IsCompanion(GetCharacter(charIndex)) )
	{
		RemoveCharacterCompanion(GetMainCharacter(),GetCharacter(charIndex));
	}
	DeleteAttribute(GetCharacter(charIndex),"ship.shipsink");
	DeleteAttribute(GetCharacter(charIndex),"curshipnum"); // NK 05-04-15 used in addshiptointerface
	RefreshBattleInterface();
}

void BI_DeadShip()
{
	int charIndex = GetEventData();
	if(charIndex==-1)
	{
		Trace("ERROR: Invalid character index");
		return;
	}
	if( IsCompanion(GetCharacter(charIndex)) )
	{
		RemoveCharacterCompanion(GetMainCharacter(),GetCharacter(charIndex));
	}
	Characters[charIndex].ship.shipsink = true;
	RefreshBattleInterface();
}

void BI_SetCommandMode(int commode, int texNum, int picNum, int chIdx)
{
	bi_icons_CommandMode = commode;
	SendMessage(&BattleInterface,"llllll",BI_IN_SET_COMMAND_MODE,commode,texNum,picNum,chIdx,-1);
}

void BI_SetSpecCommandMode(int commode, int texNum, int picNum, int chIdx, int comState)
{
	bi_icons_CommandMode = commode;
	SendMessage(&BattleInterface,"llllll",BI_IN_SET_COMMAND_MODE,commode,texNum,picNum,chIdx,comState);
}

void BI_SetPossibleCommands()
{
	int chIdx = GetEventData();
	ref mainCh = GetMainCharacter();
	int mainIdx = sti(mainCh.index);

	if( chIdx<0 || CharacterIsDead(GetCharacter(chIdx)) || bDisableAllCommands==true) // KK
	{
		aref aroot,arcur;
		makearef(aroot,BattleInterface.Commands);
		int q = GetAttributesNum(aroot);
		for(int i=0; i<q; i++)
		{
			arcur = GetAttributeN(aroot,i);
			arcur.enable = false;
		}
		BattleInterface.Commands.Cancel.enable = true;
		return;
	}

	// для главного персонажа
	if(mainIdx==chIdx)
	{
		BattleInterface.Commands.Moor.enable			= bCanEnterToLand;
		string DestinationType = ""; // MAXIMUS
		if(bCanEnterToLand) DestinationType = CheckDestinationType(); // KK // MAXIMUS
		BattleInterface.Commands.LandPort.enable		= VISIT_DECK == 1 && bCanEnterToLand == true && DestinationType != "seashore"; // KK
		BattleInterface.Commands.LandShore.enable		= VISIT_DECK == 1 && bCanEnterToLand == true && DestinationType == "seashore"; // KK
		BattleInterface.Commands.Board.enable			= bAbordageShipCanBe;
		BattleInterface.Commands.SailAway.enable		= false;
		BattleInterface.Commands.HeaveToDrift.enable	= false;
		BattleInterface.Commands.Charge.enable			= CheckAttribute(mainCh,"Ship.Cannons.Charge.Type") && GetCaracterShipCannonsType(mainCh) != CANNON_TYPE_NONECANNON; // KK
		BattleInterface.Commands.LandTroops.enable		= bAbordageFortCanBe;
		BattleInterface.Commands.AttackTown.enable		= bAbordageTownCanBe; // KK
		BattleInterface.Commands.Attack.enable			= false;
		BattleInterface.Commands.Defend.enable			= false;
		BattleInterface.Commands.Reload.enable			= bReloadCanBe;
		BattleInterface.Commands.SailTo.enable			= !bDisableSailTo && bSailTo;
		BattleInterface.Commands.Map.enable				= bMapEnter;
// KK -->
		if (GetCharacterShipCabin(GetCharacter(chIdx)) != "Cabin_none")
			BattleInterface.Commands.EnterDeck.enable = bMapEnter;
		else
			BattleInterface.Commands.EnterTartaneDeck.enable = bMapEnter;
// <-- KK
		BattleInterface.Commands.Speed.enable			= true;
		BattleInterface.Commands.CCommand.enable		= GetCompanionQuantity(mainCh)>1;
		BattleInterface.Commands.Ability.enable			= true;
	}
	// для спутников
	else
	{
		BattleInterface.Commands.Moor.enable			= false;
		BattleInterface.Commands.LandPort.enable		= false; // KK
		BattleInterface.Commands.LandShore.enable		= false; // KK
		BattleInterface.Commands.Board.enable			= false;
		BattleInterface.Commands.SailAway.enable		= true;
		BattleInterface.Commands.HeaveToDrift.enable	= true;
		BattleInterface.Commands.Charge.enable			= false;
		BattleInterface.Commands.LandTroops.enable		= false;
		BattleInterface.Commands.AttackTown.enable		= false; // KK
		BattleInterface.Commands.Attack.enable			= bAttack;
		BattleInterface.Commands.Defend.enable			= bDefend;
		BattleInterface.Commands.Reload.enable			= false;
		BattleInterface.Commands.SailTo.enable			= false;
		BattleInterface.Commands.Map.enable				= false;
// KAM, MAXIMUS Deck -->
// KK -->
		BattleInterface.Commands.EnterDeck.enable	= false;
		BattleInterface.Commands.EnterTartaneDeck.enable = false;
// <-- KK
// KAM, MAXIMUS Deck <--
		BattleInterface.Commands.Speed.enable			= false;
		BattleInterface.Commands.CCommand.enable		= false;
		BattleInterface.Commands.Ability.enable			= true;
	}
}

void BI_InitializeCommands()
{
	int idLngFile = LanguageOpenFile("commands_name.txt");

// KK -->
	BattleInterface.Commands.Cancel.enable			= false;
	BattleInterface.Commands.Cancel.picNum			= 0;
	BattleInterface.Commands.Cancel.event			= "Cancel";
	BattleInterface.Commands.Cancel.note			= LanguageConvertString(idLngFile, "sea_Cancel");
	BattleInterface.Commands.Moor.enable			= false;
	BattleInterface.Commands.Moor.picNum			= 1;
	BattleInterface.Commands.Moor.event				= "BI_Moor";
	BattleInterface.Commands.Moor.note				= LanguageConvertString(idLngFile, "sea_Moor");
	BattleInterface.Commands.LandPort.enable			= false;
	BattleInterface.Commands.LandPort.texNum			= 12;
	BattleInterface.Commands.LandPort.event				= "BI_Port";
	BattleInterface.Commands.LandPort.note				= LanguageConvertString(idLngFile, "sea_Port");
	BattleInterface.Commands.LandShore.enable			= false;
	BattleInterface.Commands.LandShore.picNum			= 1;
	BattleInterface.Commands.LandShore.texNum			= 12;
	BattleInterface.Commands.LandShore.event			= "BI_Shore";
	BattleInterface.Commands.LandShore.note				= LanguageConvertString(idLngFile, "sea_Shore");
	BattleInterface.Commands.Board.enable			= false;
	BattleInterface.Commands.Board.picNum			= 2;
	BattleInterface.Commands.Board.event			= "BI_Board";
	BattleInterface.Commands.Board.note				= LanguageConvertString(idLngFile, "sea_Board");
	BattleInterface.Commands.SailTo.enable			= false;
	BattleInterface.Commands.SailTo.picNum			= 3;
	BattleInterface.Commands.SailTo.event			= "BI_SailTo";
	BattleInterface.Commands.SailTo.note			= LanguageConvertString(idLngFile, "sea_SailTo");
	BattleInterface.Commands.LandTroops.enable		= false;
	BattleInterface.Commands.LandTroops.picNum		= 4;
	BattleInterface.Commands.LandTroops.event		= "BI_LandTroops";
	BattleInterface.Commands.LandTroops.note		= LanguageConvertString(idLngFile, "sea_LandTroops");
// KK -->
	BattleInterface.Commands.AttackTown.enable		= false;
	BattleInterface.Commands.AttackTown.picNum		= 4;
	BattleInterface.Commands.AttackTown.texNum		= 6;
	BattleInterface.Commands.AttackTown.event		= "BI_AttackTown";
	BattleInterface.Commands.AttackTown.note		= LanguageConvertString(idLngFile, "sea_LandTroops");
// <-- KK
	BattleInterface.Commands.Map.enable				= false;
	BattleInterface.Commands.Map.picNum				= 5;
	BattleInterface.Commands.Map.event				= "BI_Map";
	BattleInterface.Commands.Map.note				= LanguageConvertString(idLngFile, "sea_Map");

	BattleInterface.Commands.Attack.enable			= false;
	BattleInterface.Commands.Attack.picNum			= 7;
	BattleInterface.Commands.Attack.event			= "BI_Attack";
	BattleInterface.Commands.Attack.note			= LanguageConvertString(idLngFile, "sea_Attack");
	BattleInterface.Commands.Defend.enable			= false;
	BattleInterface.Commands.Defend.picNum			= 8;
	BattleInterface.Commands.Defend.event			= "BI_Defend";
	BattleInterface.Commands.Defend.note			= LanguageConvertString(idLngFile, "sea_Defend");
	BattleInterface.Commands.SailAway.enable		= false;
	BattleInterface.Commands.SailAway.picNum		= 9;
	BattleInterface.Commands.SailAway.event			= "BI_SailAway";
	BattleInterface.Commands.SailAway.note			= LanguageConvertString(idLngFile, "sea_SailAway");
	BattleInterface.Commands.HeaveToDrift.enable	= false;
	BattleInterface.Commands.HeaveToDrift.picNum	= 10;
	BattleInterface.Commands.HeaveToDrift.event		= "BI_HeaveToDrift";
	BattleInterface.Commands.HeaveToDrift.note		= LanguageConvertString(idLngFile, "sea_HeaveToDrift");
	BattleInterface.Commands.CCommand.enable		= false;
	BattleInterface.Commands.CCommand.picNum		= 14;
	BattleInterface.Commands.CCommand.event			= "BI_CompanionCommand";
	BattleInterface.Commands.CCommand.note			= LanguageConvertString(idLngFile, "sea_CCommand");
	BattleInterface.Commands.Ability.enable			= false;
	BattleInterface.Commands.Ability.picNum			= 13;
	BattleInterface.Commands.Ability.event			= "BI_Ability";
	BattleInterface.Commands.Ability.note			= LanguageConvertString(idLngFile, "sea_Ability");
	BattleInterface.Commands.Reload.enable			= false;
	BattleInterface.Commands.Reload.picNum			= 6;
	BattleInterface.Commands.Reload.event			= "BI_Reload";
	BattleInterface.Commands.Reload.note			= LanguageConvertString(idLngFile, "sea_Reload");
	BattleInterface.Commands.Charge.enable			= false;
	BattleInterface.Commands.Charge.picNum			= 11;
	BattleInterface.Commands.Charge.event			= "BI_Charge";
	BattleInterface.Commands.Charge.note			= LanguageConvertString(idLngFile, "sea_Charge");
	BattleInterface.Commands.Speed.enable			= false;
	BattleInterface.Commands.Speed.picNum			= 12;
	BattleInterface.Commands.Speed.event			= "BI_Speed";
	BattleInterface.Commands.Speed.note				= LanguageConvertString(idLngFile, "sea_Speed");
	BattleInterface.Commands.ImmediateDeath.enable	= false;
	BattleInterface.Commands.ImmediateDeath.picNum	= 0;
	BattleInterface.Commands.ImmediateDeath.event	= "BI_ImmDeath";
	BattleInterface.Commands.ImmediateDeath.texNum	= 7;
	BattleInterface.Commands.ImmediateDeath.note	= LanguageConvertString(idLngFile, "sea_ImmediateDeath");

	BattleInterface.AbilityIcons.Brander.enable			= false;
	BattleInterface.AbilityIcons.Brander.picNum			= 0;
	BattleInterface.AbilityIcons.Brander.texNum			= 6;
	BattleInterface.AbilityIcons.Brander.event			= "BI_Brander";
	BattleInterface.AbilityIcons.ImmediateReload.enable			= false;
	BattleInterface.AbilityIcons.ImmediateReload.picNum			= 6;
	BattleInterface.AbilityIcons.ImmediateReload.texNum			= 6;
	BattleInterface.AbilityIcons.ImmediateReload.event			= "BI_ImmediateReload";
	BattleInterface.AbilityIcons.InstantBoarding.enable			= false;
	BattleInterface.AbilityIcons.InstantBoarding.picNum			= 7;
	BattleInterface.AbilityIcons.InstantBoarding.texNum			= 6;
	BattleInterface.AbilityIcons.InstantBoarding.event			= "BI_InstantBoarding";
	BattleInterface.AbilityIcons.LightRepair.enable			= false;
	BattleInterface.AbilityIcons.LightRepair.picNum			= 5;
	BattleInterface.AbilityIcons.LightRepair.texNum			= 6;
	BattleInterface.AbilityIcons.LightRepair.event			= "BI_LightRepair";
	BattleInterface.AbilityIcons.InstantRepair.enable		= false;
	BattleInterface.AbilityIcons.InstantRepair.picNum		= 1;
	BattleInterface.AbilityIcons.InstantRepair.texNum		= 6;
	BattleInterface.AbilityIcons.InstantRepair.event		= "BI_InstantRepair";
	BattleInterface.AbilityIcons.Turn180.enable				= false;
	BattleInterface.AbilityIcons.Turn180.picNum				= 2;
	BattleInterface.AbilityIcons.Turn180.texNum				= 6;
	BattleInterface.AbilityIcons.Turn180.event				= "BI_Turn180";
	BattleInterface.AbilityIcons.SandbankManeuver.enable	= false;
	BattleInterface.AbilityIcons.SandbankManeuver.picNum	= 3;
	BattleInterface.AbilityIcons.SandbankManeuver.texNum	= 6;
	BattleInterface.AbilityIcons.SandbankManeuver.event		= "BI_SandbankManeuver";
	BattleInterface.AbilityIcons.Troopers.enable			= false;
	BattleInterface.AbilityIcons.Troopers.picNum			= 4;
	BattleInterface.AbilityIcons.Troopers.texNum			= 6;
	BattleInterface.AbilityIcons.Troopers.event				= "BI_Troopers";

// MAXIMUS Deck -->
// KK -->
	BattleInterface.Commands.EnterDeck.enable		= false;
	BattleInterface.Commands.EnterDeck.picNum		= 5;
	BattleInterface.Commands.EnterDeck.texNum		= 12;
	BattleInterface.Commands.EnterDeck.event		= "BI_EnterDeck";
	BattleInterface.Commands.EnterDeck.note			= LanguageConvertString(idLngFile, "sea_EnterDeck");

	BattleInterface.Commands.EnterTartaneDeck.enable	= false;
	BattleInterface.Commands.EnterTartaneDeck.picNum	= 5;
	BattleInterface.Commands.EnterTartaneDeck.texNum	= 12;
	BattleInterface.Commands.EnterTartaneDeck.event		= "BI_EnterTartaneDeck";
	BattleInterface.Commands.EnterTartaneDeck.note		= LanguageConvertString(idLngFile, "sea_EnterShipDeck");
// <-- KK
// MAXIMUS Deck <--

	// Hoist Flag MOD -Amokachi
	BattleInterface.Commands.HoistFlag.enable			= true;
	BattleInterface.Commands.HoistFlag.picNum			= 15; // KK
	BattleInterface.Commands.HoistFlag.event			= "BI_HoistFlag";
	BattleInterface.Commands.HoistFlag.note			= LanguageConvertString(idLngFile, "sea_HoistFlag");

	LanguageCloseFile(idLngFile);
}

ref BI_GetChargeQuantity()
{
	int chIdx = GetEventData();
	ref refChar = GetCharacter(chIdx);
	BI_ChargeState[0] = 4;
	BI_ChargeState[1] = GetCargoGoods(refChar,GOOD_BALLS);
	BI_ChargeState[2] = GetCargoGoods(refChar,GOOD_GRAPES);
	BI_ChargeState[3] = GetCargoGoods(refChar,GOOD_KNIPPELS);
	BI_ChargeState[4] = GetCargoGoods(refChar,GOOD_BOMBS);

	return &BI_ChargeState;
}

ref GetCurrentCharge()
{
	ref refChar = GetMainCharacter();
	BI_intRetValue = -1;

	if( CheckAttribute(refChar,"Ship.Cannons.Charge.Type") )
	{
		switch(sti(refChar.Ship.Cannons.Charge.Type))
		{
		case GOOD_BALLS:
			BI_intRetValue = 2;
			break;
		case GOOD_GRAPES:
			BI_intRetValue = 3;
			break;
		case GOOD_KNIPPELS:
			BI_intRetValue = 0;
			break;
		case GOOD_BOMBS:
			BI_intRetValue = 1;
			break;
		}
		if(bNotEnoughPowder) BI_intRetValue = 4; // TIH varname update // changed by MAXIMUS [gunpowder mod]
	}

	return &BI_intRetValue;
}

void BI_SetSeaState()
{
	bool bTmp;
	bSailTo = GetEventData();
	bTmp = GetEventData();
	bMapEnter = GetEventData();
	bAttack = GetEventData();
	bDefend = GetEventData();
	bReloadCanBe = GetEventData();
	bi_nReloadTarget = GetEventData();
	bEnableIslandSailTo = bMapEnter;
	if(bDisableMapEnter)	bMapEnter = false;
}

ref BI_GetData()
{
	int dataType = GetEventData();
	int chrIdx;
	ref chRef;

	switch(dataType)
	{
	// Получаем номер картинки корабля
	case BIDT_SHIPPICTURE:
		chRef = GetCharacter(GetEventData());
		if( CharacterIsDead(chRef) )
		{
			BI_intNRetValue[0] = 0;
			BI_intNRetValue[1] = 7;
			BI_intNRetValue[2] = true;
			break;
		}
		int st = GetCharacterShipType(&chRef); // PS
		if(st>=0 && st<SHIP_TYPES_QUANTITY)
		{
// KK -->
			switch(ShipsTypes[st].BIPic)
			// PS <--
			{
			// NK -->
			case "boat":
				BI_intNRetValue[0] = 11;
				BI_intNRetValue[1] = 2;
				break;
			// NK <--
			case "tartane1":
				BI_intNRetValue[0] = 11;
				BI_intNRetValue[1] = 2;
				break;
			case "tartane2":
				BI_intNRetValue[0] = 11;
				BI_intNRetValue[1] = 2;
				break;
			case "yacht1":
				BI_intNRetValue[0] = 9;
				BI_intNRetValue[1] = 2;
				break;
			case "yacht2":
				BI_intNRetValue[0] = 9;
				BI_intNRetValue[1] = 2;
				break;
			case "barque1":
				BI_intNRetValue[0] = 7;
				BI_intNRetValue[1] = 2;
				break;
			case "barque2":
				BI_intNRetValue[0] = 7;
				BI_intNRetValue[1] = 2;
				break;
			case "lugger1":
				BI_intNRetValue[0] = 15;
				BI_intNRetValue[1] = 2;
				break;
			case "lugger2":
				BI_intNRetValue[0] = 15;
				BI_intNRetValue[1] = 2;
				break;
			case "galeoth1":
				BI_intNRetValue[0] = 0;
				BI_intNRetValue[1] = 3;
				break;
			case "galeoth2":
				BI_intNRetValue[0] = 0;
				BI_intNRetValue[1] = 3;
				break;
			case "xebec1":
				BI_intNRetValue[0] = 10;
				BI_intNRetValue[1] = 2;
				break;
			case "xebec2":
				BI_intNRetValue[0] = 10;
				BI_intNRetValue[1] = 2;
				break;
			case "sloop1":
				BI_intNRetValue[0] = 8;
				BI_intNRetValue[1] = 2;
				break;
			case "sloop2":
				BI_intNRetValue[0] = 8;
				BI_intNRetValue[1] = 2;
				break;
			case "schooner1":
				BI_intNRetValue[0] = 12;
				BI_intNRetValue[1] = 2;
				break;
			case "schooner2":
				BI_intNRetValue[0] = 12;
				BI_intNRetValue[1] = 2;
				break;
			case "caravel1":
				BI_intNRetValue[0] = 4;
				BI_intNRetValue[1] = 2;
				break;
			case "caravel2":
				BI_intNRetValue[0] = 4;
				BI_intNRetValue[1] = 2;
				break;
			case "fleut1":
				BI_intNRetValue[0] = 2;
				BI_intNRetValue[1] = 2;
				break;
			case "fleut2":
				BI_intNRetValue[0] = 2;
				BI_intNRetValue[1] = 2;
				break;
			case "brig1":
				BI_intNRetValue[0] = 5;
				BI_intNRetValue[1] = 2;
				break;
			case "brig2":
				BI_intNRetValue[0] = 5;
				BI_intNRetValue[1] = 2;
				break;
			case "galeon1":
				BI_intNRetValue[0] = 0;
				BI_intNRetValue[1] = 2;
				break;
			case "galeon2":
				BI_intNRetValue[0] = 0;
				BI_intNRetValue[1] = 2;
				break;
			case "pinnace1":
				BI_intNRetValue[0] = 13;
				BI_intNRetValue[1] = 2;
				break;
			case "pinnace2":
				BI_intNRetValue[0] = 13;
				BI_intNRetValue[1] = 2;
				break;
			case "frigate1":
				BI_intNRetValue[0] = 1;
				BI_intNRetValue[1] = 2;
				break;
			case "frigate2":
				BI_intNRetValue[0] = 1;
				BI_intNRetValue[1] = 2;
				break;
			case "frigate_sat":
				BI_intNRetValue[0] = 1;
				BI_intNRetValue[1] = 2;
				break;
			case "corvette1":
				BI_intNRetValue[0] = 3;
				BI_intNRetValue[1] = 2;
				break;
			case "corvette2":
				BI_intNRetValue[0] = 3;
				BI_intNRetValue[1] = 2;
				break;
			case "battleship1":
				BI_intNRetValue[0] = 6;
				BI_intNRetValue[1] = 2;
				break;
			case "battleship2":
				BI_intNRetValue[0] = 6;
				BI_intNRetValue[1] = 2;
				break;
			case "manowar1":
				BI_intNRetValue[0] = 14;
				BI_intNRetValue[1] = 2;
				break;
			case "manowar2":
				BI_intNRetValue[0] = 14;
				BI_intNRetValue[1] = 2;
				break;
			case "manowar_gub":
				BI_intNRetValue[0] = 14;
				BI_intNRetValue[1] = 2;
				break;
			case "BlackPearl":
				BI_intNRetValue[0] = 0;
				BI_intNRetValue[1] = 11;
				break;
			case "Lineship":
				BI_intNRetValue[0] = 0;
				BI_intNRetValue[1] = 4;
				break;
			case "Warship":
				BI_intNRetValue[0] = 1;
				BI_intNRetValue[1] = 4;
				break;
			case "Xebec3":				//Mod Ship by Duke Surak'nar 17/08/2003
				BI_intNRetValue[0] = 0;
				BI_intNRetValue[1] = 10;
				break;
			// following 2 entries are for ordinary Lineships
			case "BlackPearl1":
				BI_intNRetValue[0] = 0;
				BI_intNRetValue[1] = 4;
				break;
			case "BlackPearl2":
				BI_intNRetValue[0] = 0;
				BI_intNRetValue[1] = 4;
				break;
			case "Shnyava1":
				BI_intNRetValue[0] = 2;
				BI_intNRetValue[1] = 11;
				break;
			case "Shnyava2":
				BI_intNRetValue[0] = 2;
				BI_intNRetValue[1] = 11;
				break;
			case "Brig_20_Gun1_18":
				BI_intNRetValue[0] = 2;
				BI_intNRetValue[1] = 11;
				break;
			case "Brig_16_Gun1_18":
				BI_intNRetValue[0] = 3;
				BI_intNRetValue[1] = 11;
				break;
			case "Brigantina1":
				BI_intNRetValue[0] = 1;
				BI_intNRetValue[1] = 11;
				break;
			case "SchoonerXebec":
				BI_intNRetValue[0] = 5;
				BI_intNRetValue[1] = 11;
				break;
			case "Manow50_gub":
				BI_intNRetValue[0] = 6;
				BI_intNRetValue[1] = 11;
				break;
			case "SloopofWar_50":
				BI_intNRetValue[0] = 7;
				BI_intNRetValue[1] = 11;
				break;
			case "HeavyFrigate":
				BI_intNRetValue[0] = 8;
				BI_intNRetValue[1] = 11;
				break;
			case "Surprise":
				BI_intNRetValue[0] = 9;
				BI_intNRetValue[1] = 11;
				break;
			case "CorvFrig2_50":
				BI_intNRetValue[0] = 10;
				BI_intNRetValue[1] = 11;
				break;
			case "HeavyWarship":
				BI_intNRetValue[0] = 12;
				BI_intNRetValue[1] = 11;
				break;
			case "Pinnaceofwar40g":
				BI_intNRetValue[0] = 13;
				BI_intNRetValue[1] = 11;
				break;
			case "WallerPinnace":
				BI_intNRetValue[0] = 14;
				BI_intNRetValue[1] = 11;
				break;
			case "FleutOfWar34G":
				BI_intNRetValue[0] = 15;
				BI_intNRetValue[1] = 11;
				break;
// added by MAXIMUS [new ships from AOP] -->
			case "battleship3":
				BI_intNRetValue[0] = 4;
				BI_intNRetValue[1] = 11;
				break;
			case "tartane3":
				BI_intNRetValue[0] = 11;
				BI_intNRetValue[1] = 2;
				break;
			case "manowar3":
				BI_intNRetValue[0] = 11;
				BI_intNRetValue[1] = 11;
				break;
// added by MAXIMUS [new ships from AOP] <--
			case "flyingdutchman":
				BI_intNRetValue[0] = 0;
				BI_intNRetValue[1] = 11;
				break;
			}
// <-- KK
			BI_intNRetValue[2] = false;
		}	
		break;

	case BIDT_GERALD_DATA:
		{
			chrIdx = GetEventData();
			if(chrIdx<0) break;
			chRef = GetCharacter(chrIdx);
			BI_intNRetValue[0] = 8;
			switch( SeaAI_GetRelation(chrIdx,GetMainCharacterIndex()) )
			{
			case RELATION_FRIEND:	BI_intNRetValue[1] = 10; break;		//changed by KAM
			case RELATION_NEUTRAL:	BI_intNRetValue[1] = 11; break;		//changed by KAM
			case RELATION_ENEMY:	BI_intNRetValue[1] = 9; break;		//changed by KAM
			}
			BI_intNRetValue[2] = 8;
			switch( sti(chRef.nation) )
			{
			case ENGLAND:		BI_intNRetValue[3] = 3; break;
			case FRANCE:		BI_intNRetValue[3] = 2; break;
			case SPAIN:		BI_intNRetValue[3] = 0; break;
			case PIRATE:		BI_intNRetValue[3] = 5; break;
			case HOLLAND:		BI_intNRetValue[3] = 4; break;
			case PORTUGAL:		BI_intNRetValue[3] = 1; break;
			case CATALONIA:		BI_intNRetValue[3] = 6; break;		//added by KAM
			case NEUTRAL_NATION:	BI_intNRetValue[3] = 7; break;		//added by KAM
			case UNKNOWN_NATION:	BI_intNRetValue[3] = 8; break;		//added by KAM
			case PERSONAL_NATION:	BI_intNRetValue[3] = 12; break;		// KK
			}
		}
		break;
	}
	return &BI_intNRetValue;
}

void SetParameterData()
{
	int idLngFile = LanguageOpenFile("commands_name.txt"); // KK
	ref PChar = GetMainCharacter(); // PB
	string compasstype = CheckCharacterEquipByGroup(PChar, COMPASS_ITEM_TYPE); // KK

	BattleInterface.CommandTextures.list.t0.name = "battle_interface\cicons_charge.tga";
	BattleInterface.CommandTextures.list.t0.xsize = 1;
	BattleInterface.CommandTextures.list.t0.ysize = 4;

	BattleInterface.CommandTextures.list.t1.name = "battle_interface\cicons_command.tga";
	BattleInterface.CommandTextures.list.t1.xsize = 4;
	BattleInterface.CommandTextures.list.t1.ysize = 4;

	BattleInterface.CommandTextures.list.t2.name = "battle_interface\ships_16.tga";
	BattleInterface.CommandTextures.list.t2.xsize = 4;
	BattleInterface.CommandTextures.list.t2.ysize = 4;
	BattleInterface.CommandTextures.list.t3.name = "battle_interface\ships_1.tga";
	BattleInterface.CommandTextures.list.t3.xsize = 1;
	BattleInterface.CommandTextures.list.t3.ysize = 1;
	BattleInterface.CommandTextures.list.t4.name = "battle_interface\ships_2.tga";
	BattleInterface.CommandTextures.list.t4.xsize = 1;
	BattleInterface.CommandTextures.list.t4.ysize = 2;

	BattleInterface.CommandTextures.list.t5.name = "battle_interface\SailControls.tga";
	BattleInterface.CommandTextures.list.t5.xsize = 4;
	BattleInterface.CommandTextures.list.t5.ysize = 1;

	BattleInterface.CommandTextures.list.t6.name = "battle_interface\sea_abilitys.tga";
	BattleInterface.CommandTextures.list.t6.xsize = 4;
	BattleInterface.CommandTextures.list.t6.ysize = 2;

	BattleInterface.CommandTextures.list.t7.name = "battle_interface\scull.tga";
	BattleInterface.CommandTextures.list.t7.xsize = 1;
	BattleInterface.CommandTextures.list.t7.ysize = 1;

	BattleInterface.CommandTextures.list.t8.name = "battle_interface\small_nations.tga";
	BattleInterface.CommandTextures.list.t8.xsize = 16;					//changed by KAM
	BattleInterface.CommandTextures.list.t8.ysize = 1;

	BattleInterface.CommandTextures.list.t9.name = "battle_interface\Artefact.tga";
	BattleInterface.CommandTextures.list.t9.xsize = 1;
	BattleInterface.CommandTextures.list.t9.ysize = 1;

	BattleInterface.CommandTextures.list.t10.name = "battle_interface\08shs_02.tga";	//Mod Ship by Duke Surak'nar 17/08/2003
	BattleInterface.CommandTextures.list.t10.xsize = 1;
	BattleInterface.CommandTextures.list.t10.ysize = 1;

// KK -->
	BattleInterface.CommandTextures.list.t11.name = "battle_interface\ships_32.tga";
	BattleInterface.CommandTextures.list.t11.xsize = 4;
	BattleInterface.CommandTextures.list.t11.ysize = 4;

	BattleInterface.CommandTextures.list.t12.name = "battle_interface\LandTarget1.tga";
	BattleInterface.CommandTextures.list.t12.xsize = 4;
	BattleInterface.CommandTextures.list.t12.ysize = 2;	

	BattleInterface.CommandTextures.list.t13.name = "battle_interface\LandTarget4.tga";
	BattleInterface.CommandTextures.list.t13.xsize = 8;
	BattleInterface.CommandTextures.list.t13.ysize = 2;
// <-- KK

	BattleInterface.CommandTextures.ChargeTexNum = 0;
	BattleInterface.CommandTextures.CommandTexNum = 1;

	BattleInterface.CommandShowParam.maxShowQuantity = 8;
	BattleInterface.CommandShowParam.iconDistance = 4;
	BattleInterface.CommandShowParam.iconWidth = RecalculateHIcon(64);
	BattleInterface.CommandShowParam.iconHeight = RecalculateVIcon(64);
	BattleInterface.CommandShowParam.leftIconsOffset = sti(showWindow.left)+RecalculateHIcon(16);
	BattleInterface.CommandShowParam.downIconsOffset = sti(showWindow.bottom)-RecalculateVIcon(80);
	BattleInterface.CommandShowParam.buttonWidth = RecalculateHIcon(8);
	BattleInterface.CommandShowParam.buttonHeight = RecalculateVIcon(64);
	BattleInterface.CommandShowParam.buttonOffset = RecalculateHIcon(4);
	BattleInterface.CommandShowParam.buttonTexture = "battle_interface\lr_buttons.tga";
	BattleInterface.CommandShowParam.shipStateWidth = RecalculateHIcon(64);
	BattleInterface.CommandShowParam.shipStateHeight = RecalculateVIcon(16);
	BattleInterface.CommandShowParam.shipStateTexture = "battle_interface\indicators.tga";
	BattleInterface.CommandShowParam.shipStateOffset = RecalculateVIcon(0);
	BattleInterface.CommandShowParam.GeraldWidth = RecalculateHIcon(32);
	BattleInterface.CommandShowParam.GeraldHeight = RecalculateVIcon(32);
	BattleInterface.CommandShowParam.commandFont = "bold_numbers";
	BattleInterface.CommandShowParam.printXOffset = RecalculateHIcon(32);
	BattleInterface.CommandShowParam.printYOffset = RecalculateVIcon(-26);
	BattleInterface.CommandShowParam.commandNoteFont = "interface_normal";
	BattleInterface.CommandShowParam.noteXOffset = RecalculateHIcon(0);
	BattleInterface.CommandShowParam.noteYOffset = RecalculateVIcon(-28);
	BattleInterface.CommandShowParam.argbTFactorColor = argb(256,64,64,64);

// KK -->
	BattleInterface.UserIcons.ui1.enable = true;
	BattleInterface.UserIcons.ui1.pic = 0;
	BattleInterface.UserIcons.ui1.tex = 5;
	BattleInterface.UserIcons.ui1.name = "sail_none";
	BattleInterface.UserIcons.ui1.note = LanguageConvertString(idLngFile, "sea_LowerSails");
	//----------------------------------------------
	BattleInterface.UserIcons.ui2.enable = true;
	BattleInterface.UserIcons.ui2.pic = 1;
	BattleInterface.UserIcons.ui2.tex = 5;
	BattleInterface.UserIcons.ui2.name = "sail_midi";
	BattleInterface.UserIcons.ui2.note = LanguageConvertString(idLngFile, "sea_BattleSails");
	//----------------------------------------------
	BattleInterface.UserIcons.ui3.enable = true;
	BattleInterface.UserIcons.ui3.pic = 2;
	BattleInterface.UserIcons.ui3.tex = 5;
	BattleInterface.UserIcons.ui3.name = "sail_fast";
	BattleInterface.UserIcons.ui3.note = LanguageConvertString(idLngFile, "sea_FullSails");
	//----------------------------------------------
	BattleInterface.UserIcons.ui4.enable = true;
	BattleInterface.UserIcons.ui4.pic = 11;
	BattleInterface.UserIcons.ui4.tex = 13;
	BattleInterface.UserIcons.ui4.name = "ShipDeck";
	BattleInterface.UserIcons.ui4.note = LanguageConvertString(idLngFile, "sea_EnterShipDeck");
	//----------------------------------------------
	BattleInterface.UserIcons.ui5.enable = true;
	BattleInterface.UserIcons.ui5.pic = 12;
	BattleInterface.UserIcons.ui5.tex = 13;
	BattleInterface.UserIcons.ui5.name = "Cabin";
	BattleInterface.UserIcons.ui5.note = LanguageConvertString(idLngFile, "sea_EnterCabin");
	//----------------------------------------------
	BattleInterface.UserIcons.ui6.enable = true;
	BattleInterface.UserIcons.ui6.pic = 13;
	BattleInterface.UserIcons.ui6.tex = 13;
	BattleInterface.UserIcons.ui6.name = "Seadogs";
	BattleInterface.UserIcons.ui6.note = LanguageConvertString(idLngFile, "sea_EnterSeadogs");
	//----------------------------------------------
	BattleInterface.UserIcons.ui7.enable = true;
	BattleInterface.UserIcons.ui7.pic = 14;
	BattleInterface.UserIcons.ui7.tex = 13;
	BattleInterface.UserIcons.ui7.name = "Deck1";
	if (GetCharacterShipCannonsDeckCount(GetMainCharacter()) == 1)
		BattleInterface.UserIcons.ui7.note = LanguageConvertString(idLngFile, "sea_EnterMainCannonsDeck");
	else
		BattleInterface.UserIcons.ui7.note = LanguageConvertString(idLngFile, "sea_EnterUpperCannonsDeck");
	//----------------------------------------------
	BattleInterface.UserIcons.ui8.enable = true;
	BattleInterface.UserIcons.ui8.pic = 14;
	BattleInterface.UserIcons.ui8.tex = 13;
	BattleInterface.UserIcons.ui8.name = "Deck2";
	BattleInterface.UserIcons.ui8.note = LanguageConvertString(idLngFile, "sea_EnterLowerCannonsDeck");
	//----------------------------------------------
	BattleInterface.UserIcons.ui9.enable = true;
	BattleInterface.UserIcons.ui9.pic = 14;
	BattleInterface.UserIcons.ui9.tex = 13;
	BattleInterface.UserIcons.ui9.name = "Deck3";
	BattleInterface.UserIcons.ui9.note = LanguageConvertString(idLngFile, "sea_EnterMainCannonsDeck");
	//----------------------------------------------
	BattleInterface.UserIcons.ui10.enable = true;
	BattleInterface.UserIcons.ui10.pic = 15;
	BattleInterface.UserIcons.ui10.tex = 13;
	BattleInterface.UserIcons.ui10.name = "Hold1";
	if (GetCharacterShipCargoHoldCount(GetMainCharacter()) > 1)
		BattleInterface.UserIcons.ui10.note = LanguageConvertString(idLngFile, "sea_EnterHold1");
	else
		BattleInterface.UserIcons.ui10.note = LanguageConvertString(idLngFile, "sea_EnterHold");
	//----------------------------------------------
	BattleInterface.UserIcons.ui11.enable = true;
	BattleInterface.UserIcons.ui11.pic = 15;
	BattleInterface.UserIcons.ui11.tex = 13;
	BattleInterface.UserIcons.ui11.name = "Hold2";
	BattleInterface.UserIcons.ui11.note = LanguageConvertString(idLngFile, "sea_EnterHold2");
// <-- KK

	//===============================================
	BattleInterface.MessageIcons.IconWidth = RecalculateHIcon(64);
	BattleInterface.MessageIcons.IconHeight = RecalculateVIcon(24);
	BattleInterface.MessageIcons.IconDist = RecalculateVIcon(2);
	BattleInterface.MessageIcons.IconBottom = sti(showWindow.bottom)-RecalculateVIcon(80+20);
	BattleInterface.MessageIcons.IconMaxQuantity = 4;
	BattleInterface.MessageIcons.BlendTime = 3.0;
	BattleInterface.MessageIcons.FallSpeed = 22.0;
	BattleInterface.MessageIcons.argbHighBlind = argb(255,128,128,128);
	BattleInterface.MessageIcons.argbLowBlind = argb(255,68,68,68);
	BattleInterface.MessageIcons.BlindUpTime = 0.5;
	BattleInterface.MessageIcons.BlindDownTime = 1.0;
	BattleInterface.MessageIcons.texture = "battle_interface\MessageIcons.tga";
	BattleInterface.MessageIcons.TexHSize = 2;
	BattleInterface.MessageIcons.TexVSize = 2;

	BattleInterface.navigation.aspectRatio				= showWindow.aspectRatio;
	// PB: Compasses -->
	if(!DISPLAY_BATTLEINTERFACE)
	{
		switch(compasstype)
		{
			case "":         bRealBattleInterface = true;  break; // KK
			case "compass1": bRealBattleInterface = true;  break;
			case "compass2": bRealBattleInterface = false; break;
			case "compass3": bRealBattleInterface = false; break; // KK
		}
	}
	// PB: Compasses <--
	if(bRealBattleInterface)
	{
		BattleInterface.navigation.navigatorWidth		= RecalculateHIcon(80); // ccc 192
		BattleInterface.navigation.navigatorHeight		= RecalculateVIcon(80); // ccc 192
		BattleInterface.navigation.rightPos				= sti(showWindow.left)+RecalculateHIcon(80); // ccc showWindow.right
		BattleInterface.navigation.topPos				= sti(showWindow.bottom)-RecalculateVIcon(180); // ccc showWindow.top
		BattleInterface.navigation.speedOutYOffset		= RecalculateVIcon(-40); // ccc -88
		BattleInterface.navigation.shipSpeedXOffset		= RecalculateHIcon(37); // ccc 80
		BattleInterface.navigation.windSpeedXOffset		= RecalculateHIcon(-35); // ccc -80
		BattleInterface.navigation.fontScale			= 0.35; // ccc 0.75
		BattleInterface.navigation.windWidth			= 15; // ccc 30
		BattleInterface.navigation.windHeight			= 50; // ccc 120
	}
	else
	{
		BattleInterface.navigation.navigatorWidth		= RecalculateHIcon(192);
		BattleInterface.navigation.navigatorHeight		= RecalculateVIcon(192);
		BattleInterface.navigation.rightPos				= showWindow.right;
		BattleInterface.navigation.topPos				= showWindow.top;
		BattleInterface.navigation.speedOutYOffset		= RecalculateVIcon(-88);
		BattleInterface.navigation.shipSpeedXOffset		= RecalculateHIcon(80);
		BattleInterface.navigation.windSpeedXOffset		= RecalculateHIcon(-80);
		BattleInterface.navigation.fontScale			= 0.75;
		BattleInterface.navigation.windWidth			= 30;
		BattleInterface.navigation.windHeight			= 120;
	}

// KK -->
	if (GetCaracterShipCannonsType(PChar) != CANNON_TYPE_NONECANNON)
		BattleInterface.navigation.cannonsTexture			= "battle_interface\indicators_cannons_reload.tga";
	else
		BattleInterface.navigation.cannonsTexture			= "battle_interface\empty.tga";
	if (compasstype == "") {
		BattleInterface.navigation.compasTexture = "battle_interface\empty.tga";
		BattleInterface.navigation.speedTexture				= "battle_interface\empty.tga";
		BattleInterface.navigation.emptyTexture				= "battle_interface\indicators_dark_and_center_ship_nowind.tga";
		BattleInterface.navigation.windTexture				= "battle_interface\empty.tga";
		BattleInterface.navigation.mapRadius=0;
		BattleInterface.navigation.shipShowRadius			= 0.0;
	} else {
// PB: Recode to switch -->
  	switch(ONSEA_COMPASS)
  	{
			case 0: BattleInterface.navigation.compasTexture = "battle_interface\compass.tga"; break; // Stock default
			case 1: BattleInterface.navigation.compasTexture = "battle_interface\compass1.tga"; break; // Catalina The Pirate version
			case 2: BattleInterface.navigation.compasTexture = "battle_interface\compass2.tga"; break; // Age of Pirates version
  	}
// PB: Recode to switch <--
		if (compasstype == "compass1") {
			BattleInterface.navigation.speedTexture				= "battle_interface\empty.tga";
			BattleInterface.navigation.emptyTexture				= "battle_interface\indicators_dark_and_center_ship_nowind.tga";
			BattleInterface.navigation.shipShowRadius			= 0.0;
		} else {
			BattleInterface.navigation.speedTexture				= "battle_interface\indicators_wind_and_ship.tga";
			BattleInterface.navigation.emptyTexture				= "battle_interface\indicators_dark_and_center_ship.tga";
			BattleInterface.navigation.speedShowFont		= "bold_numbers";
			BattleInterface.navigation.shipShowRadius			= 8.0;
		}
		BattleInterface.navigation.windTexture				= "battle_interface\wind_pointer.tga";

		if(bRealBattleInterface)
		{
			BattleInterface.navigation.mapRadius			= 5; // ccc 54
		}
		else
		{
			BattleInterface.navigation.mapRadius			= 54;
		}
	}
	BattleInterface.navigation.leftChargeBegAngle		= 215;
	BattleInterface.navigation.leftChargeEndAngle		= 325;
	BattleInterface.navigation.rightChargeBegAngle		= 145;
	BattleInterface.navigation.rightChargeEndAngle		= 35;
	BattleInterface.navigation.forwardChargeBegAngle	= 335;
	BattleInterface.navigation.forwardChargeEndAngle	= 385;
	BattleInterface.navigation.backwardChargeBegAngle	= 205;
	BattleInterface.navigation.backwardChargeEndAngle	= 155;
	BattleInterface.navigation.shipSpeedBegAngle		= 175;
	BattleInterface.navigation.shipSpeedEndAngle		= 55;
	BattleInterface.navigation.windSpeedBegAngle		= 180;
	BattleInterface.navigation.windSpeedEndAngle		= 410;

	BattleInterface.navigation.horizontRadius			= 400;
	BattleInterface.navigation.minScale					= 0.5;
	BattleInterface.navigation.maxScale					= 4;
	BattleInterface.navigation.scaleStep				= 0.1;
	BattleInterface.navigation.argbReadyCannonColor		= argb(255,0,155,0);
	BattleInterface.navigation.argbChargeCannonColor	= argb(255,255,0,0);
	BattleInterface.navigation.argbSeaColor				= argb(255,10,30,80);
	BattleInterface.navigation.argbFireZoneColor		= argb(60,250,250,250);
	if (compasstype != "compass3") {
		BattleInterface.navigation.argbEnemyShipColor		= argb(255,128,128,128);
		BattleInterface.navigation.argbFrendShipColor		= argb(255,128,128,128);
		BattleInterface.navigation.argbNeutralShipColor		= argb(255,128,128,128);
	} else {
		BattleInterface.navigation.argbEnemyShipColor		= argb(255,255,0,0);
		BattleInterface.navigation.argbFrendShipColor		= argb(255,0,255,0);
		BattleInterface.navigation.argbNeutralShipColor		= argb(255,128,128,128);
	}
	BattleInterface.navigation.argbDeadShipColor		= argb(255,0,0,255);
	BattleInterface.navigation.argbBackMaxColor			= argb(255,0,0,128);
	BattleInterface.navigation.argbBackMinColor			= argb(0,0,0,128);
	if (GetCaracterShipCannonsType(PChar) != CANNON_TYPE_NONECANNON) {
		if (CANNONPOWDER_MOD) {// TIH --> mod toggle 7-7-06
			// changed by MAXIMUS [gunpowder mod] -->
			BattleInterface.navigation.chargeTexture			= "battle_interface\small_cannons_gunpowder.tga";
			BattleInterface.navigation.chargeTextureGreed		= "1,8";
			// changed by MAXIMUS [gunpowder mod] <--
		} else {
			BattleInterface.navigation.chargeTexture			= "battle_interface\small_cannons.tga";
			BattleInterface.navigation.chargeTextureGreed		= "1,4";
		}// TIH <-- mod toggle
	} else {
		BattleInterface.navigation.chargeTexture			= "battle_interface\empty.tga";
	}
	if(bRealBattleInterface)
	{
		BattleInterface.navigation.chargePos			= RecalculateHIcon(70)+","+RecalculateVIcon(73); //ccc 160 & 174
		BattleInterface.navigation.chargePictureSize	= "20,20"; //ccc "32,32"
	}
	else
	{
		BattleInterface.navigation.chargePos			= RecalculateHIcon(160)+","+RecalculateVIcon(174);
		BattleInterface.navigation.chargePictureSize	= "32,32";
	}
	LanguageCloseFile(idLngFile);
// <-- KK
}

ref ProcessSailDamage()
{
	// от кого удар
	int shootIdx = GetEventData();
	// перс
	int chrIdx = GetEventData();
	string sMastName = GetEventData();
	// координаты паруса
	string reyName = GetEventData();
	int groupNum = GetEventData();
	// данные о дырках
	int holeCount = GetEventData();
	int holeData = GetEventData();
	int maxHoleCount = GetEventData();
	// мощность паруса
	float sailPower = GetEventData();

// KK -->
	if (shootIdx == chrIdx) {
		BI_g_fRetVal = 0.0;
		return &BI_g_fRetVal;
	}
// <-- KK

	ref chref = GetCharacter(chrIdx);
	string groupName = ""+groupNum;
	aref arSail;
	makearef(arSail,chref.ship.sails.(reyName).(groupName));

	float sailDmg = 0.0;
	float sailDmgMax = GetCharacterShipSP(chref) * sailPower;
	if( !CheckAttribute(arSail,"dmg") )	{ sailDmg = 0.0; }

	if(sMastName=="*")
	{
		sailDmg += GetRigDamage(shootIdx,sti(AIBalls.CurrentBallType),chref);
		if(sailDmg>sailDmgMax)	{ sailDmg = sailDmgMax; }
		int needHole = GetNeedHoleFromDmg(sailDmg,sailDmgMax,maxHoleCount);
		if(holeCount!=needHole)
		{
			if(holeCount<needHole)
			{
				holeData = RandomHole2Sail(chrIdx,reyName,groupNum, maxHoleCount, holeData, needHole-holeCount);
				holeCount = needHole;
			}
			else
			{
				sailDmg = GetNeedDmgFromHole(holeCount,sailDmgMax,maxHoleCount);
			}
		}
	}
	else
	{
		if(sMastName!="#")	{ arSail.mastFall = sMastName; }
		sailDmg = sailDmgMax;
	}

	arSail.hc = holeCount;
	arSail.hd = holeData;
	arSail.mhc = maxHoleCount;
	arSail.sp = sailPower;
	arSail.dmg = sailDmg;

	chref.ship.SP = CalculateShipSP(chref);
	BI_g_fRetVal = sailDmg;
	return &BI_g_fRetVal;
}

void ProcessDayRepair()
{
	//trace("Gauging: NEXTDAY_start PDR");
	int i, cn;
	float matQ, tmpf, repPercent;
	ref chref;
	for(i=0; i<4; i++)
	{
		cn = GetCompanionIndex(GetMainCharacter(),i);
		if(cn==-1) continue;
		chref = GetCharacter(cn);
		RepairAllCannons(&chref); // NK can qty. For now repair all fixable guns. Later go back and set repair rates. 05-04-19

		// расчет починки корпуса
		if( GetHullPercent(chref)<100.0 )
		{
			repPercent = GetHullRPD(chref);
			matQ = repPercent*GetHullPPP(chref);
			tmpf = GetRepairGoods(true,chref);
			if(tmpf<matQ)	{ repPercent = tmpf/GetHullPPP(chref); }
			repPercent = ProcessHullRepair(chref,repPercent);
			matQ = repPercent*GetHullPPP(chref);
			RemoveRepairGoods(true,chref,matQ);
		}

		// расчет починки парусов
		if( GetSailPercent(chref)<100.0 )
		{
			repPercent = GetSailRPD(chref);
			matQ = repPercent*GetSailSPP(chref);
			tmpf = GetRepairGoods(false,chref);
			if(tmpf<matQ)	{ repPercent = tmpf/GetSailSPP(chref); }
			repPercent = ProcessSailRepair(chref,repPercent);
			matQ = repPercent*GetSailSPP(chref);
			RemoveRepairGoods(false,chref,matQ);
		}
	}
	//trace("Gauging: NEXTDAY_end PDR");
}

// procGetSailTextureData is now in a separate file in the same directory as this file

ref procGetRiggingData()
{
	int i,n;

	int retVal = 0;

	string datName = GetEventData();
	if(datName=="GetFlagTexNum")
	{
		i = GetEventData();
		n = GetEventData();
		if(i==true)
		{
			switch(n)
			{
				case HOLLAND: retVal = 0; break;
				case ENGLAND: retVal = 1; break;
				case FRANCE: retVal = 2; break;
				case PORTUGAL: retVal = 3; break;
				case SPAIN: retVal = 4; break;
				case PIRATE: retVal = 5; break;
				case CATALONIA: retVal = 6; break;		//added by KAM
				case UNKNOWN_NATION: retVal = 6; break;		//added by KAM		// changed after build 11 by KAM
				case NEUTRAL_NATION: retVal = 6; break;		//added by KAM
				case PERSONAL_NATION: retVal = 7; break;	// KK
			}
		}
		else
		{
			switch(n)
			{
				case HOLLAND: retVal = 0; break;
				case ENGLAND: retVal = 1; break;
				case FRANCE: retVal = 2; break;
				case PORTUGAL: retVal = 3; break;
				case SPAIN: retVal = 4; break;
				case PIRATE: retVal = 5; break;
				case CATALONIA: retVal = 6; break;		//added by KAM
				case UNKNOWN_NATION: retVal = 6; break;		//added by KAM		// changed after build 11 by KAM
				case NEUTRAL_NATION: retVal = 6; break;		//added by KAM
				case PERSONAL_NATION: retVal = 7; break;	// KK
			}
		}
	}
	return &retVal;
}

void procBISelectShip()
{
	int chrIdx = GetEventData();
	int isMyChr = GetEventData();

	if(chrIdx==GetMainCharacterIndex())	chrIdx = -1;

	float fShSpeed = 0.005;
	float fShAmp = 1.0;
	float fShW = 1.0;
	float fShH = 1.0;
	float fTop = 10.0;

	SendMessage(&objShipPointer,"lllfffff",MSG_SP_CHANGESHIP,chrIdx,isMyChr,fShSpeed,fShAmp,fShW,fShH,fTop);
}

void procMastFall()
{
	int chrIdx = GetEventData();
	string mastName = GetEventData();
	int bFirstFall = GetEventData();

	if(chrIdx<0) return;
	int mastNum = strcut(mastName,4,strlen(mastName)-1);

	trace("For character "+chrIdx+" fall Mast name "+mastName+" has index "+mastNum);
	SendMessage(&PeopleOnShip, "lal", MSG_PEOPLES_ON_SHIP_MASTFALL, GetCharacter(chrIdx), mastNum);
}

bool CheckInstantRepairCondition(ref chref)
{
	//int tmpLangFileID = LanguageOpenFile("interface_strings.txt");
//boal -->
	//if(!GetCharacterPerkUsing(chref,"InstantRepair")) return false;

//ccc realistic shipyard repair at anchorage only->
	// LDH 02Oct06
	if(!bMapEnter && REALREPAIR) return false;
//ccc repair <-

	bool	retRepair = GetCharacterPerkUsing(chref,"InstantRepair");
	if(!retRepair)
	{
		int cn;
		for(int i=1; i<4; i++)
		{
			cn = GetOfficersIndex(chref,i);
			if(cn!=-1)
			{
				if(GetCharacterPerkUsing(GetCharacter(cn),"InstantRepair"))
				{
					retRepair = true;
					break;
				}	
			}
		}
	}
	if(!retRepair) return false;
//boal <-- 

	float chrShipHP = GetHullPercent(chref);
	float chrShipSP = GetSailPercent(chref);

	bool bYesHPRepair = chrShipHP<90.0;
	bool bYesSPRepair = chrShipSP<90.0;

	if( bYesHPRepair )	{ bYesHPRepair = GetCargoGoods(chref,GOOD_PLANKS)>0; }
	if( bYesSPRepair )	{ bYesSPRepair = GetCargoGoods(chref,GOOD_SAILCLOTH)>0; }

	return bYesHPRepair || bYesSPRepair;
	//LanguageCloseFile(tmpLangFileID);
}

void BI_PerkAgainUsable()
{
	BI_SetCommandMode(-1,-1,-1,-1);
}

float GetRepairGoods(bool bIsHull, ref chref)
{
	float fGoodsQ = 0.0;

	if( bIsHull )
	{
		fGoodsQ = GetCargoGoods(chref,GOOD_PLANKS);
		if( CheckAttribute(chref,"RepairMaterials.forHull") )
		{	fGoodsQ += stf(chref.RepairMaterials.forHull);
		}
	}
	else
	{
		fGoodsQ = GetCargoGoods(chref,GOOD_SAILCLOTH);
		if( CheckAttribute(chref,"RepairMaterials.forSails") )
		{	fGoodsQ += stf(chref.RepairMaterials.forSails);
		}
	}

	return fGoodsQ;
}

void RemoveRepairGoods(bool bIsHull, ref chref, float matQ)
{
	int nGoodsQ = 0;
	float fGoodsQ = GetRepairGoods(bIsHull,chref);

	if( bIsHull )
	{
		if(fGoodsQ<=matQ)	{ DeleteAttribute(chref,"RepairMaterials.forHull"); }
		else
		{
			fGoodsQ -= matQ;
			nGoodsQ = makeint(fGoodsQ);
			chref.RepairMaterials.forHull = fGoodsQ - nGoodsQ;
		}
		SetCharacterGoods(chref,GOOD_PLANKS,nGoodsQ);
	}
	else
	{
		if(fGoodsQ<=matQ)	{ DeleteAttribute(chref,"RepairMaterials.forSails"); }
		else
		{
			fGoodsQ -= matQ;
			nGoodsQ = makeint(fGoodsQ);
			chref.RepairMaterials.forSails = fGoodsQ - nGoodsQ;
		}
		SetCharacterGoods(chref,GOOD_SAILCLOTH,nGoodsQ);
	}

}

float GetRigDamage(int shootIdx, int iBallType, ref damage_chr)
{
	ref rBall = GetGoodByType(iBallType);
	float fDmgRig = stf(rBall.DamageRig);
	ref shoot_chr;
	if(shootIdx >=0 && shootIdx != GetMainCharacterIndex() && CheckAttribute(damage_chr,"surrendered")) return 0.0; // NK because AI doesn't respect surrender. 05-04-23
	if(USE_REAL_CANNONS)
	{
		if( shootIdx>=0 )
		{
			shoot_chr = GetCharacter(shootIdx);
			if( IsCharacterPerkOn(shoot_chr,"CannonProfessional") ) { fDmgRig *= 1.20; }
			else
			{
				if( IsCharacterPerkOn(shoot_chr,"SailsDamageUp") )  { fDmgRig *= 1.10; }
			}
		}

		if( IsCharacterPerkOn(damage_chr,"ShipDefenseProfessional") ) { fDmgRig *= 0.75; }
		else
		{
			if( IsCharacterPerkOn(damage_chr,"AdvancedBattleState") ) { fDmgRig *= 0.85; }
			else
			{
				if( IsCharacterPerkOn(damage_chr,"BasicBattleState") )  { fDmgRig *= 0.92; }
			}
		}
//KB - Tuning ships
//KB - Tuning ships - gchasers effect on sails
//KB if ( sti(shoot_chr.index) == 0 ) {Trace("KB - Chaser  before " + fDmgRig);}
		aref temparef;
		float chasercritchance = 0.0;
		makearef(temparef,AIBalls);
		if(CheckAttribute(temparef,"quad")) {
			if ( AIBalls.quad == "cannonf" ) {  //KB It's a chaser
				makearef(temparef,shoot_chr.ship);
				if (CheckAttribute(temparef,"tune")) {
					makearef(temparef,shoot_chr.ship.tune);
					if(CheckAttribute(temparef,"gchasers")) {
						if ( sti(shoot_chr.ship.tune.gchasers.on) == 1 ) {
							chasercritchance += makefloat(GCSAILCRIT/100);
						}
					}
				}
				chasercritchance += makefloat(CSAILCRIT/100);
				if ( frnd() < chasercritchance ) {   //KB it's a critical
Trace ("KB - Tuning - Critical sail by chasers ");
					fDmgRig *= makefloat(CSAILCRITDMG);
				}
			}
		}
//KB if ( sti(shoot_chr.index) == 0 ) {Trace("KB - Chaser  after " + fDmgRig);}
// KB Tuning ships - new sails will reduce the amount of damage received
		makearef(temparef,damage_chr.ship);
		if (CheckAttribute(temparef,"tune")) {
			makearef(temparef,damage_chr.ship.tune);
			if(CheckAttribute(temparef,"nsails")) {
				if ( sti(damage_chr.ship.tune.nsails.on) == 1 ) {
Trace("KB - Tuning ships Damage limited by nsails");
					fDmgRig *= makefloat(1-stf(damage_chr.ship.tune.nsails.sails)/100);
				}
			}
		}
//KB - END Tuning ships
	}
	else
	{
		if( shootIdx>=0 )
		{
			shoot_chr = GetCharacter(shootIdx);
			if( IsCharacterPerkOn(shoot_chr,"CannonProfessional") )	{ fDmgRig *= 1.3; }
			else
			{
				if( IsCharacterPerkOn(shoot_chr,"SailsDamageUp") )	{ fDmgRig *= 1.15; }
			}
		}
		
		if( IsCharacterPerkOn(damage_chr,"ShipDefenseProfessional") )	{ fDmgRig *= 0.6; }
		else
		{
			if( IsCharacterPerkOn(damage_chr,"AdvancedBattleState") )	{ fDmgRig *= 0.75; }
			else
			{
				if( IsCharacterPerkOn(damage_chr,"BasicBattleState") )	{ fDmgRig *= 0.85; }
			}
		}
	}
	return fDmgRig;
}

void MakeSailDmg(int chrIdx, float dmg)
{
	object objSail;
	if( !FindClass(&objSail,"sail") ) return;
	SendMessage(&objSail,"lslf", MSG_SAIL_SCRIPT_PROCESSING,"RandomSailsDmg", chrIdx,dmg);
}

ref ProcessRandomSailDmg()
{
	BI_g_fRetVal = 0.0;
	//"lslfflll"
	int chrIdx = GetEventData();
	string nodeName = GetEventData();
	int grNum = GetEventData();
	float fDmg = GetEventData();
	float fSPow = GetEventData();
	int hc_new = GetEventData();
	int mhc = GetEventData();
	int hdat_new = GetEventData();

	if(chrIdx<0) return &BI_g_fRetVal;
	ref chref = GetCharacter(chrIdx);

	aref arSail;
	string groupName = ""+grNum;
	makearef(arSail,chref.ship.sails.(nodeName).(groupName));

	int hc_old = 0;
	if( CheckAttribute(arSail,"hc") )	hc_old = sti(arSail.hc);
	float fDmg_old = 0.0;
	if( CheckAttribute(arSail,"dmg") )	fDmg_old = stf(arSail.dmg);

	int itmp = hc_new;
	float sailDmgMax = GetCharacterShipSP(chref) * fSPow;

	float fTopDmg = sailDmgMax;
	if(itmp<mhc)	fTopDmg = GetNeedDmgFromHole(itmp+1,sailDmgMax,mhc) - 0.0001;
	if(fTopDmg>fDmg_old+fDmg)	fTopDmg = fDmg_old+fDmg;

	fDmg = fTopDmg-fDmg_old;
	if(fDmg<=0.0)	return &BI_g_fRetVal;
	chref.ship.SP = stf(chref.ship.SP)-fDmg;

	itmp = GetNeedHoleFromDmg(fTopDmg,sailDmgMax,mhc);
	if(itmp>hc_old)
	{
		BI_g_fRetVal = fDmg;
		arSail.hc = hc_new;
		arSail.hd = hdat_new;
	}
	else
	{
		BI_g_fRetVal = -fDmg;
		if( !CheckAttribute(arSail,"hc") )	arSail.hc = 0;
		if( !CheckAttribute(arSail,"hd") )	arSail.hd = 0;
	}

	arSail.mhc = mhc;
	arSail.sp = fSPow;
	arSail.dmg = fTopDmg;

	return &BI_g_fRetVal;
}

void procSetUsingAbility()
{
	int q;
	int chIdx = GetEventData();
	ref mainCh = GetMainCharacter();
	int mainIdx = sti(mainCh.index);
	aref aroot,arcur;
	string tmpStr;

	if( chIdx<0 || CharacterIsDead(GetCharacter(chIdx)) )
	{
		makearef(aroot,BattleInterface.AbilityIcons);
		q = GetAttributesNum(aroot);
		for(int i=0; i<q; i++)
		{
			arcur = GetAttributeN(aroot,i);
			arcur.enable = false;
		}
		return;
	}

	// для главного персонажа
	if(mainIdx==chIdx)
	{
		BattleInterface.AbilityIcons.Brander.enable			= false;
		BattleInterface.AbilityIcons.Troopers.enable		= false;

		BattleInterface.AbilityIcons.ImmediateReload.enable	= GetCharacterPerkUsing(mainCh,"ImmediateReload");
		BattleInterface.AbilityIcons.InstantBoarding.enable	= GetCharacterPerkUsing(mainCh,"InstantBoarding") && bAttack;

		BattleInterface.AbilityIcons.LightRepair.enable		= false;
		if(GetCharacterPerkUsing(mainCh,"LightRepair"))
		{	if(GetHullPercent(mainCh)<10.0 || GetSailPercent(mainCh)<10.0)
			{	BattleInterface.AbilityIcons.LightRepair.enable = true;
			}
		}
		BattleInterface.AbilityIcons.InstantRepair.enable	= CheckInstantRepairCondition(mainCh);
		BattleInterface.AbilityIcons.Turn180.enable			= GetCharacterPerkUsing(mainCh,"Turn180");
		BattleInterface.AbilityIcons.SandbankManeuver.enable= GetCharacterPerkUsing(mainCh,"SandbankManeuver");

		// Set items abilities
		q = FindQuestUsableItem(&arcur,0);
		while( q>0 )
		{
			tmpStr = arcur.id;
			if( GetCharacterItem(mainCh,arcur.id)>0 )
			{
				BattleInterface.AbilityIcons.(tmpStr).enable	= true;
				BattleInterface.AbilityIcons.(tmpStr).picNum	= arcur.quest.pic;
				BattleInterface.AbilityIcons.(tmpStr).texNum	= 9;
				BattleInterface.AbilityIcons.(tmpStr).event		= arcur.id;
				BattleInterface.AbilityIcons.(tmpStr).quest		= arcur.quest;
			}
			else
			{
				BattleInterface.AbilityIcons.(tmpStr).enable	= false;
			}
			q = FindQuestUsableItem(&arcur,q+1);
		}
	}

	else
	{
		BattleInterface.AbilityIcons.Brander.enable			= false;
		if(bAttack && GetRemovable(GetCharacter(chIdx)) && GetCharacterPerkUsing(mainCh,"Brander"))
			BattleInterface.AbilityIcons.Brander.enable		= true;

		BattleInterface.AbilityIcons.Troopers.enable		= GetCharacterPerkUsing(GetMainCharacter(),"Troopers");

		BattleInterface.AbilityIcons.ImmediateReload.enable	= false;
		BattleInterface.AbilityIcons.InstantBoarding.enable	= false;
		BattleInterface.AbilityIcons.LightRepair.enable		= false;
		BattleInterface.AbilityIcons.InstantRepair.enable	= false;
		BattleInterface.AbilityIcons.Turn180.enable			= false;
		BattleInterface.AbilityIcons.SandbankManeuver.enable= false;
	}
}

ref procCheckEnableLocator()
{
	BI_intRetValue = true;

	string comName = GetEventData();
	aref arLoc = GetEventData();

	if(comName=="BI_SailTo")
	{
		if( CheckAttribute(&AISea,"Island") && CheckAttribute(arLoc,"name") )
		{
			BI_intRetValue = Island_isGotoEnableLocal(AISea.Island,arLoc.name);
		}
	}

	return &BI_intRetValue;
}

ref procCheckEnableShip()
{
	BI_intRetValue = true;

	string comName = GetEventData();
	int cn = GetEventData();

	if(cn>=0)
	{
		switch(comName)
		{
		case "BI_InstantBoarding":
			BI_intRetValue = Character_IsAbordageEnable(GetCharacter(cn));
		break;
		}
	}

	return &BI_intRetValue;
}

void BI_ProcessControlPress()
{
	string ControlName = GetEventData();
// KK -->
	ref PChar = GetMainCharacter();
	if (HasSubStr(ControlName, "BI_Charge")) {
		if (GetCaracterShipCannonsType(PChar) == CANNON_TYPE_NONECANNON) return;
		if (bDisableAllCommands) return;
	}
	if (HasSubStr(ControlName, "Ship_") && bDisableAllCommands) return;
	if (HasSubStr(ControlName, "Telescope") && bDisableAllCommands) return;
// <-- KK

	//int tmpNameFileID = LanguageOpenFile("interface_strings.txt");// MAXIMUS 02.10.2006

//boal -->
	int chargeType=GOOD_BALLS;

	int ammoQty = 0;

	switch(ControlName)
	{
		case "BI_ChargeCannonballs":
			if (GetCurrentCharge() == 2) break; // KK
			ammoQty = GetCargoGoods(PChar, GOOD_BALLS);
			if ( ammoQty > 0 )
			{
				Log_SetStringToLog(XI_ConvertString("Balls"));
				chargeType=GOOD_BALLS;
				Ship_ChangeCharge(PChar, chargeType);
			}
			else
			{
				Log_SetStringToLog(TranslateString("","No Balls to Load"));// MAXIMUS 02.10.2006
			}
		break;
		case "BI_ChargeGrapes":
			if (GetCurrentCharge() == 3) break; // KK
			ammoQty = GetCargoGoods(PChar, GOOD_GRAPES);
			if ( ammoQty > 0 )
			{
				Log_SetStringToLog(XI_ConvertString("Grapes"));
				chargeType=GOOD_GRAPES;
				Ship_ChangeCharge(PChar, chargeType);
			}
			else
			{
				Log_SetStringToLog(TranslateString("","No Grapes to Load"));// MAXIMUS 02.10.2006
			}
		break;
		case "BI_ChargeKnippels":
			if (GetCurrentCharge() == 0) break; // KK
			ammoQty = GetCargoGoods(PChar, GOOD_KNIPPELS);
			if ( ammoQty > 0 )
			{
				Log_SetStringToLog(XI_ConvertString("Chains"));
				chargeType=GOOD_KNIPPELS;
				Ship_ChangeCharge(PChar, chargeType);
			}
			else
			{
				Log_SetStringToLog(TranslateString("","No Chains to Load"));// MAXIMUS 02.10.2006
			}
		break;
		case "BI_ChargeBombs":
				if (GetCurrentCharge() == 1) break; // KK
			ammoQty = GetCargoGoods(PChar, GOOD_BOMBS);
			if ( ammoQty > 0 )
			{
				//if (USE_REAL_CANNONS == 0) { // TIH allow quick charge to stolen bombs Aug31'06
				Log_SetStringToLog(XI_ConvertString("Bombs"));
				chargeType=GOOD_BOMBS;
				Ship_ChangeCharge(PChar, chargeType);
				//}
			}
			else
			{
				Log_SetStringToLog(TranslateString("","No Bombs to Load"));// MAXIMUS 02.10.2006
			}
		break;
	}
// boal <--
	if(ControlName=="TimeScale") 
	{
		// NK basetime 05-04-25 -->
		float basetime = 1.0;
		if(CheckAttribute(PChar,"basetime")) basetime = stf(PChar.basetime);
		if(IsPerkIntoList("TimeSpeed"))
		{
			SetTimeScale(1.0 * basetime);
			DelPerkFromActiveList("TimeSpeed");
		}
		else
		{
			SetTimeScale(GetSeaTimeScale() * basetime);
			AddPerkToActiveList("TimeSpeed");
		}
		// NK <--
	}
	//LanguageCloseFile(tmpNameFileID);// MAXIMUS 02.10.2006
}

ref procGetSRollSpeed()
{
	int chrIdx = GetEventData();
	BI_g_fRetVal = 0.0;
	if(chrIdx>=0) BI_g_fRetVal = GetRSRollSpeed(GetCharacter(chrIdx));
	return &BI_g_fRetVal;
}

float GetRSRollSpeed(ref chref)
{
	float fRollSpeed;
	if(USE_REAL_SAILING) { fRollSpeed = 0.2 + 0.05 * makefloat( GetCharacterSkill(chref,SKILL_SAILING) ); } //0.5  KNB
	else fRollSpeed = 0.5 + 0.05 * makefloat( GetCharacterSkill(chref,SKILL_SAILING) );
	int crewQ = GetCrewQuantity(chref);
	int crewMin = GetMinCrewQuantity(chref);
	if(crewQ<crewMin) fRollSpeed *= makefloat(crewQ)/makefloat(crewMin);
	return fRollSpeed;
}

ref BI_GetLandData()
{
	string attrName;
	aref arLoc, arIsl, arList;
	arLoc = GetEventData();

	BI_intNRetValue[0] = 0;
	BI_intNRetValue[1] = BI_RELATION_NEUTRAL;
	BI_intNRetValue[2] = -1;
	BI_intNRetValue[3] = -1;

	if( CheckAttribute(arLoc,"fort.model") )
	{
		BI_intNRetValue[0] = 1;
		int chrIdx = Fort_FindCharacter(AISea.Island,"reload",arLoc.name);
		if(chrIdx>=0)
		{
			switch( SeaAI_GetRelation(chrIdx,GetMainCharacterIndex()) )
			{
			case RELATION_FRIEND:	BI_intNRetValue[1] = BI_RELATION_FRIEND;	break;
			case RELATION_NEUTRAL:	BI_intNRetValue[1] = BI_RELATION_NEUTRAL;	break;
			case RELATION_ENEMY:	BI_intNRetValue[1] = BI_RELATION_ENEMY;		break;
			}
		}
	}

	if( CheckAttribute(arLoc,"tex") && CheckAttribute(arLoc,"pic") )
	{
		makearef( arIsl, Islands[FindIsland(AISea.Island)] );
		attrName = "InterfaceTextures." + arLoc.tex;
		if( CheckAttribute(arIsl,attrName) )
		{
			BI_intNRetValue[2] = AddTextureToList( &BattleInterface, arIsl.(attrName), sti(arIsl.(attrName).h), sti(arIsl.(attrName).v) );
			BI_intNRetValue[3] = sti(arLoc.pic);
		}
	}
	// NK EUROLANG -->
	/*if( CheckAttribute(arLoc,"label") ) {
		arLoc.labelLoc = LanguageConvertString(g_LocLngFileID,arLoc.label);
		if( arLoc.labelLoc == "" ) {
			Trace("Warning! Language: string <"+arLoc.label+"> hav`t translation into file <LocLables.txt>");
		}
	}*/
	// NK <--

	// Заглушка
	if( BI_intNRetValue[2]<0 || BI_intNRetValue[3]<0 )
	{
		BI_intNRetValue[2] = AddTextureToList( &BattleInterface, "battle_interface\LandTarget1.tga", 4, 2 ); // KK
		if( BI_intNRetValue[0]==0 ) {
			BI_intNRetValue[3] = 2; // KK
		} else {
			BI_intNRetValue[3] = 1; // KK
		}
	}

	return &BI_intNRetValue;
}

int GetTargChrIndex(int targNum, string locName)
{
	if(targNum==-1) {
		return Fort_FindCharacter(AISea.Island,"reload",locName);
	} else {
		return targNum;
	}
}

bool CheckSuccesfullBoard(ref rBoarderChr, ref rSieger)
{
	// skill = 1 -> k = 0.5; skill = 10 -> k = 2.0
	float k = 0.333 + GetSummonSkillFromName(rBoarderChr, SKILL_SNEAK)*0.167;

	// skill = 1 -> limit = 0.45 -> 0.2^0.5 (20%);   skill = 10 -> limit = 0.81 -> 0.9^2 (90%)
	float topLimit = 0.41 + GetSummonSkillFromName(rBoarderChr, SKILL_GRAPPLING)*0.04;

	if( pow(rand(1000)/1000.0, k) < topLimit ) return true;
	return false;
}

// LDH time display 17Sep06
#event_handler("DisplaySeaTimeEvent","procDisplaySeaTime");
void procDisplaySeaTime()
{
	ref mchr = GetMainCharacter();
	if (DISPLAY_SEA_TIME || CheckCharacterEquipByGroup(mchr, CLOCK_ITEM_TYPE) != "") // PB: Clocks
	{
		if (CheckAttribute(mchr, "BaseCurrentTime"))	// Test to see if we're still on deck
		{
			float fGetTime = GetTime();					// GetTime() updates every 5 game minutes
			int iSeaTime = GetSeaTime();				// GetSeaTime() returns approx number of seconds since sea started
			if (stf(mchr.BaseCurrentTime) != fGetTime)
			{
				mchr.CurrentTime = fGetTime;
				mchr.BaseCurrentTime = fGetTime;
				mchr.TimeSeconds = iSeaTime;
				Log_SetEternalString("Time: " + GetStringTime(stf(mchr.CurrentTime)));
			}
			if (iSeaTime >= sti(mchr.TimeSeconds)+60/TIMESCALAR_SEA)	// 12 seconds, this is approximate, but works
			{
				mchr.TimeSeconds = iSeaTime;
				float CurrentTime = stf(mchr.CurrentTime);
				CurrentTime += (1.0/60.0);								// add one minute to current time
				if (CurrentTime >= 24.0) CurrentTime -= 24.0;			// LDH 16Oct06 - 24:01 should be 00:01 for example
				mchr.CurrentTime = CurrentTime;
				Log_SetEternalString("Time: " + GetStringTime(CurrentTime));
			}
			PostEvent("DisplaySeaTimeEvent",250);	// when BaseCurrentTime attribute is deleted, this will stop calling itself
		}
	}
}

// KK -->
void SetUserIcons(string parent)
{
	ref mchr = GetMainCharacter();
	switch (parent)
	{
		case "BI_EnterDeck":
			int ndecks = GetCharacterShipCannonsDeckCount(mchr);
			int nholds = GetCharacterShipCargoHoldCount(mchr);
			BattleInterface.UserIcons.ui1.enable = false;
			BattleInterface.UserIcons.ui2.enable = false;
			BattleInterface.UserIcons.ui3.enable = false;
			BattleInterface.UserIcons.ui4.enable = true;
			BattleInterface.UserIcons.ui5.enable = GetCharacterShipCabin(mchr)!="Cabin_none";
			BattleInterface.UserIcons.ui6.enable = GetCharacterShipCQuarters(mchr)!="";
			BattleInterface.UserIcons.ui7.enable = (ndecks > 0);
			BattleInterface.UserIcons.ui8.enable = (ndecks > 2);
			BattleInterface.UserIcons.ui9.enable = (ndecks > 1);
			BattleInterface.UserIcons.ui10.enable = (nholds > 0);
			BattleInterface.UserIcons.ui11.enable = (nholds > 1);
		break;
		case "BI_Speed":
			BattleInterface.UserIcons.ui1.enable = true;
			BattleInterface.UserIcons.ui2.enable = true;
			BattleInterface.UserIcons.ui3.enable = true;
			BattleInterface.UserIcons.ui4.enable = false;
			BattleInterface.UserIcons.ui5.enable = false;
			BattleInterface.UserIcons.ui6.enable = false;
			BattleInterface.UserIcons.ui7.enable = false;
			BattleInterface.UserIcons.ui8.enable = false;
			BattleInterface.UserIcons.ui9.enable = false;
			BattleInterface.UserIcons.ui10.enable = false;
			BattleInterface.UserIcons.ui11.enable = false;
		break;
	}
}

string CheckDestinationType()
{
	aref LocatorRef = GetReloadMapRef(&arIslandReload, "name", sIslandLocator);
	if (CheckAttribute(LocatorRef, "go") == false || LocatorRef.go == "") return "";
	if (!CheckAttribute(Locations[FindLocation(LocatorRef.go)], "type")) return "";
	if(!CheckAttribute(Locations[FindLocation(LocatorRef.go)], "id")) return "";// MAXIMUS -->
	characters[GetMainCharacterIndex()].location.from_sea = LocatorRef.go;
	if(Locations[FindLocation(LocatorRef.go)].type=="port")
	{
		BattleInterface.Commands.LandPort.picNum			= 2;
		if(HasSubStr(Locations[FindLocation(LocatorRef.go)].id,"QC_")) { BattleInterface.Commands.LandPort.picNum			= 1; }
	}// MAXIMUS <--
	return Locations[FindLocation(LocatorRef.go)].type;
}
// <-- KK
