/*====================================================|START OF SKILLS-SECTION|====================================================*/
bool IsMainCharacter(ref chr)
{
	if(CheckAttribute(chr,"chr_ai.type") && chr.chr_ai.type==LAI_TYPE_PLAYER) return true;
	if(CheckAttribute(chr,"index") && sti(chr.index)==GetMainCharacterIndex()) return true;
	return false;
}

bool IsUsedAlliesModel(ref chr)
{
	if(!bAllies(chr))
	{
		if(IsUsedOfficerModel(chr))// for excluding twins-officers
		{
			trace("Officer's twin found!!!");
			return true;
		}
		if(IsUsedMainCharacterModel(chr))// for excluding main character's twins
		{
			trace("Main character's twin found!!!");
			return true;
		}
	}

	return false;
}

bool IsUsedMainCharacterModel(ref chr)
{
	if(!CheckAttribute(chr,"model")) return false;

	ref PChar = GetMainCharacter();
	string CharacterModel = chr.model;
	if(CharacterModel==PChar.model || CharacterModel==strcut(PChar.model,0,strlen(PChar.model)-3)) return true;

	return false;
}

bool IsUsedOfficerModel(ref chr)
{
	if(!CheckAttribute(chr,"model")) return false;
	if(CheckAttribute(chr,"Dialog.Filename"))
	{
		if(chr.Dialog.Filename!="Enc_Officer_dialog.c" && chr.Dialog.Filename!="Enc_Walker.c") return false;
	}

	ref PChar = GetMainCharacter();
	int i, j, tempIdx, tempNum;
	ref tempChar, tmpChar;

// ******* STEP 1/4: CHECKING OFFICERS *******
	for(i=1; i<4; i++)
	{
		tempIdx = GetOfficersIndex(PChar,i);
		if(tempIdx>=0)
		{
			tempChar = &characters[tempIdx];
			if(chr.model==tempChar.model) return true;
			if(chr.model=="Beatrise" && tempChar.model=="BeatriceA") return true;
			if(chr.model=="BeatriceA" && tempChar.model=="Beatrise") return true;
		}
	}

// ******* STEP 2/4: CHECKING COMPANIONS AND THEIR OFFICERS *******
	for(i=1; i<4; i++)
	{
		tempIdx = GetCompanionIndex(PChar,i);
		if(tempIdx>=0)
		{
			tempChar = &characters[tempIdx];
			if(chr.model==tempChar.model) return true;
			if(chr.model=="Beatrise" && tempChar.model=="BeatriceA") return true;
			if(chr.model=="BeatriceA" && tempChar.model=="Beatrise") return true;
			for(j=1; j<4; j++)
			{
				tempNum = GetOfficersIndex(tempChar,j);
				if(tempNum>=0)
				{
					tmpChar = &characters[tempNum];
					if(chr.model==tmpChar.model) return true;
					if(chr.model=="Beatrise" && tmpChar.model=="BeatriceA") return true;
					if(chr.model=="BeatriceA" && tmpChar.model=="Beatrise") return true;
				}
			}
		}
	}

// ******* STEP 3/4: CHECKING CAPTAINS ON SHORE LEAVE AND THEIR OFFICERS *******
	for(i=0; i<8; i++)
	{
		string tempstring1 = "port" + i;
		for(j=1; j<5; j++)
		{
			string tempstring2 = "slot" + j;
			if(CheckAttribute(PChar,"ShipBerthing."+tempstring1+"."+tempstring2+".status") && sti(PChar.ShipBerthing.(tempstring1).(tempstring2).status)==2)
			{
				tempIdx = sti(PChar.ShipBerthing.(tempstring1).(tempstring2).captainindex);
				tempChar = &characters[tempIdx];
				if(chr.model==tempChar.model) return true;
				if(chr.model=="Beatrise" && tempChar.model=="BeatriceA") return true;
				if(chr.model=="BeatriceA" && tempChar.model=="Beatrise") return true;
				for(int k=1; k<4; k++)
				{
					tempNum = GetOfficersIndex(tempChar,k);
					if(tempNum>=0)
					{
						tmpChar = &characters[tempNum];
						if(chr.model==tmpChar.model) return true;
						if(chr.model=="Beatrise" && tmpChar.model=="BeatriceA") return true;
						if(chr.model=="BeatriceA" && tmpChar.model=="Beatrise") return true;
					}
				}
			}
		}
	}

// ******* STEP 4/4: CHECKING NON-OFFICERS PASSENGERS *******
	for (i=0; i<GetPassengersQuantity(PChar); i++)
	{
		tempIdx = GetPassenger(PChar,i);
		if(tempIdx>=0)
		{
			tempChar = &characters[tempIdx];
			if(!IsOfficer(tempChar))
			{
				if(chr.model==tempChar.model) return true;
				if(chr.model=="Beatrise" && tempChar.model=="BeatriceA") return true;
				if(chr.model=="BeatriceA" && tempChar.model=="Beatrise") return true;
			}
		}
	}

	return false;
}

void AddPartyExpChar(ref chref, string expName, int _exp)
{
	if(!ownDeckStarted() && CheckAttribute(chref,"IsFantom") && sti(chref.IsFantom)==1) { return; }//MAXIMUS: fantoms not need to be updated (I think so)
	if(!CheckAttribute(chref,"index")) { return; }
	if(sti(chref.index)<0) { return; }
	int cn,cn2,i,j, myindex;
	myindex = sti(chref.index);
	float sxmult = 1.0 + GetOfficersPerkUsing(chref,"SharedExperience");
	AddCharacterExpNSChar(chref, expName, _exp);
	if(IsOfficer(chref) || IsCompanion(chref)) { chref = GetMainCharacter(); AddCharacterExpNSChar(chref, expName, _exp); }
	for(i=0; i < GetPassengersQuantity(chref); i++)
	{
		cn = GetPassenger(chref, i);
		if(cn == -1 || cn == myindex) continue;
		if(CheckAttribute(Characters[cn],"prisoned") && sti(Characters[cn].prisoned)) continue;
		if(IsOfficer(Characters[cn])) {AddCharacterExpNSChar(&Characters[cn], expName, _exp);}
		else {AddCharacterExpNSChar(&Characters[cn], expName, _exp * 0.5 * sxmult);}
	}
	if(GetCompanionQuantity(chref) > 1)
	{
		for(i=1; i < 4; i++)
		{
			cn = GetCompanionIndex(chref, i);
			if(cn == -1) continue;
			for(j=0; j<4; j++)
			{
				cn2 = GetOfficersIndex(&Characters[cn], j);
				if(cn2 == -1 || cn2 == myindex) continue;
				AddCharacterExpNSChar(&Characters[cn2], expName, _exp);
			}
		}
	}
}

int AddCharacterExpChar(ref _refCharacter, string expName, int _exp)
{
	if(!CheckAttribute(_refCharacter,"tmpExp") && !ownDeckStarted() && CheckAttribute(_refCharacter,"IsFantom") && sti(_refCharacter.IsFantom)==1) { return 0; }//MAXIMUS: fantoms not need to be updated (I think so)
	if(!CheckAttribute(_refCharacter,"index")) { return 0; }
	if(sti(_refCharacter.index)<0) { return 0; }
	int i, cn, myindex;
	myindex = sti(_refCharacter.index);
	AddCharacterExpNSChar(_refCharacter, expName, _exp);
	float sxmult = 1.0 + GetOfficersPerkUsing(_refCharacter,"SharedExperience");
	for(i=0; i < 4; i++)
	{
		cn = GetOfficersIndex(_refCharacter, i);
		if(cn == -1) { continue; }
		if(cn == myindex) { continue; }
		AddCharacterExpNSChar(&Characters[cn], expName, makeint(makefloat(_exp) * 0.5 * sxmult));
	}
	if(!CheckAttribute(_refCharacter,"Experience")) _refCharacter.Experience = 1;
	return sti(_refCharacter.Experience);
}

int AddCharacterExpNSChar(ref _refCharacter, string expName, int _exp)
{
	if(!CheckAttribute(_refCharacter,"tmpExp") && !ownDeckStarted() && CheckAttribute(_refCharacter,"IsFantom") && sti(_refCharacter.IsFantom)==1) { return 0; }//MAXIMUS: fantoms not need to be updated (I think so)
	if(!CheckAttribute(_refCharacter,"index")) { return 0; }
	if(sti(_refCharacter.index)<0) { return 0; }
	if(_exp < 1) return 0;
	if(CheckAttribute(_refCharacter,"tmpExp")) DeleteAttribute(_refCharacter,"tmpExp");
	//int tmpLangFileID = LanguageOpenFile("interface_strings.txt");
	float realExpFloat;
	bool bShown = true;
	if(!CheckAttribute(_refCharacter,"id")) { _refCharacter.id = "without_id"; }
	if(!CheckAttribute(_refCharacter,"rank")) { _refCharacter.rank = 1; }
	if(!CheckAttribute(_refCharacter,"skill.calc")) { _refCharacter.skill.calc = 0; }
	if(bAllies(_refCharacter)) { realExpFloat = makefloat(_exp*GetDifficultyLevel(GetCharacterDifficultyName(GetDifficulty()))); }
	else
	{
		realExpFloat = makefloat(_exp*1.3*GetDifficultyLevel(GetCharacterDifficultyName(GetDifficulty())));
		if(CheckAttribute(_refCharacter,"chr_ai.type"))
		{
			if(_refCharacter.chr_ai.type!=LAI_TYPE_BUILDING)
			{
				if(!CheckAttribute(_refCharacter,"resorted"))
				{
					if(CheckAttribute(_refCharacter, "perks.FreePoints") == true && sti(_refCharacter.perks.FreePoints)>0) // KK
					{
						ResortFreePerks(_refCharacter);
						_refCharacter.resorted = true;
					}
				}
			}
		}
	}
	if(!CheckAttribute(_refCharacter,"Experience")) _refCharacter.Experience = 1;
	int realExp = makeint(realExpFloat/2);
	int retVal = false;
	int nextExp = CalculateExperienceFromRank(sti(_refCharacter.rank)+1);
	bool bStop = false;
	int curExp = sti(_refCharacter.Experience) + realExp;
	if(curExp>nextExp) { if(_refCharacter.skill.calc<2) { curExp = sti(_refCharacter.Experience); bStop = true; } }
	_refCharacter.Experience = curExp;

	if(!CheckAttribute(_refCharacter,"Experience."+expName)) _refCharacter.Experience.(expName) = makeint(sti(Rand(19)+1)*1000);

	int chrSkill = makeint(sti(_refCharacter.Experience.(expName))/500);

	if(!bStop && LogsToggle && realExp > 10 * makeint(_refCharacter.rank) && realExp > 25 && !CheckAttribute(_refCharacter,"donotshowXP"))
	{
		if(sti(_refCharacter.index)==GetMainCharacterIndex()) { Log_SetStringToLog(GetMySimpleName(_refCharacter) + " " + TranslateString("","Gained") + " " + realExp + " " + XI_ConvertString("XP")); }
	}

	if(!CheckAttribute(_refCharacter,"skill."+expName)) { _refCharacter.skill.(expName) = 1; }
	else { if(sti(_refCharacter.skill.(expName))==0) { _refCharacter.skill.(expName) = 1; } }

	if(CheckAttribute(_refCharacter,"skill."+expName+".bonus")) { realExp = makeint(realExp*_refCharacter.skill.(expName).bonus); }
	realExp = makeint(realExp*makefloat(1+makefloat(sti(10/sti(_refCharacter.skill.(expName)))/10)));
	int curSkill = sti(_refCharacter.Experience.(expName)) + realExp;
	if(makeint(_exp)>=500) curSkill = sti(_refCharacter.Experience.(expName)) + makeint(realExp*0.5);

	int newSkill = makeint(curSkill/500);
	if(LogsToggle) { if(sti(_refCharacter.index)==GetMainCharacterIndex()) { if(newSkill>chrSkill) Log_SetStringToLog(GetMySimpleName(_refCharacter) + " " + TranslateString("","Gained") + " +" + (newSkill - chrSkill) + "% " + XI_ConvertString("to_skill") + " " + XI_ConvertString(expName)); } }

	int nextSkill = 50000;
	if(curSkill>=nextSkill)
	{
		if(curSkill==nextSkill) curSkill = 0;
		if(curSkill>nextSkill) curSkill = makeint(curSkill-nextSkill);
		if(sti(_refCharacter.skill.(expName))<10)
		{
			_refCharacter.skill.calc = sti(_refCharacter.skill.calc)+1;
			_refCharacter.skill.(expName) = sti(_refCharacter.skill.(expName)) + 1;
			if(LogsToggle) { Log_SetStringToLog(GetMySimpleName(_refCharacter) + " " + TranslateString("","Gained") + " " + XI_ConvertString("skill_level") + " " + XI_ConvertString(expName) + " - " + sti(_refCharacter.skill.(expName))); }
		}
	}
	if(sti(_refCharacter.skill.(expName))<10) _refCharacter.Experience.(expName) = curSkill;
	else _refCharacter.Experience.(expName) = "0";

	if(curExp>=nextExp && !bStop)
	{
		if(CheckAttribute(_refCharacter,"perks.FreePoints"))
		{
			int freePerks = 0;
			int charPerks = 0;
			int chrPerksQ = 0;
			aref arPerksRoot; makearef(arPerksRoot,ChrPerksList.list);
			chrPerksQ = GetAttributesNum(arPerksRoot);
			for(int i=0; i<chrPerksQ; i++)
			{
				string perkName = GetAttributeName(GetAttributeN(arPerksRoot,i));
				if(!CheckCharacterPerk(_refCharacter,perkName)) freePerks = freePerks +1;
				if(CheckCharacterPerk(_refCharacter,perkName)) charPerks = charPerks +1;
			}
			if(freePerks>0)
			{
				if(!bStop) { _refCharacter.perks.FreePoints = sti(_refCharacter.perks.FreePoints) + 1; }
				if(!bAllies(_refCharacter))
				{
					if(CheckAttribute(_refCharacter,"chr_ai.type"))
					{
						if(_refCharacter.chr_ai.type!=LAI_TYPE_BUILDING)
						{
							if(CheckAttribute(_refCharacter,"donotshowXP")) { bShown = false; }
							if(sti(_refCharacter.perks.FreePoints)>0) { SetNextPerkToCharacter(_refCharacter, expName, bShown); }
						}
					}
				}
			}
			else { _refCharacter.perks.FreePoints = sti(_refCharacter.perks.FreePoints); }
		}
		else
		{
			_refCharacter.perks.FreePoints = 1;
		}
		if(!bStop)
		{
			_refCharacter.rank = sti(_refCharacter.rank) + 1;
			nextExp = CalculateExperienceFromRank(sti(_refCharacter.rank)+1);
			ResetHP(&_refCharacter);
			_refCharacter.skill.calc = sti(_refCharacter.skill.calc) - 2;
			if(CheckAttribute(_refCharacter,"quest.officerprice")) _refCharacter.quest.officerprice = sti(_refCharacter.quest.officerprice) + 200 * OPRICE_LEVEL_MULT;
			retVal = true;
			Log_SetStringToLog(GetMySimpleName(_refCharacter) + " " + TranslateString("","has gained a new level! (Now level") + " " + _refCharacter.rank + ")");
			PlayStereoSound("interface\new_level.wav");
		}
		//LanguageCloseFile(tmpLangFileID);
	}
	if(retVal)
	{
		if(IsOfficer(_refCharacter) || IsCompanion(_refCharacter))
		{
			AddMsgToCharacter(_refCharacter,MSGICON_LEVELUP);
		}
	}
	return retVal;
}

void Ship_AddCharacterExpChar(ref rCharacter, string expName, int iExpQuantity)
{
	bool t = IsCompanion(rCharacter);
	bool ns;
	if(!t)
	{
		ns = CheckAttribute(rCharacter,"donotshowXP");
		if(!ns) { rCharacter.donotshowXP = true; }
	}
	rCharacter.tmpExp = true;//MAXIMUS: identifier for ships-owners. If NPC is fantom he will gain exp, but only during sea battle
	AddCharacterExpChar(rCharacter, expName, makeint(iExpQuantity));
	if(!t){ if(!ns) { DeleteAttribute(rCharacter,"donotshowXP"); } }

	if(IsMainCharacter(rCharacter))
	{
		fSeaExp = fSeaExp + iExpQuantity;
	}
}

int AllDaysCount;//MAXIMUS: calculates days amount (updating in calendar.c)

void InitAutoSkillsSystem(ref refCharacter, bool dailyUpdate)
{
	if(CheckAttribute(refCharacter,"corpse")) return;
	if(dailyUpdate && CheckAttribute(refCharacter,"index") && sti(refCharacter.index)==GetMainCharacterIndex()) return;
	if(dailyUpdate && bAllies(refCharacter)) return;
	if(!dailyUpdate && CheckAttribute(refCharacter,"autoskills") && refCharacter.autoskills==1) return;
	if(!CheckAttribute(refCharacter,"Experience")) { refCharacter.Experience = 1; }
	if(!CheckAttribute(refCharacter,"rank")) { refCharacter.rank = 1; }
	refCharacter.skill.calc = 2;
	int nextSkill = 50000;
	int skillsCalc = 0;
	if(SKILLS_UP_BONUS<10) SKILLS_UP_BONUS = 10;
	if(SKILLS_UP_BONUS>99) SKILLS_UP_BONUS = 99;
	float curSpeed = makefloat(stf(SKILLS_UP_BONUS+100)/100);
//MAXIMUS: Checks for last meeting with character. If player met with him more, than 1 day ago, character's skill-experience will increase (from +1% to +4%) depending on a difficulty level -->
	int numUp = sti(GetDataYear() + GetDataMonth() + AllDaysCount);
	int expUp = sti(GetDifficulty()*500);
	if(CheckAttribute(refCharacter,"locDate") && sti(numUp-sti(refCharacter.locDate))>0)
	{
		numUp = sti(numUp - sti(refCharacter.locDate));
		expUp = expUp*numUp;
	}
	else { expUp = 0; }// for fantoms and first time logined characters
//MAXIMUS: <--
	int bonusCalc = 0;
	int randBonus = -1;
	for(int c = 0; c < 10; c++)
	{
		if(CheckAttribute(refCharacter,"bonusCalc")) bonusCalc = sti(refCharacter.bonusCalc);
		else { refCharacter.bonusCalc = bonusCalc; }
		string curSkillName = GetSkillName(c);
		if(!CheckAttribute(refCharacter,"Experience."+curSkillName)) { refCharacter.experience.(curSkillName) = makeint(makeint(Rand(19)+1)*3000)); }
		else { refCharacter.experience.(curSkillName) = makeint(sti(refCharacter.experience.(curSkillName)) + expUp); }//MAXIMUS: skills increase automatically, depending on days counting
		
		if(!CheckAttribute(refCharacter,"skill."+curSkillName)) { refCharacter.skill.(curSkillName) = 1; }
		else { if(sti(refCharacter.skill.(curSkillName))==0) { refCharacter.skill.(curSkillName) = 1; } }
		if(sti(refCharacter.Experience.(curSkillName))>=nextSkill)
		{
			if(CheckAttribute(refCharacter,"skill."+curSkillName))
			{
				if(sti(refCharacter.skill.(curSkillName))<10)
				{
					refCharacter.skill.(curSkillName) = sti(refCharacter.skill.(curSkillName)) + 1;
					refCharacter.Experience.(curSkillName) = makeint(sti(refCharacter.Experience.(curSkillName))-nextSkill);
				}
				else
				{
					refCharacter.skill.(curSkillName) = sti(refCharacter.skill.(curSkillName));
					refCharacter.Experience.(curSkillName) = "0";
				}
			}
		}
		if(!CheckAttribute(refCharacter,"perks.FreePoints")) { refCharacter.perks.FreePoints = 1; }
		if(GetCharacterindex(refCharacter.id)==GetMainCharacterIndex()) continue;
		if(bAllies(refCharacter)) continue;
		if(CheckAttribute(refCharacter,"chr_ai.type"))
		{
			if(refCharacter.chr_ai.type!=LAI_TYPE_BUILDING)
			{
				if(!CheckAttribute(refCharacter,"quest.officerprice"))
				{
					if(GetLevel(refCharacter)>=3)
					{
						int freePerks = 0;
						int usedPerks = 0;
						aref arPerksRoot; makearef(arPerksRoot,ChrPerksList.list);
						for(int i=0; i<GetAttributesNum(arPerksRoot); i++)
						{
							string perkName = GetAttributeName(GetAttributeN(arPerksRoot,i));
							if(!CheckCharacterPerk(refCharacter,perkName)) freePerks = freePerks +1;
							else usedPerks = usedPerks +1;
						}
						if(freePerks>=3)
						{
							if(sti(refCharacter.perks.FreePoints)==0) { refCharacter.perks.FreePoints = makeint(Rand(2)+1); }
						}
					}
					if(CheckAttribute(refCharacter,"perks.FreePoints") && sti(refCharacter.perks.FreePoints)>0) { SetNextPerkToCharacter(refCharacter, curSkillName, false); }
				}
			}
		}
		refCharacter.autoskills = 1;
		if(sti(refCharacter.skill.(curSkillName))>1) { skillsCalc = skillsCalc + sti(refCharacter.skill.(curSkillName)) - 1; }
		if(sti(refCharacter.bonusCalc)<2 && randBonus==-1) { randBonus = Rand(9); }
		if(sti(refCharacter.bonusCalc)<2 && CheckAttribute(refCharacter,"skill."+curSkillName+".bonus") && stf(refCharacter.skill.(curSkillName).bonus)>1.0)
		{
			refCharacter.bonusCalc = sti(refCharacter.bonusCalc)+1;
			if(randBonus==c) { randBonus = c-1; }
		}
	}
	if(sti(refCharacter.bonusCalc)<2 && randBonus>=0)
	{
		string bonusSkillName = GetSkillName(randBonus);
		refCharacter.skill.(bonusSkillName).bonus = curSpeed;
		bonusSkillName = GetRandSkillName(refCharacter);
		refCharacter.skill.(bonusSkillName).bonus = curSpeed;
	}
	if(!CheckAttribute(refCharacter,"Money")) { refCharacter.Money = GetRandCharMoney(refCharacter, makeint(Rand(15)+10)); }
	else
	{
		if(sti(refCharacter.Money)==0) { refCharacter.Money = GetRandCharMoney(refCharacter, makeint(Rand(15)+10)); }
	}
	skillsCalc = makeint(skillsCalc/2);
	refCharacter.rank = sti(1 + skillsCalc);
	refCharacter.Experience = CalculateExperienceFromRank(sti(refCharacter.rank));
	if(!CheckAttribute(refCharacter,"quest.officerprice"))
	{
		LAi_SetCurHPMax(refCharacter);
		ResetHP(refCharacter);
	}
	refCharacter.locDate = sti(GetDataYear() + GetDataMonth() + AllDaysCount);
}

string GetRandSkillName(ref chr)
{
	string SkillName = "";
	int skillNum = Rand(9);
	for(int c = 0; c < 10; c++)
	{
		string curSkill = GetSkillName(c);
		if(skillNum==c)
		{
			if(!CheckAttribute(chr,"skill."+curSkill+".bonus")) { SkillName = curSkill; }
			else
			{
				if(skillNum<=3) { skillNum = skillNum+sti(Rand(2)+1); }
				else { if(skillNum<=9) { skillNum = skillNum-sti(Rand(8)+1); } }
				SkillName = GetSkillName(skillNum);
			}
			return SkillName;
		}
	}
	return "Leadership";
}

string perksInfo, charInfo, tempInfo;

void SetNextPerkToCharacter(ref refCharacter, string skillName, bool bShown)
{
	int tmpLangFileID = LanguageOpenFile("AbilityDescribe.txt");
	//int tmpTextFileID = LanguageOpenFile("interface_strings.txt");
	int usedPerk = 0;
	charInfo = GetMyFullName(refCharacter) + " " + TranslateString("","GainedPerk") + " ";
	tempInfo = "";
	perksInfo = "";
	if(skillName==SKILL_DEFENCE) { if(SendMessage(GetMainCharacter(), "ls", MSG_CHARACTER_EX_MSG, "IsFightMode")!=0) skillName = SKILL_FENCING; }
	if(skillName==SKILL_DEFENCE) { if(CheckAttribute(objLandInterface,"data.riskAlarm") && objLandInterface.data.riskAlarm==1) skillName = SKILL_FENCING; }
	if(sti(refCharacter.perks.FreePoints)>0)
	{
		switch(skillName)
		{
			case SKILL_LEADERSHIP: if(SetPerks_Leadership(refCharacter, true)>0) { usedPerk = SetPerks_Leadership(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); } break;
			case SKILL_FENCING: if(SetPerks_Blade(refCharacter, true)>0) { usedPerk = SetPerks_Blade(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); } break;
			case SKILL_SAILING: if(SetPerks_Navigator(refCharacter, true)>0) { usedPerk = SetPerks_Navigator(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); } break;
			case SKILL_ACCURACY: if(SetPerks_Gun(refCharacter, true)>0) { usedPerk = SetPerks_Gun(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); } break;
			case SKILL_CANNONS: if(SetPerks_Cannon(refCharacter, true)>0) { usedPerk = SetPerks_Cannon(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); } break;
			case SKILL_GRAPPLING: if(SetPerks_Grappling(refCharacter, true)>0) { usedPerk = SetPerks_Grappling(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); } break;
			case SKILL_REPAIR: if(SetPerks_QMaster(refCharacter, true)>0) { usedPerk = SetPerks_QMaster(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); } break;
			case SKILL_DEFENCE: if(SetPerks_Defense(refCharacter, true)>0) { usedPerk = SetPerks_Defense(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); } break;
			case SKILL_COMMERCE: if(SetPerks_QMaster(refCharacter, true)>0) { usedPerk = SetPerks_QMaster(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); } break;
			case SKILL_SNEAK: if(SetPerks_Leadership(refCharacter, true)>0) { usedPerk = SetPerks_Leadership(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); } break;
		}
		if(usedPerk>0) { if(LogsToggle && bShown) { Log_SetStringToLog(charInfo + tempInfo); } }
		LanguageCloseFile(tmpLangFileID);
		//LanguageCloseFile(tmpTextFileID);
	}
	if(usedPerk<=0) { ResortFreePerks(refCharacter); }
}

void ResortFreePerks(ref refCharacter)
{
	int tmpLangFileID = LanguageOpenFile("AbilityDescribe.txt");
	//int tmpTextFileID = LanguageOpenFile("interface_strings.txt");
	int usedPerk = 0;
	charInfo = GetMySimpleName(refCharacter) + " " + TranslateString("","GainedPerk") + " ";
	if(sti(refCharacter.perks.FreePoints)>0)
	{
		if(SetPerks_Blade(refCharacter, true)>0) { usedPerk = SetPerks_Blade(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); }
		else
		{
			if(SetPerks_Gun(refCharacter, true)>0) { usedPerk = SetPerks_Gun(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); }
			else
			{
				if(SetPerks_Leadership(refCharacter, true)>0) { usedPerk = SetPerks_Leadership(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); }
				else
				{
					if(SetPerks_Navigator(refCharacter, true)>0) { usedPerk = SetPerks_Navigator(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); }
					else
					{
						if(SetPerks_Cannon(refCharacter, true)>0) { usedPerk = SetPerks_Cannon(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); }
						else
						{
							if(SetPerks_Grappling(refCharacter, true)>0) { usedPerk = SetPerks_Grappling(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); }
							else
							{
								if(SetPerks_Defense(refCharacter, true)>0) { usedPerk = SetPerks_Defense(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); }
								else
								{
									if(SetPerks_QMaster(refCharacter, true)>0) { usedPerk = SetPerks_QMaster(refCharacter, false); tempInfo = LanguageConvertString(tmpLangFileID,perksInfo); }
								}
							}
						}
					}
				}
			}
		}
	}
	LanguageCloseFile(tmpLangFileID);
	//LanguageCloseFile(tmpTextFileID);
}

int SetPerks_Leadership(ref Npchar, bool bCheck)
{
	int usedPerk = 0;
	if(!CheckAttribute(Npchar,"Perks.List.SharedExperience")) { perksInfo = "SharedExperience"; if(!bCheck) { Npchar.Perks.List.SharedExperience = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
	else
	{ 
		if(!CheckAttribute(Npchar,"Perks.List.IronWill")) { perksInfo = "IronWill"; if(!bCheck) { Npchar.Perks.List.IronWill = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
		else { return 0; }
	}

	return usedPerk;
}

int SetPerks_Blade(ref Npchar, bool bCheck)
{
	int usedPerk = 0;
	if(!CheckAttribute(Npchar,"Perks.List.BasicDefense")) { perksInfo = "BasicDefense"; if(!bCheck) { Npchar.Perks.List.BasicDefense = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
	else
	{
		if(!CheckAttribute(Npchar,"Perks.List.AdvancedDefense")) { perksInfo = "AdvancedDefense"; if(!bCheck) { Npchar.Perks.List.AdvancedDefense = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
		else
		{
			if(!CheckAttribute(Npchar,"Perks.List.Toughness")) { perksInfo = "Toughness"; if(!bCheck) { Npchar.Perks.List.Toughness = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
			if(!CheckAttribute(Npchar,"Perks.List.Rush")) { perksInfo = "Rush"; if(!bCheck) { Npchar.Perks.List.Rush = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
			if(!CheckAttribute(Npchar,"Perks.List.CriticalHit")) { perksInfo = "CriticalHit"; if(!bCheck) { Npchar.Perks.List.CriticalHit = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
			else
			{
				if(!CheckAttribute(Npchar,"Perks.List.SwordplayProfessional")) { perksInfo = "SwordplayProfessional"; if(!bCheck) { Npchar.Perks.List.SwordplayProfessional = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
				else { return 0; }
			}
		}
	}

	return usedPerk;
}

int SetPerks_Gun(ref Npchar, bool bCheck)
{
	int usedPerk = 0;
	if(!CheckAttribute(Npchar,"Perks.List.Gunman")) { perksInfo = "Gunman"; if(!bCheck) { Npchar.Perks.List.Gunman = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
	else
	{
		if(!CheckAttribute(Npchar,"Perks.List.GunProfessional")) { perksInfo = "GunProfessional"; if(!bCheck) { Npchar.Perks.List.GunProfessional = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
		else { return 0; }
	}

	return usedPerk;
}

int SetPerks_Cannon(ref Npchar, bool bCheck)
{
	int usedPerk = 0;
	if(!CheckAttribute(Npchar,"Perks.List.FastReload")) { perksInfo = "FastReload"; if(!bCheck) { Npchar.Perks.List.FastReload = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
	else
	{
		if(!CheckAttribute(Npchar,"Perks.List.ImmediateReload")) { perksInfo = "ImmediateReload"; if(!bCheck) { Npchar.Perks.List.ImmediateReload = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
	}

	if(!CheckAttribute(Npchar,"Perks.List.HullDamageUp")) { perksInfo = "HullDamageUp"; if(!bCheck) { Npchar.Perks.List.HullDamageUp = "1"; } usedPerk = 1; return usedPerk; }
	if(!CheckAttribute(Npchar,"Perks.List.SailsDamageUp")) { perksInfo = "SailsDamageUp"; if(!bCheck) { Npchar.Perks.List.SailsDamageUp = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
	if(!CheckAttribute(Npchar,"Perks.List.CrewDamageUp")) { perksInfo = "CrewDamageUp"; if(!bCheck) { Npchar.Perks.List.CrewDamageUp ="1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
	if(!CheckAttribute(Npchar,"Perks.List.perkLongRangeGrappling")) { perksInfo = "LongRangeGrappling"; if(!bCheck) { Npchar.Perks.List.perkLongRangeGrappling ="1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }

	if(sti(Npchar.Perks.List.HullDamageUp)+sti(Npchar.Perks.List.SailsDamageUp)+sti(Npchar.Perks.List.CrewDamageUp)>2)
	{
		if(!CheckAttribute(Npchar,"Perks.List.CriticalShoot")) { perksInfo = "CriticalShoot"; if(!bCheck) { Npchar.Perks.List.CriticalShoot = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
		else
		{
			if(!CheckAttribute(Npchar,"Perks.List.LongRangeShoot")) { perksInfo = "LongRangeShoot"; if(!bCheck) { Npchar.Perks.List.LongRangeShoot ="1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
			else
			{
				if(!CheckAttribute(Npchar,"Perks.List.CannonProfessional")) { perksInfo = "CannonProfessional"; if(!bCheck) { Npchar.Perks.List.CannonProfessional ="1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
				else { return 0; }
			}
		}
	}

	return usedPerk;
}

int SetPerks_Navigator(ref Npchar, bool bCheck)
{
	int usedPerk = 0;
	if(!CheckAttribute(Npchar,"Perks.List.ShipSpeedUp")) { perksInfo = "ShipSpeedUp"; if(!bCheck) { Npchar.Perks.List.ShipSpeedUp = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
	else
	{
		if(!CheckAttribute(Npchar,"Perks.List.ShipTurnRateUp")) { perksInfo = "ShipTurnRateUp"; if(!bCheck) { Npchar.Perks.List.ShipTurnRateUp = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
		else
		{
			if(!CheckAttribute(Npchar,"Perks.List.Turn180")) { perksInfo = "Turn180"; if(!bCheck) { Npchar.Perks.List.Turn180 = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
			else
			{
				if(!CheckAttribute(Npchar,"Perks.List.SandbankManeuver")) { perksInfo = "SandbankManeuver"; if(!bCheck) { Npchar.Perks.List.SandbankManeuver = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
				else
				{
					if(!CheckAttribute(Npchar,"Perks.List.StormProfessional")) { perksInfo = "StormProfessional"; if(!bCheck) { Npchar.Perks.List.StormProfessional = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
					else
					{
						if(!CheckAttribute(Npchar,"Perks.List.SailingProfessional")) { perksInfo = "SailingProfessional"; if(!bCheck) { Npchar.Perks.List.SailingProfessional = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
						else { return 0; }
					}
				}
			}
		}
	}

	return usedPerk;
}

int SetPerks_Grappling(ref Npchar, bool bCheck)
{
	int usedPerk = 0;
	bool tmp = false;
	if(!CheckAttribute(Npchar,"Perks.List.LongRangeGrappling")) tmp = true;
	else { if(Npchar.Perks.List.LongRangeGrappling != "1") tmp = true;}
	if(tmp) { perksInfo = "LongRangeGrappling"; if(!bCheck) { Npchar.Perks.List.LongRangeGrappling = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
	else
	{
		tmp = false;
		if(!CheckAttribute(Npchar,"Perks.List.GrapplingProfessional")) tmp = true;
		else { if(Npchar.Perks.List.GrapplingProfessional != "1") tmp = true; }
		if(tmp) { perksInfo = "GrapplingProfessional"; if(!bCheck) { Npchar.Perks.List.GrapplingProfessional = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
		else
		{
			if(!CheckAttribute(Npchar,"Perks.List.Brander")) { perksInfo = "Brander"; if(!bCheck) { Npchar.Perks.List.Brander = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
			else
			{
				if(!CheckAttribute(Npchar,"Perks.List.Musketsshoot")) { perksInfo = "Musketsshoot"; if(!bCheck) { Npchar.Perks.List.Musketsshoot = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
				else
				{
					if(!CheckAttribute(Npchar,"Perks.List.Instantboarding")) { perksInfo = "Instantboarding"; if(!bCheck) { Npchar.Perks.List.Instantboarding = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
					else
					{
						if(!CheckAttribute(Npchar,"Perks.List.Troopers")) { perksInfo = "Troopers"; if(!bCheck) { Npchar.Perks.List.Troopers = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
						else { return 0; }
					}
				}
			}
		}
	}

	return usedPerk;
}

int SetPerks_Defense(ref Npchar, bool bCheck)
{
	int usedPerk = 0;
	bool tmp = false;
	if(!CheckAttribute(Npchar,"Perks.List.BasicBattleState")) tmp = true;
	else { if(Npchar.Perks.List.BasicBattleState != "1") tmp = true;}
	if(tmp) { perksInfo = "BasicBattleState"; if(!bCheck) { Npchar.Perks.List.BasicBattleState = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
	else
	{
		tmp = false;
		if(!CheckAttribute(Npchar,"Perks.List.AdvancedBattleState")) tmp = true;
		else { if(Npchar.Perks.List.AdvancedBattleState != "1") tmp = true;}
		if(tmp) { perksInfo = "AdvancedBattleState"; if(!bCheck) { Npchar.Perks.List.AdvancedBattleState = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
		else 
		{
			tmp = false;
			if(!CheckAttribute(Npchar,"Perks.List.ShipDefenseProfessional")) tmp = true;
			else { if(Npchar.Perks.List.ShipDefenseProfessional != "1") tmp = true;}
			if(tmp) { perksInfo = "ShipDefenseProfessional"; if(!bCheck) { Npchar.Perks.List.ShipDefenseProfessional = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
			else { return 0; }
		}
	}

	return usedPerk;
}

int SetPerks_QMaster(ref Npchar, bool bCheck)
{
	int usedPerk = 0;
	if(!CheckAttribute(Npchar,"Perks.List.LightRepair")) { perksInfo = "LightRepair"; if(!bCheck) { Npchar.Perks.List.LightRepair = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
	else
	{
		if(!CheckAttribute(Npchar,"Perks.List.InstantRepair")) { perksInfo = "InstantRepair"; if(!bCheck) { Npchar.Perks.List.InstantRepair = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
	}
	if(!CheckAttribute(Npchar,"Perks.List.Trustworthy")) { perksInfo = "Trustworthy"; if(!bCheck) { Npchar.Perks.List.Trustworthy = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
	if(!CheckAttribute(Npchar,"Perks.List.BasicCommerce")) { perksInfo = "BasicCommerce"; if(!bCheck) { Npchar.Perks.List.BasicCommerce = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
	else
	{
		if(!CheckAttribute(Npchar,"Perks.List.AdvancedCommerce")) { perksInfo = "AdvancedCommerce"; if(!bCheck) { Npchar.Perks.List.AdvancedCommerce = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
		else
		{
			if(!CheckAttribute(Npchar,"Perks.List.BasicLandOwner")) { perksInfo = "BasicLandOwner"; if(!bCheck) { Npchar.Perks.List.BasicLandOwner = "1"; Npchar.perks.FreePoints = sti(Npchar.perks.FreePoints) - 1; } usedPerk = 1; return usedPerk; }
			else { return 0; }
		}
	}

	return usedPerk;
}

void DailySkillsUpdate()
{
	for(int i=0; i<CHARACTERS_QUANTITY; i++)
	{
		ref curChar = GetCharacter(i);
		if(curChar!=GetMainCharacter())
		{
			if(!IsCompanion(curChar)) { if(!IsOfficer(curChar)) { if(!IsOfficerCompanion(curChar)) { if(!IsOnShoreLeave(curChar)) { if(!IsOfficerOnShoreLeave(curChar)) { if(CheckAttribute(curChar,"skill")) { if(CheckAttribute(curChar,"sex")) { if(CheckAttribute(curChar,"chr_ai.type")) { if(curChar.chr_ai.type!=LAI_TYPE_BUILDING) { InitAutoSkillsSystem(curChar, true); } } } } } } } } }
		}
	}
}

string GetCharacterDifficultyName(int d)
{                             
	string retstr = "Unknown";
	switch(d)
	{
		case 1: retstr = "Apprentice"; break;
		case 2: retstr = "Journeyman"; break;
		case 3: retstr = "Adventurer"; break;
		case 4: retstr = "Swashbuckler"; break;
	}
	return retstr;
}

float GetDifficultyLevel(string difName)
{
	float difNum = 1.0;
	switch(difName)
	{
		case "Journeyman": difNum = 0.75; break;
		case "Adventurer": difNum = 0.5; break;
		case "Swashbuckler": difNum = 0.25; break;
	}
	return makefloat(difNum);
}

bool bAllies(ref refCharacter)
{
	if(!CheckAttribute(refCharacter,"index")) return false;
	if(sti(refCharacter.index)==-1) return false;

	if(IsMainCharacter(refCharacter)) return true;
	if(IsCompanion(refCharacter)) return true;
	if(IsOfficer(refCharacter)) return true;
	if(IsOfficerCompanion(refCharacter)) return true;
	if(IsPassenger(refCharacter)) return true;
	if(IsOnShoreLeave(refCharacter)) return true;
	if(IsOfficerOnShoreLeave(refCharacter)) return true;
	return false;
}
/*====================================================|END OF SKILLS-SECTION|====================================================*/

/*=======================================================|QUESTS  SECTION|=======================================================*/
string GenerateMR(ref PChar, ref NPChar)
{
	PChar.quest.RemoveMRs.win_condition.l1 = "ExitFromLocation";
	PChar.quest.RemoveMRs.win_condition.l1.location = PChar.location;
	PChar.quest.RemoveMRs.win_condition = "RemoveMRs";

	return XI_ConvertString("MR_1") + " " + GetMyRespectfullyName(PChar) + XI_ConvertString("MR_2") + " " + XI_ConvertString(NPChar.currentMR.relationtype) + " " + Characters[GetCharacterIndex(NPChar.currentMR)].name + XI_ConvertString("MR_3");
}

string GenerateTradeQuest(ref pchar, int iTradeNation, int iTradeGoods, float fprice, float tprice, bool bMain)// moved here from traders dialogs
{
	string sNation = "";
//MAXIMUS -[such functions must be universal (IMHO), if we are planning to make a real Caribbean in the future]->
	string friendlyTowns = "";
	string pirateTowns = "";
	for(int i=0; i<TOWNS_QUANTITY; i++)
	{
		if(!CheckAttribute(&Towns[i],"id")) continue;
		if(!CheckAttribute(&Towns[i],"nation")) continue;
		if(CheckAttribute(&Towns[i],"skiptrade") && Towns[i].skiptrade==true) continue;//MAXIMUS: added for some towns (such as St. John's on Antigua)
		if(Towns[i].nation!=iTradeNation) continue;
		friendlyTowns = StoreString(friendlyTowns,Towns[i].id);
	}
	if(friendlyTowns!="")
	{
		sNation = GetRandSubString(friendlyTowns);
		while(sNation=="" || HasSubStr(sNation,",") || GetIslandIDFromTown(sNation)==GetIslandIDFromTown(GetCurrentTownId())) { sNation = GetRandSubString(friendlyTowns); }
	}
	else { sNation = "Quebradas Costillas"; }//MAXIMUS: Quebradas Costillas - why some trader can't trade with pirates?
	int iQuantityGoods = GetSquadronFreeSpace(pchar, iTradeGoods) * 4/5; // NK ratio 05-05-12
	float fDistance = GetTownDistance2D(GetCurrentTown(), GetTownFromID(sNation));
	float fWeight = GetGoodWeightByType(iTradeGoods, iQuantityGoods);
	// money was ((iQuantityGoods *10+99)/100)*100;
	// should give ~40k (at scl 0.02) for 2000 goods brought 1000 distance, and you get a commission on the sale.
	float pricediff = tprice - fprice;
	if(pricediff<1) pricediff = 1.0;
	int iMoney = round(GetCharPriceMod(&PChar, PRICE_TYPE_SELL, true) * fDistance * fWeight * TRADEQUEST_DIST_SCL + pricediff * iQuantityGoods * TRADEQUEST_COMMISSION);
	int iTradeExp = round(fDistance * sqrt(fWeight) * TRADEQUEST_DIST_SCL * 10);
	int iDaysExpired = 20 + makeint(fDistance/100);
	// NK <--

	if(!bMain) return "";

	pchar.quest.generate_trade_quest.iTradeGoods = iTradeGoods;
	pchar.quest.generate_trade_quest.iQuantityGoods = iQuantityGoods;
	pchar.quest.generate_trade_quest.iMoney = iMoney;
	pchar.quest.generate_trade_quest.iTradeExp = iTradeExp;
	pchar.quest.generate_trade_quest.iTradeNation = iTradeNation;
	//MAXIMUS -->
	pchar.quest.generate_trade_quest.iTradeColony = sNation;
	int tmpSeaFileID = LanguageOpenFile("ShipEatGood.txt");
	pchar.quest.generate_trade_quest.iGoodName = LanguageConvertString(tmpSeaFileID,"seg_"+Goods[makeint(iTradeGoods)].name);
	LanguageCloseFile(tmpSeaFileID);
	if(LoadSegment("characters\init\StoresOwners.c"))
	{
		CreateStoresOwners(sti(pchar.firststore));
		UnloadSegment("characters\init\StoresOwners.c");
	}
	pchar.quest.generate_trade_quest.iStoreOwner = GetMySimpleName(characterFromID(GetStoreOwner(sNation)));
	//MAXIMUS <--

	return XI_ConvertString(sNation);
}

void TradeQuestDone()
{
	ref PChar = GetMainCharacter();

	if(AUTO_SKILL_SYSTEM)
	{
		AddPartyExpChar(PChar, "Leadership", (makeint(PChar.quest.generate_trade_quest.iTradeExp)/10));
		AddPartyExpChar(PChar, "Commerce", makeint(PChar.quest.generate_trade_quest.iTradeExp));
		AddPartyExpChar(PChar, "Sneak", (makeint(PChar.quest.generate_trade_quest.iTradeExp)/100));
	}
	else { AddPartyExp(PChar, (makeint(PChar.quest.generate_trade_quest.iTradeExp))); }
	AddMoneyToCharacter(PChar, makeint(PChar.quest.generate_trade_quest.iMoney));
	PlayStereoSound("INTERFACE\took_item.wav");
	PChar.quest.generate_trade_quest_progress = "";
	PChar.quest.generate_trade_quest.over = "yes";
	RemoveCharacterGoods(PChar, makeint(PChar.quest.generate_trade_quest.iTradeGoods), makeint(PChar.quest.generate_trade_quest.iQuantityGoods));
}

void KillPirateQuestDone()
{
	ref PChar = GetMainCharacter();

	if(AUTO_SKILL_SYSTEM)
	{
		AddPartyExpChar(pchar, "Leadership", 1500);
		AddPartyExpChar(pchar, "Sneak", 15);
	}
	else { AddPartyExp(pchar, 1500); }
	PlayStereoSound("INTERFACE\took_item.wav");
	AddMoneyToCharacter(pchar, makeint(pchar.quest.generate_kill_quest.money));
	AddDialogExitQuest("kill_pirate_refused_2");
	ChangeCharacterReputation(pchar, 1);
	pchar.quest.generate_kill_quest = "wait_timer";
}

extern int CreateStoresOwners(int n);

void GenerateTreasureQuest(ref PChar, ref NPChar, int sum)
{
	string sea_location, treasure_location, destination, attackers_location;
	string numquest, treasure_locator, attackers_locator;
	int Calc_luck = Makeint(NPchar.skill.sneak);
	switch(Rand(10))  // GENERATE DESTINATION
	{
		case 0 :
			treasure_location = "Oxbay_Jungle_02"; treasure_locator="citizen04";
 			attackers_location = treasure_location; attackers_locator = treasure_locator;
			numquest="8"; destination = "Oxbay";
		break;
		case 1 :
			treasure_location = "Dungeon 1"; treasure_locator="randitem1";
			attackers_location = ""; attackers_locator = "";
			numquest="9"; destination = "Oxbay";
		break;
		case 2 :
			treasure_location = "Conceicao_Grot"; treasure_locator="randitem1";
			attackers_location = "Conceicao_shore_02"; attackers_locator = "locator14";
			numquest="10"; destination = "Conceicao";
		break;
		case 3 :
			treasure_location = "Hispaniola_grot3"; treasure_locator="randitem1";
			attackers_location = "Hispaniola_passage"; attackers_locator = "goto7";
			numquest="1"; destination = "Hispaniola";
		break;
		case 4 :
			treasure_location = "Turks_shore_ship"; treasure_locator="randitem1";
			attackers_location = "Turks_shore_01"; attackers_locator = "goto1";
			numquest="2"; destination = "Turks";
		break;
		case 5 :
			treasure_location = "Cuba_Shore_01"; treasure_locator="randitem1";
			attackers_location = treasure_location; attackers_locator = "locator5";
			numquest="3"; destination = "Cuba";
		break;
		case 6 :
			treasure_location = "Turks_Cave_Exit_02"; treasure_locator="goto4";
			attackers_location = treasure_location; attackers_locator = "goto5";
			numquest="4"; destination = "Turks";
		break;
		case 7 :
			treasure_location = "Cayman_Grot_01"; treasure_locator="randitem1";
			attackers_location = "Cayman_Jungle_06"; attackers_locator = "goto5";
			numquest="5"; destination = "Cayman";
		break;
		case 8 :
			treasure_location = "Cayman_Grot_02"; treasure_locator="randitem4";
			attackers_location = "Cayman_Jungle_08"; attackers_locator = "goto9";
			numquest="6"; destination = "Cayman";
		break;
		case 9 :
			treasure_location = "Guadeloupe_Lighthouse"; treasure_locator="randitem1";
			attackers_location = treasure_location; attackers_locator = "goto22";
			numquest="7"; destination = "Guadeloupe";
		break;
		case 10 :
			treasure_location = "Hispaniola_shore_02"; treasure_locator="citizen04";
			attackers_location = treasure_location; attackers_locator = "citizen06";
			numquest="11"; destination = "Hispaniola";
		break;
	}
	Group_DelCharacter("Story_Pirate", "Quest pirate");
	Group_deleteGroup("Story_Pirate");
	if(rand(Makeint(Pchar.skill.sneak))>0)
	{
		GeneratePirateQuest(NPChar); // KK
		Characters[GetCharacterIndex("Quest pirate")].nation=PIRATE;
		SetCharacterRelationBoth(GetCharacterIndex("Quest pirate"),GetMainCharacterIndex(),RELATION_ENEMY);
		Group_CreateGroup("Story_Pirate");
		Group_AddCharacter("Story_Pirate", "Quest pirate");
		Group_SetGroupCommander("Story_Pirate", "Quest pirate");
		Group_SetTaskAttack("Story_Pirate", PLAYER_GROUP);
		Group_LockTask("Story_Pirate");
		Group_SetPursuitGroup("Story_Pirate", PLAYER_GROUP);
		Group_SetAddress("Story_Pirate", destination, "", "");
		//Logit("TreasureQuest: Story_Pirate "+GetCharacterIndex("Quest pirate")+" generated");// DEBUG
	}
	if(rand(Makeint(Pchar.skill.sneak))>0)
	{
		ref pir; string ani;
		int con;
		for(con =  1; con < 11 ; con++)
		{
			pir = &Characters[GetcharacterIndex("Treas_Pirate_" + con)];
			pir.model = LAi_GetBoardingModel(pir, &ani);
			LAi_SetImmortal(pir, false);
			if(rand(Makeint(Pchar.skill.sneak)) > 0) { ChangeCharacterAddressGroup(pir, attackers_location, "goto", attackers_locator); }
			else { ChangeCharacterAddressGroup(pir, "", "", ""); }
			//LAi_SetPatrolType(pir);
			//LAi_group_MoveCharacter(pir, LAI_GROUP_MONSTERS);
			LAi_SetWarriorType(pir);
			LAi_group_MoveCharacter(pir, "treasure_pirates");

			LAi_group_SetRelation(LAI_GROUP_PLAYER, "treasure_pirates", "enemy");
			LAi_group_SetRelation(LAI_DEFAULT_GROUP, "treasure_pirates", "enemy");
			LAi_group_SetRelation(LAI_GROUP_MONSTERS, "treasure_pirates", "enemy");
			LAi_group_FightGroups("treasure_pirates", LAI_GROUP_PLAYER, true);

			//LAi_tmpl_SetFollow(pir, Pchar, 120);
			pir.rank = Pchar.rank;
			pir.experience = Pchar.experience;
			pir.name = "Pirate";
			pir.middlename = "";
			pir.lastname = "";
			LAi_SetHP(pir, Pchar.chr_ai.hp_max,Pchar.chr_ai.hp);
			if(IsCharacterPerkOn(Pchar,"BasicDefense")) {pir.perks.list.BasicDefense = true;}
			if(IsCharacterPerkOn(Pchar,"AdvancedDefense")) {pir.perks.list.AdvancedDefense = true;}					
			if(IsCharacterPerkOn(Pchar,"SwordplayProfessional")) {pir.perks.list.SwordplayProfessional = true;}	
			if(IsCharacterPerkOn(Pchar,"CriticalHit")) {pir.perks.list.CriticalHit = true;}
			if(IsCharacterPerkOn(Pchar,"Gunman")) {pir.perks.list.Gunman = true;}
			if(IsCharacterPerkOn(Pchar,"GunProfessional")) {pir.perks.list.GunProfessional = true;}
			DeleteAttribute(&pir, "items");
			LAi_NPC_Equip(&pir, sti(pir.rank), true, true);
			pir.money = rand(1000);
			//Logit("TreasureQuest: Treas_Pirate "+GetcharacterIndex("Treas_Pirate_" + con)+" generated");// DEBUG
		}
	}
	sea_location = FindSeaShoreForLocation(treasure_location);
	CloseQuestHeader("treasure");
	Preprocessor_Add("island", TranslateString("", destination)); // KK hahaha!
	if(FindSeaShoreForLocation(treasure_location)!="") Preprocessor_Add("seashore", TranslateString("", locations[FindLocation(sea_location)].id.label)); // KK
	Preprocessor_Add("destination", TranslateString("", locations[FindLocation(treasure_location)].id.label)); // KK
	DeleteQuestHeader("treasure");
	AddQuestRecord("treasure",numquest);
	Preprocessor_Remove("destination"); // KK
	Preprocessor_Remove("seashore"); // KK
	Preprocessor_Remove("island"); // KK
	AddMoneyToCharacter(NPChar, Sum);
	AddMoneyToCharacter(PChar, -Sum);
	PlayStereoSound("INTERFACE\took_item.wav");

	// TIH --> these were missing, need to be set for proper tracking and handling
	PChar.trquestnum = numquest;
	PChar.trlocation = treasure_location;
	PChar.trlocator = treasure_locator;
	PChar.trlocatorfound = "";
	PChar.trlocationexit = "";
	PChar.trlocatorexit = "";
	// TIH <--
	//Log_SetStringToLog(" " + Calc_luck + " ");
	//Log_SetStringToLog(Npchar.money);
	//Log_SetStringToLog(treasure_location);
	//Log_SetStringToLog(treasure_locator);
	//Npchar.money = 100;
	Calc_luck = rand(Calc_luck); // chance you may get robbed, higher luck means higher chances
	if( Calc_luck != 0 )
	{
		//TREASURE
		Locations[FindLocation(treasure_location)].(treasure_locator).money = (Calc_luck*rand(3000));// TIH put here instead
		if(calc_luck > 4){Locations[FindLocation(treasure_location)].(treasure_locator).items.cursedcoin = (Calc_luck*rand(1000));}
		Locations[FindLocation(treasure_location)].(treasure_locator).items.jewelry1 = (Calc_luck*rand(100));
		if(calc_luck > 3){Locations[FindLocation(treasure_location)].(treasure_locator).items.jewelry2 = (Calc_luck*rand(100));}
		if(calc_luck > 3){Locations[FindLocation(treasure_location)].(treasure_locator).items.jewelry3 = (Calc_luck*rand(100));}
		if(calc_luck > 4){Locations[FindLocation(treasure_location)].(treasure_locator).items.jewelry4 = (Calc_luck*rand(100));}
		Locations[FindLocation(treasure_location)].(treasure_locator).items.jewelry5 = (Calc_luck*rand(100));
		Locations[FindLocation(treasure_location)].(treasure_locator).items.jewelry6 = (Calc_luck*rand(100));
		if(calc_luck > 2){Locations[FindLocation(treasure_location)].(treasure_locator).items.jewelry7 = (Calc_luck*rand(100));}
		Locations[FindLocation(treasure_location)].(treasure_locator).items.jewelry8 = (Calc_luck*rand(100));
		Locations[FindLocation(treasure_location)].(treasure_locator).items.jewelry9 = (Calc_luck*rand(100));
		if(calc_luck > 5){Locations[FindLocation(treasure_location)].(treasure_locator).items.jewelry10 = (Calc_luck*rand(100));}
		if(calc_luck > 1){Locations[FindLocation(treasure_location)].(treasure_locator).items.jewelry11 = (Calc_luck*rand(100));}
		Locations[FindLocation(treasure_location)].(treasure_locator).items.jewelry12 = (Calc_luck*rand(100));
		Locations[FindLocation(treasure_location)].(treasure_locator).items.jewelry13 = (Calc_luck*rand(100));
		if(calc_luck > 2){Locations[FindLocation(treasure_location)].(treasure_locator).items.jewelry14 = (Calc_luck*rand(100));}
		Locations[FindLocation(treasure_location)].(treasure_locator).items.jewelry15 = (Calc_luck*rand(100));
		if(calc_luck > 6){Locations[FindLocation(treasure_location)].(treasure_locator).items.jewelry16 = (Calc_luck*rand(100));}
		if(calc_luck > 9){Locations[FindLocation(treasure_location)].(treasure_locator).items.indian1 = (Calc_luck*rand(100));}
		Locations[FindLocation(treasure_location)].(treasure_locator).items.indian3 = (Calc_luck*rand(50));
		if(calc_luck > 9){Locations[FindLocation(treasure_location)].(treasure_locator).items.indian5 = (Calc_luck*rand(100));}
		if(calc_luck > 8){Locations[FindLocation(treasure_location)].(treasure_locator).items.indian6 = (Calc_luck*rand(100));}
		Locations[FindLocation(treasure_location)].(treasure_locator).items.indian8 = (Calc_luck*rand(10));
		Locations[FindLocation(treasure_location)].(treasure_locator).items.indian9 = (Calc_luck*rand(10));
		if(calc_luck > 9){Locations[FindLocation(treasure_location)].(treasure_locator).items.indian10 = (Calc_luck*rand(100));}
		if(calc_luck > 7){Locations[FindLocation(treasure_location)].(treasure_locator).items.indian12 = (Calc_luck*rand(100));}
		if(calc_luck > 8){Locations[FindLocation(treasure_location)].(treasure_locator).items.indian14 = (Calc_luck*rand(100));}
		//WEAPONS
		if(calc_luck > 6)
		{				
			Locations[FindLocation(treasure_location)].(treasure_locator).items.pistol3 = (Calc_luck*rand(5));
			Locations[FindLocation(treasure_location)].(treasure_locator).items.pistol4 = (Calc_luck*rand(5));
			Locations[FindLocation(treasure_location)].(treasure_locator).items.pistol5 = (Calc_luck*rand(5));
		}
		if(calc_luck > 7)
		{				
			Locations[FindLocation(treasure_location)].(treasure_locator).items.pistol6 = (Calc_luck*rand(4));
			Locations[FindLocation(treasure_location)].(treasure_locator).items.pistol7 = (Calc_luck*rand(4));
			Locations[FindLocation(treasure_location)].(treasure_locator).items.spyglass3 = 1;
		}
		if(calc_luck > 8)
		{				
			Locations[FindLocation(treasure_location)].(treasure_locator).items.pistol8 = (Calc_luck*rand(4));
			Locations[FindLocation(treasure_location)].(treasure_locator).items.pistolmtoon = (Calc_luck*rand(4));
			Locations[FindLocation(treasure_location)].(treasure_locator).items.commonarmor = (Calc_luck*rand(3));
		}
		if(calc_luck > 9)
		{
			Locations[FindLocation(treasure_location)].(treasure_locator).items.pistol9 = (Calc_luck*rand(4));
			Locations[FindLocation(treasure_location)].(treasure_locator).items.pistolmket = (Calc_luck*rand(10));
			Locations[FindLocation(treasure_location)].(treasure_locator).items.goldarmor = rand(10);
			Locations[FindLocation(treasure_location)].(treasure_locator).items.blade24 = rand(10);
			Locations[FindLocation(treasure_location)].(treasure_locator).items.blade27 = rand(10);
			Locations[FindLocation(treasure_location)].(treasure_locator).items.spyglass4 = 1;
		}
	}
}

string FindSeaShoreForLocation(string locID)//MAXIMUS: search for nearest shore
{
	if(locID=="") return "";
	if(FindLocation(locID)==-1) return "";
	if(CheckAttribute(&locations[FindLocation(locID)],"type") && locations[FindLocation(locID)].type=="seashore") return locations[FindLocation(locID)].id;

	aref loc; makearef(loc, locations[FindLocation(locID)].reload);
	for(int i=0; i<GetAttributesNum(loc); i++)
	{
		aref attr = GetAttributeN(loc,i);
		string attrName = GetAttributeName(attr);
		if(CheckAttribute(loc,attrName+".go") && loc.(attrName).go!="")
		{
			if(FindLocation(loc.(attrName).go)!=-1)
			{
				if(CheckAttribute(&locations[FindLocation(loc.(attrName).go)],"type"))
				{
					if(locations[FindLocation(loc.(attrName).go)].type=="seashore") return locations[FindLocation(loc.(attrName).go)].id;
					else
					{
						aref loc1; makearef(loc1, locations[FindLocation(loc.(attrName).go)].reload);
						for(int j=0; j<GetAttributesNum(loc1); j++)
						{
							aref attr1 = GetAttributeN(loc1,j);
							string attrName1 = GetAttributeName(attr1);
							if(CheckAttribute(loc1,attrName1+".go") && loc1.(attrName1).go!="")
							{
								if(FindLocation(loc1.(attrName1).go)!=-1)
								{
									if(CheckAttribute(&locations[FindLocation(loc1.(attrName1).go)],"type"))
									{
										if(locations[FindLocation(loc1.(attrName1).go)].type=="seashore") return locations[FindLocation(loc1.(attrName1).go)].id;
										else
										{
											aref loc2; makearef(loc2, locations[FindLocation(loc1.(attrName1).go)].reload);
											for(int k=0; k<GetAttributesNum(loc2); k++)
											{
												aref attr2 = GetAttributeN(loc2,k);
												string attrName2 = GetAttributeName(attr2);
												if(CheckAttribute(loc2,attrName2+".go") && loc2.(attrName2).go!="")
												{
													if(FindLocation(loc2.(attrName2).go)!=-1)
													{
														if(CheckAttribute(&locations[FindLocation(loc2.(attrName2).go)],"type"))
														{
															if(locations[FindLocation(loc2.(attrName2).go)].type=="seashore") return locations[FindLocation(loc2.(attrName2).go)].id;
															else
															{
																aref loc3; makearef(loc3, locations[FindLocation(loc2.(attrName2).go)].reload);
																for(int l=0; l<GetAttributesNum(loc3); l++)
																{
																	aref attr3 = GetAttributeN(loc3,l);
																	string attrName3 = GetAttributeName(attr3);
																	if(CheckAttribute(loc3,attrName3+".go") && loc3.(attrName3).go!="")
																	{
																		if(FindLocation(loc3.(attrName3).go)!=-1)
																		{
																			if(CheckAttribute(&locations[FindLocation(loc3.(attrName3).go)],"type"))
																			{
																				if(locations[FindLocation(loc3.(attrName3).go)].type=="seashore") return locations[FindLocation(loc3.(attrName3).go)].id;
																				else
																				{//MAXIMUS: currently checks up to 4 locations, but can search more :)
																				}
																			}
																		}
																	}
																}
															}
														}
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
	return locations[FindLocation(locID)].id;
}
/*====================================================|END OF QUESTS SECTION|====================================================*/

/*====================================================|START OF DIRECT-SAILS|====================================================*/
ref DirectSailMessenger(string encType)
{
	string ani, model, firstName;
	ref mainChar = GetMainCharacter();
	ref tmpChar;

	model = LAi_GetBoardingModel(mainChar, &ani);
	firstName = XI_ConvertString("Crewmember");

	tmpChar = mainChar;
	tmpChar.old.name = tmpChar.name;
	tmpChar.old.lastname = tmpChar.lastname;
	tmpChar.old.model = tmpChar.model;
	tmpChar.old.Dialog.Filename = tmpChar.Dialog.Filename;
	tmpChar.old.Dialog.Currentnode = tmpChar.Dialog.Currentnode;
	if(!CheckAttribute(tmpChar,"greeting")) { tmpChar.greeting = ""; }
	tmpChar.old.greeting = tmpChar.greeting;
	tmpChar.old.Dialog.Currentnode = tmpChar.Dialog.Currentnode;
	if(CheckAttribute(tmpChar,"disableDlg")) { tmpChar.old.disableDlg = sti(tmpChar.disableDlg); tmpChar.disableDlg = 0; }

	tmpChar.model = model;
	tmpChar.name = firstName;
	tmpChar.lastname = "";
	tmpChar.Dialog.Filename = "Enc_DirectSail_dialog.c";
	tmpChar.Dialog.Currentnode = "First time";
	tmpChar.greeting = encType;
	tmpChar.IsFantom = false;
	tmpChar.SailHo = true;

	for(int i=0; i<GetPassengersQuantity(mainChar); i++)
	{
		int idx = GetPassenger(mainChar,i);
		if(idx>0)
		{
			if(CheckAttribute(characters[idx],"quest.officertype") && !CheckAttribute(characters[idx],"prisoned"))
			{
				if(characters[idx].quest.officertype==OFFIC_TYPE_BOATSWAIN || characters[idx].quest.officertype==OFFIC_TYPE_FIRSTMATE)
				{
					tmpChar.name = XI_ConvertString(characters[idx].quest.officertype);
					tmpChar.model = characters[idx].model;
					Facemaker(tmpChar);
					return tmpChar;
				}
			}
		}
	}
	Facemaker(tmpChar);
	return tmpChar;
}

void ResetTimeToNormal()
{
	ref PChar = GetMainCharacter();
	float basetime = 1.0;
	if(CheckAttribute(PChar,"basetime")) basetime = stf(PChar.basetime);
	if(IsPerkIntoList("TimeSpeed"))
	{
		SetTimeScale(basetime);
		DelPerkFromActiveList("TimeSpeed");
		PChar.timeaccel1030 = "30";
	}
}
/*=====================================================|END OF DIRECT-SAILS|=====================================================*/

/*====================================================|START OF ABORDAGE_MOD|====================================================*/
ref CreateTwinCharacter(ref _refEnemy)
{
	ref refMyCharacter = GetMainCharacter();
	ref Fightincabin;

	Fightincabin = _refEnemy;
	Fightincabin.isFantom = 0;
	Fightincabin.fight = 0;
	_refEnemy.isFantom = 0;
	_refEnemy.fight = 0;

	bool IsFantom = CheckAttribute(_refEnemy, "isFantom") == true && sti(_refEnemy.IsFantom) == true; // KK
	if(!IsFantom) IsFantom = strleft(_refEnemy.id,4)=="fenc";//MAXIMUS:
	if(!IsFantom) IsFantom = _refEnemy.id=="0";//MAXIMUS:
	int freeIdx = FindFreeCabinCaptain(); // KK
	if(freeIdx != -1)
	{
		if(IsFantom)
		{
			Fightincabin = GetCharacter(freeIdx); // KK

			int newIndex = Fightincabin.index;
			string newId = Fightincabin.id
			CopyAttributes(&Fightincabin,_refEnemy);
			Fightincabin.index = newIndex;
			Fightincabin.id	= newId;
			facemaker(Fightincabin);

			if(CheckAttribute(Fightincabin,"ship")) DeleteAttribute(Fightincabin,"ship");
			if(CheckAttribute(Fightincabin,"shiptype")) DeleteAttribute(Fightincabin,"shiptype");
			if(CheckAttribute(Fightincabin,"shipmoney")) DeleteAttribute(Fightincabin,"shipmoney");
			if(CheckAttribute(Fightincabin,"curshipnum")) DeleteAttribute(Fightincabin,"curshipnum");
			if(CheckAttribute(Fightincabin,"seaai")) DeleteAttribute(Fightincabin,"seaai");
			if(CheckAttribute(Fightincabin,"features")) DeleteAttribute(Fightincabin,"features");
			if(CheckAttribute(Fightincabin,"viper_sailstype")) DeleteAttribute(Fightincabin,"viper_sailstype");
			if(CheckAttribute(Fightincabin,"seatime")) DeleteAttribute(Fightincabin,"seatime");
			if(CheckAttribute(Fightincabin,"relation")) DeleteAttribute(Fightincabin,"relation");
			if(CheckAttribute(Fightincabin,"fantomtype")) DeleteAttribute(Fightincabin,"fantomtype");
			if(CheckAttribute(Fightincabin,"canfiretime")) DeleteAttribute(Fightincabin,"canfiretime");
			if(CheckAttribute(Fightincabin,"rankscale")) DeleteAttribute(Fightincabin,"rankscale");
			if(CheckAttribute(Fightincabin,"tmpperks")) DeleteAttribute(Fightincabin,"tmpperks");
			if(CheckAttribute(Fightincabin,"tmpskill")) DeleteAttribute(Fightincabin,"tmpskill");
			if(CheckAttribute(Fightincabin,"points")) DeleteAttribute(Fightincabin,"points");
			if(CheckAttribute(Fightincabin,"randofficers")) DeleteAttribute(Fightincabin,"randofficers");
			if(CheckAttribute(Fightincabin,"skillnatmult")) DeleteAttribute(Fightincabin,"skillnatmult");
			if(CheckAttribute(Fightincabin,"nodisarm")) DeleteAttribute(Fightincabin,"nodisarm");
			if(CheckAttribute(Fightincabin,"points")) DeleteAttribute(Fightincabin,"points");
			if(CheckAttribute(Fightincabin,"isFantom")) DeleteAttribute(Fightincabin,"isFantom");

			Fightincabin.isFantom = 1;
			Fightincabin.fight = 0;
			_refEnemy.isFantom = 1;
			_refEnemy.fight = 0;

			if(CheckAttribute(_refEnemy,"Ship"))
			{
				Fightincabin.Ship = "";
				aref arShipMy, arShipEnemy;
				makearef(arShipMy,Fightincabin.Ship);
				makearef(arShipEnemy,_refEnemy.Ship);
				CopyAttributes(&arShipMy,&arShipEnemy);
			}
		}
	}

	if(!UsableOfficer(_refEnemy))
	{
		switch(Rand(7))
		{
			case 0: Fightincabin.quest.officertype = OFFIC_TYPE_BOATSWAIN; break;
			case 1: Fightincabin.quest.officertype = OFFIC_TYPE_CANNONEER; break;
			case 2: Fightincabin.quest.officertype = OFFIC_TYPE_QMASTER; break;
			case 3: Fightincabin.quest.officertype = OFFIC_TYPE_NAVIGATOR; break;
			case 4: Fightincabin.quest.officertype = OFFIC_TYPE_FIRSTMATE; break;
			case 5: Fightincabin.quest.officertype = OFFIC_TYPE_CARPENTER; break;
			case 6: Fightincabin.quest.officertype = OFFIC_TYPE_DOCTOR; break;
			case 7: Fightincabin.quest.officertype = OFFIC_TYPE_ABORDAGE; break;
		}
		LAi_Create_Officer(rand(8), &Fightincabin);
	}

	if(CheckAttribute(_refEnemy,"quest.officerprice")) { Fightincabin.quest.officerprice = _refEnemy.quest.officerprice; }
	else { Fightincabin.quest.officerprice = makeint((sti(refMyCharacter.rank) * 2 + 10)*100) - 330 + rand(40)*15 + rand(10); }

	if(!CheckAttribute(_refEnemy,"money")) { Fightincabin.money = makeint(rand(100)); }
	if(CheckAttribute(_refEnemy,"money")) { Fightincabin.wealth = makeint(sti(_refEnemy.money)*(frand(5.0)+2.3)); }

	Fightincabin.nodisarm = 1;
	if(!CheckAttribute(Fightincabin,"chr_ai.type")) { Fightincabin.chr_ai.type = "stay"; }
	if(!CheckAttribute(Fightincabin,"model.entity")) { Fightincabin.model.entity = "NPCharacter"; }
	Fightincabin.Dialog.Filename = "Cabinfight_dialog.c";
	Fightincabin.Dialog.Currentnode = "First time";
	if(Fightincabin.sex=="woman") Fightincabin.greeting = "Gr_Pirate_f";
	else Fightincabin.greeting = "Gr_Dark Teacher";
	if (IsFantom) LAi_NPC_Equip(&Fightincabin, sti(Fightincabin.rank), true, 0.5); // KK

	return Fightincabin;
}

bool UsableOfficer(ref _refEnemy)
{
	if(CheckAttribute(_refEnemy,"quest.officertype"))
	{
		if(_refEnemy.quest.officertype==OFFIC_TYPE_BOATSWAIN) return true;
		if(_refEnemy.quest.officertype==OFFIC_TYPE_CANNONEER) return true;
		if(_refEnemy.quest.officertype==OFFIC_TYPE_QMASTER) return true;
		if(_refEnemy.quest.officertype==OFFIC_TYPE_NAVIGATOR) return true;
		if(_refEnemy.quest.officertype==OFFIC_TYPE_FIRSTMATE) return true;
		if(_refEnemy.quest.officertype==OFFIC_TYPE_CARPENTER) return true;
		if(_refEnemy.quest.officertype==OFFIC_TYPE_DOCTOR) return true;
		if(_refEnemy.quest.officertype==OFFIC_TYPE_ABORDAGE) return true;
	}
	return false;
}
/*=====================================================|END OF ABORDAGE_MOD|=====================================================*/

/*====================================================|START OF LOCATION-MOD|====================================================*/
void InitQCBrothel()
{
	if (FindLocation("QC_Brothel") < 0) return; // KK
	int n = FindLocation("QC_town"); // KK
	if (n < 0) return; // KK
	Locations[n].reload.l7.name = "Reload9";
	Locations[n].reload.l7.go = "QC_brothel";
	Locations[n].reload.l7.emerge = "reload1";
	Locations[n].reload.l7.autoreload = "0";
	Locations[n].reload.l7.label = "#stown_name# Brothel.";

	// -----BROTHEL--------------------------------------------
	n = FindLocation("QC_Brothel"); // KK
	Locations[n].id = "QC_brothel";
	locations[n].id.label = "#stown_name# Brothel.";
	Locations[n].filespath.models = "locations\inside\Largetavern";
	Locations[n].image = "Tavern_01.tga";

	//Town sack
	Locations[n].townsack = "Quebradas Costillas"; // NK - "Oxbay";

	//Sound
	locations[n].type = "brothel";
	locations[n].fastreload = "QC";
	//Models
	//Always
	Locations[n].models.always.tavern = "LT";
	Locations[n].models.always.locators = "LT_l";
	Locations[n].models.always.window = "LT_w";
	Locations[n].models.always.window.tech = "LocationWindows";
	Locations[n].models.always.window.level = 50;
	//Day
	Locations[n].models.day.charactersPatch = "LT_p";

	//Night
	Locations[n].models.night.charactersPatch = "LT_p";

	//Environment
	Locations[n].environment.weather = "false";
	Locations[n].environment.sea = "false";
	Locations[n].models.back = "back\redlt_";

	//Reload map
	Locations[n].reload.l1.name = "reload1";
	Locations[n].reload.l1.go = "QC_town";
	Locations[n].reload.l1.emerge = "reload9";
	Locations[n].reload.l1.autoreload = "0";
	Locations[n].reload.l1.label = "#stown_name#.";
	Locations[n].monsters = "0";
	LAi_LocationFightDisable(Locations[n], true);

	Locations[n].island = "QuebradasCostillas"; // NK 04-08-29
}

// KK -->
void InitTortugaBrothel()
{
	if (FindLocation("Tortuga_Brothel") < 0) return;
	int n = FindLocation("Tortuga_Port");
	if (n < 0) return;
	Locations[n].reload.l11.go = "Tortuga_Brothel";
	Locations[n].reload.l11.emerge = "reload1";
	Locations[n].reload.l11.label = " #stown_name# Brothel.";

	// -----BROTHEL--------------------------------------------
	n = FindLocation("Tortuga_Brothel");
	Locations[n].id = "Tortuga_Brothel";
	Locations[n].id.label = "#stown_name# Brothel.";
	//Town sack
	Locations[n].townsack = "Tortuga";
	//Sound
	locations[n].type = "brothel";
	locations[n].fastreload = "Tortuga";
	LAi_LocationFantomsGen(&Locations[n], false);

	InitBrothel(Locations[n].id);

	//Reload map
	Locations[n].reload.l1.go = "Tortuga_Port";
	Locations[n].reload.l1.emerge = "brothel";
	Locations[n].reload.l1.label = "#stown_name#";

	Locations[n].reload.l2.go = "Tortuga_Brothel_bedroom";
	Locations[n].reload.l2.emerge = "reload1";
	Locations[n].reload.l2.label = "Brothel Bedroom";

	Locations[n].reload.l3.go = "Tortuga_Brothel_room";
	Locations[n].reload.l3.emerge = "reload1";
	Locations[n].reload.l3.label = "Opium Den";

	Locations[n].island = "Hispaniola";
}

void InitPaPBrothel()
{
	if (FindLocation("PaP_Brothel") < 0) return;
	int n = FindLocation("Guadeloupe_Port");
	if (n < 0) return;
	Locations[n].reload.l11.go = "PaP_Brothel";
	Locations[n].reload.l11.emerge = "reload1";
	Locations[n].reload.l11.label = " #stown_name# Brothel.";

	// -----BROTHEL--------------------------------------------
	n = FindLocation("PaP_Brothel");
	Locations[n].id = "PaP_Brothel";
	locations[n].id.label = "#stown_name# Brothel.";
	//Town sack
	Locations[n].townsack = "Pointe a Pitre";
	//Sound
	locations[n].type = "brothel";
	locations[n].fastreload = "Pointe_a_Pitre";
	LAi_LocationFantomsGen(&locations[n], false);

	InitBrothel(Locations[n].id);

	//Reload map
	Locations[n].reload.l1.go = "Guadeloupe_Port";
	Locations[n].reload.l1.emerge = "brothel";
	Locations[n].reload.l1.label = "#stown_name#";
	
	Locations[n].reload.l2.go = "PaP_Brothel_bedroom";
	Locations[n].reload.l2.emerge = "reload1";
	Locations[n].reload.l2.label = "Brothel Bedroom";
	
	Locations[n].reload.l3.go = "PaP_Brothel_room";
	Locations[n].reload.l3.emerge = "reload1";
	Locations[n].reload.l3.label = "Opium Den";

	Locations[n].island = "Guadeloupe";
}

void InitCharlestownBrothel()
{
	if (FindLocation("Charlestown_Brothel") < 0) return;
	int n = FindLocation("Charlestown_Port");
	if (n < 0) return;

	locations[n].reload.l9.name = "housePirate";
	locations[n].reload.l9.go = "Charlestown_Brothel";
	locations[n].reload.l9.emerge = "reload1";
	locations[n].reload.l9.autoreload = "0";
	locations[n].reload.l9.label = "Brothel";
	locations[n].reload.l9.disable = 0;
	Locations[n].reload.l9.close_for_night = 0;

	// -----BROTHEL--------------------------------------------
	n = FindLocation("Charlestown_Brothel");
	Locations[n].id = "Charlestown_Brothel";
	locations[n].id.label = "#stown_name# Brothel.";

	//Town sack
	Locations[n].townsack = "Charlestown";

	//Sound
	Locations[n].type = "brothel";
	Locations[n].fastreload = "Charlestown";
	LAi_LocationFantomsGen(&Locations[n], true);

	InitBrothel(Locations[n].id);

	//Reload map
	Locations[n].reload.l1.go = "Charlestown_Port";
	Locations[n].reload.l1.emerge = "housePirate";
	Locations[n].reload.l1.label = "#stown_name#";
	
	Locations[n].reload.l2.go = "Charlestown_Brothel_bedroom";
	Locations[n].reload.l2.emerge = "reload1";
	Locations[n].reload.l2.label = "Brothel Bedroom";

	Locations[n].island = "QuebradasCostillas";
}
// <-- KK

#event_handler("CheckQuestPossibility", "CheckGambledQuest");
void CheckGambledQuest()
{
	ref PChar = GetMainCharacter();
	if(!HasSubStr(PChar.location,"tavern") && !CheckAttribute(PChar,"IsOnDeck"))
	{
		PChar.quest.not_to_the_ship_2.win_condition.l1 = "ExitFromLocation";
		PChar.quest.not_to_the_ship_2.win_condition.l1.location = PChar.location;
		PChar.quest.not_to_the_ship_2.win_condition = "girl_for_sale_2";
	}
	else { PostEvent("CheckQuestPossibility", 100, "1", 0); }
}

//======================================| NEW AOP TOWNS |======================================//

void InitAOPAntigua(string locationID)
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Towns\Antigua";

	Locations[FindLocation(locationID)].models.always.locators = "Town_l";
	Locations[FindLocation(locationID)].upgrades = "upgrades";

	Locations[FindLocation(locationID)].models.always.shipyard = "upgrades\shipyard1";
	Locations[FindLocation(locationID)].models.always.shipyard.locator.group = "upgrades";
	Locations[FindLocation(locationID)].models.always.shipyard.locator.name = "shipyard";
	Locations[FindLocation(locationID)].models.always.shipyard.status = "upgrades\shipyard1";

	Locations[FindLocation(locationID)].reload.l2.name = "reload1_back";
	Locations[FindLocation(locationID)].reload.l2.autoreload = "0";
// KK -->
	if (VISIT_DECK == 1)
		Locations[FindLocation(locationID)].reload.l2.label = "Ship.";
	else
		Locations[FindLocation(locationID)].reload.l2.label = "Sea.";
// <-- KK
	Locations[FindLocation(locationID)].locators_radius.reload.reload1_back = 2;

	InitAOPlocation(locationID);
}

void InitAOPStMartin(string locationID)
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Towns\StMartin";

	Locations[FindLocation(locationID)].models.always.locators = "Town_l";

	Locations[FindLocation(locationID)].models.always.l3 = "plan1";
	Locations[FindLocation(locationID)].models.always.l3.level = 9;
	Locations[FindLocation(locationID)].models.always.l3.tech = "LocationModelBlend";

	Locations[FindLocation(locationID)].upgrades = "upgrades";

	Locations[FindLocation(locationID)].models.always.shipyard = "..\upgrades\shipyard3";
	Locations[FindLocation(locationID)].models.always.shipyard.status = "..\upgrades\shipyard3";

	InitAOPlocation(locationID);
}

void InitAOPGuadeloupe(string locationID)
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Towns\Guadeloupe";

	Locations[FindLocation(locationID)].models.always.locators = "Town_l";
	Locations[FindLocation(locationID)].upgrades = "upgrades";

	Locations[FindLocation(locationID)].models.always.shipyard = "..\upgrades\shipyard1";
	Locations[FindLocation(locationID)].models.always.shipyard.status = "..\upgrades\shipyard1";

	InitAOPlocation(locationID);
}

void InitAOPTortuga(string locationID)
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Towns\Tortuga";

	Locations[FindLocation(locationID)].models.always.locators = "Town_l";
	Locations[FindLocation(locationID)].upgrades = "upgrades";

	Locations[FindLocation(locationID)].models.always.shipyard = "..\upgrades\shipyard1";
	Locations[FindLocation(locationID)].models.always.shipyard.status = "..\upgrades\shipyard1";

	InitAOPlocation(locationID);
}

void InitAOPMontserrat(string locationID)
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Towns\Montserrat";

	Locations[FindLocation(locationID)].models.always.locators = "Town_l";

	Locations[FindLocation(locationID)].models.always.l3 = "plan1";
	Locations[FindLocation(locationID)].models.always.l3.level = 9;
	Locations[FindLocation(locationID)].models.always.l3.tech = "LocationModelBlend";
	Locations[FindLocation(locationID)].models.always.l5 = "fontain1";
    Locations[FindLocation(locationID)].models.always.l5.uvslide.u0 = 0.0005;
    Locations[FindLocation(locationID)].models.always.l5.uvslide.v0 = 0.2;
	Locations[FindLocation(locationID)].models.always.l5.level = 999;
	Locations[FindLocation(locationID)].models.always.l5.tech = "LocationWaterFall";
	Locations[FindLocation(locationID)].models.always.l6 = "fontain2";
    Locations[FindLocation(locationID)].models.always.l6.uvslide.u0 = 0.04;
    Locations[FindLocation(locationID)].models.always.l6.uvslide.v0 = 0.01;
	Locations[FindLocation(locationID)].models.always.l6.level = 999;
	Locations[FindLocation(locationID)].models.always.l6.tech = "LocationWaterFall";

	Locations[FindLocation(locationID)].upgrades = "upgrades";

	Locations[FindLocation(locationID)].models.always.shipyard = "..\upgrades\shipyard1";
	Locations[FindLocation(locationID)].models.always.shipyard.status = "..\upgrades\shipyard1";

	Locations[FindLocation(locationID)].reload.l2.name = "reload1_back";
	Locations[FindLocation(locationID)].reload.l2.autoreload = "0";
// KK -->
	if (VISIT_DECK == 1)
		Locations[FindLocation(locationID)].reload.l2.label = "Ship.";
	else
		Locations[FindLocation(locationID)].reload.l2.label = "Sea.";
// <-- KK
	Locations[FindLocation(locationID)].locators_radius.reload.reload1_back = 2;

	InitAOPlocation(locationID);
}

void InitAOPlocation(string locationID)
{
	//Models
	Locations[FindLocation(locationID)].models.always.shipyard.locator.group = "upgrades";
	Locations[FindLocation(locationID)].models.always.shipyard.locator.name = "shipyard";

	Locations[FindLocation(locationID)].models.always.academy = "..\upgrades\academy1";
	Locations[FindLocation(locationID)].models.always.academy.locator.group = "upgrades";
	Locations[FindLocation(locationID)].models.always.academy.locator.name = "academy";

	Locations[FindLocation(locationID)].models.always.church = "..\upgrades\church1";
	Locations[FindLocation(locationID)].models.always.church.locator.group = "upgrades";
	Locations[FindLocation(locationID)].models.always.church.locator.name = "church";

	Locations[FindLocation(locationID)].models.always.storehouse = "..\upgrades\storehouse1";
	Locations[FindLocation(locationID)].models.always.storehouse.locator.group = "upgrades";
	Locations[FindLocation(locationID)].models.always.storehouse.locator.name = "storehouse";

	Locations[FindLocation(locationID)].models.always.huts = "..\upgrades\huts1";
	Locations[FindLocation(locationID)].models.always.huts.locator.group = "upgrades";
	Locations[FindLocation(locationID)].models.always.huts.locator.name = "huts";

	Locations[FindLocation(locationID)].models.always.fishingpier = "..\upgrades\fishingpier1";
	Locations[FindLocation(locationID)].models.always.fishingpier.locator.group = "upgrades";
	Locations[FindLocation(locationID)].models.always.fishingpier.locator.name = "fishingpier";

	Locations[FindLocation(locationID)].models.always.mill = "..\upgrades\mill1";
	Locations[FindLocation(locationID)].models.always.mill.locator.group = "upgrades";
	Locations[FindLocation(locationID)].models.always.mill.locator.name = "mill";

	Locations[FindLocation(locationID)].models.always.mill_movie = "..\upgrades\mill_movie";
	Locations[FindLocation(locationID)].models.always.mill_movie.locator.group = "upgrades";
	Locations[FindLocation(locationID)].models.always.mill_movie.locator.name = "mill_movie";
	Locations[FindLocation(locationID)].models.always.mill_movie.rotate.x = 0.0;
	Locations[FindLocation(locationID)].models.always.mill_movie.rotate.y = 0.0;
	Locations[FindLocation(locationID)].models.always.mill_movie.rotate.z = 1.0;
/*
//=======================================| SECTION FOR DESTROYED BUILDINGS |=======================================//

	Locations[FindLocation(locationID)].models.always.shipyard = "..\upgrades\shipyard_destroyed";
	Locations[FindLocation(locationID)].models.always.shipyard.locator.group = "upgrades";
	Locations[FindLocation(locationID)].models.always.shipyard.locator.name = "shipyard";

	Locations[FindLocation(locationID)].models.always.academy = "..\upgrades\academy_destroyed";
	Locations[FindLocation(locationID)].models.always.academy.locator.group = "upgrades";
	Locations[FindLocation(locationID)].models.always.academy.locator.name = "academy";

	Locations[FindLocation(locationID)].models.always.church = "..\upgrades\church_destroyed";
	Locations[FindLocation(locationID)].models.always.church.locator.group = "upgrades";
	Locations[FindLocation(locationID)].models.always.church.locator.name = "church";

	Locations[FindLocation(locationID)].models.always.storehouse = "..\upgrades\storehouse_destroyed";
	Locations[FindLocation(locationID)].models.always.storehouse.locator.group = "upgrades";
	Locations[FindLocation(locationID)].models.always.storehouse.locator.name = "storehouse";

	Locations[FindLocation(locationID)].models.always.huts = "..\upgrades\huts_destroyed";
	Locations[FindLocation(locationID)].models.always.huts.locator.group = "upgrades";
	Locations[FindLocation(locationID)].models.always.huts.locator.name = "huts";

	Locations[FindLocation(locationID)].models.always.fishingpier = "..\upgrades\fishingpier_destroyed";
	Locations[FindLocation(locationID)].models.always.fishingpier.locator.group = "upgrades";
	Locations[FindLocation(locationID)].models.always.fishingpier.locator.name = "fishingpier";

	Locations[FindLocation(locationID)].models.always.mill = "..\upgrades\mill_destroyed";
	Locations[FindLocation(locationID)].models.always.mill.locator.group = "upgrades";
	Locations[FindLocation(locationID)].models.always.mill.locator.name = "mill";

	Locations[FindLocation(locationID)].models.always.mill_movie = "";
	Locations[FindLocation(locationID)].models.always.mill_movie.locator.group = "";
	Locations[FindLocation(locationID)].models.always.mill_movie.locator.name = "";

//=======================================| SECTION FOR DESTROYED BUILDINGS |=======================================//
*/

	//Always
	Locations[FindLocation(locationID)].models.always.grassPatch = "Town_g";
	Locations[FindLocation(locationID)].models.always.l1 = "Town";
	Locations[FindLocation(locationID)].models.always.l1.foam = "1";
	Locations[FindLocation(locationID)].models.always.l2 = "Town_sb";
	Locations[FindLocation(locationID)].models.always.l2.foam = "1";

	Locations[FindLocation(locationID)].models.always.l4 = "Town_signsA";
	Locations[FindLocation(locationID)].models.always.l4.level = 9;

	//Day
	Locations[FindLocation(locationID)].models.day.rinok = "Town_e1";
	Locations[FindLocation(locationID)].models.day.fonar = "Town_fd";
	Locations[FindLocation(locationID)].models.day.charactersPatch = "Town_pd";
	//Night
	Locations[FindLocation(locationID)].models.night.fonar = "Town_fn";
	Locations[FindLocation(locationID)].models.night.charactersPatch = "Town_pn";

	//Reload map
	Locations[FindLocation(locationID)].reload.l1.name = "reload2_back";
	Locations[FindLocation(locationID)].reload.l1.autoreload = "0";
// KK -->
	if (VISIT_DECK == 1)
		Locations[FindLocation(locationID)].reload.l1.label = "Ship.";
	else
		Locations[FindLocation(locationID)].reload.l1.label = "Sea.";
// <-- KK
	Locations[FindLocation(locationID)].locators_radius.reload.reload2_back = 2;

	Locations[FindLocation(locationID)].reload.l2.name = "reload2_back";
	Locations[FindLocation(locationID)].reload.l2.autoreload = "0";
// KK -->
	if (VISIT_DECK == 1)
		Locations[FindLocation(locationID)].reload.l2.label = "Ship.";
	else
		Locations[FindLocation(locationID)].reload.l2.label = "Sea.";
// <-- KK
	Locations[FindLocation(locationID)].locators_radius.reload.reload2_back = 2;

	Locations[FindLocation(locationID)].reload.l3.name = "reload5_back";
	Locations[FindLocation(locationID)].reload.l3.autoreload = "0";
	Locations[FindLocation(locationID)].reload.l3.label = "Shipyard.";
	Locations[FindLocation(locationID)].reload.l3.close_for_night = 1;

	Locations[FindLocation(locationID)].reload.l4.name = "reload6_back";
	Locations[FindLocation(locationID)].reload.l4.autoreload = "0";
	Locations[FindLocation(locationID)].reload.l4.label = "Store.";
	Locations[FindLocation(locationID)].reload.l4.close_for_night = 1;

	Locations[FindLocation(locationID)].reload.l5.name = "reload3_back";
	Locations[FindLocation(locationID)].reload.l5.autoreload = "0";
	Locations[FindLocation(locationID)].reload.l5.label = "Residence.";
	Locations[FindLocation(locationID)].reload.l5.close_for_night = 1;

	Locations[FindLocation(locationID)].reload.l6.name = "reload4_back";
	Locations[FindLocation(locationID)].reload.l6.autoreload = "0";
	Locations[FindLocation(locationID)].reload.l6.label = "Tavern.";

	Locations[FindLocation(locationID)].reload.l7.name = "houseS1";
	Locations[FindLocation(locationID)].reload.l7.autoreload = "0";

	Locations[FindLocation(locationID)].reload.l8.name = "reload8_back";
	Locations[FindLocation(locationID)].reload.l8.autoreload = "0";
	Locations[FindLocation(locationID)].reload.l8.label = "Loanshark's Office.";
	Locations[FindLocation(locationID)].reload.l8.close_for_night = 1;

	Locations[FindLocation(locationID)].reload.l9.name = "reload7_back";
	Locations[FindLocation(locationID)].reload.l9.autoreload = "0";
	Locations[FindLocation(locationID)].reload.l9.label = "Church.";
	Locations[FindLocation(locationID)].reload.l9.close_for_night = 1;

	Locations[FindLocation(locationID)].reload.l10.name = "gate";
	Locations[FindLocation(locationID)].reload.l10.autoreload = "0";

	Locations[FindLocation(locationID)].reload.l11.name = "brothel";
	Locations[FindLocation(locationID)].reload.l11.autoreload = "0";

	Locations[FindLocation(locationID)].reload.l12.name = "houseS3";
	Locations[FindLocation(locationID)].reload.l12.autoreload = "0";

	Locations[FindLocation(locationID)].reload.l13.name = "houseH1";
	Locations[FindLocation(locationID)].reload.l13.autoreload = "0";

	Locations[FindLocation(locationID)].reload.l14.name = "barracks";
	Locations[FindLocation(locationID)].reload.l14.autoreload = "0";
	Locations[FindLocation(locationID)].reload.l14.close_for_night = 1;

	Locations[FindLocation(locationID)].reload.l15.name = "storehouse";
	Locations[FindLocation(locationID)].reload.l15.autoreload = "0";
	Locations[FindLocation(locationID)].reload.l15.close_for_night = 1;

	Locations[FindLocation(locationID)].reload.l16.name = "academy";
	Locations[FindLocation(locationID)].reload.l16.autoreload = "0";
	Locations[FindLocation(locationID)].reload.l16.close_for_night = 1;
}

void InitArsenal(string locationID)
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Inside\Bank02";
	Locations[FindLocation(locationID)].image = "Barracks.tga";
	//Models
	Locations[FindLocation(locationID)].models.back = "..\back\inside_back_";
	//Always
	Locations[FindLocation(locationID)].models.always.cave = "Bank02";
	Locations[FindLocation(locationID)].models.always.locators = "Bank02_locators";
	Locations[FindLocation(locationID)].models.always.window = "Bank02_windows";
	Locations[FindLocation(locationID)].models.always.window.tech = "LocationWindows";
	Locations[FindLocation(locationID)].models.always.window.level = 50;
	//Day
	Locations[FindLocation(locationID)].models.day.charactersPatch = "Bank02_patch";
	//Night
	Locations[FindLocation(locationID)].models.night.charactersPatch = "Bank02_patch";
	//Environment
	Locations[FindLocation(locationID)].environment.weather = "false";
	Locations[FindLocation(locationID)].environment.sea = "false";

	//Reload map
	Locations[FindLocation(locationID)].reload.l1.name = "reload1";
	Locations[FindLocation(locationID)].reload.l1.emerge = "barracks";
	Locations[FindLocation(locationID)].reload.l1.autoreload = "0";

	Locations[FindLocation(locationID)].reload.l2.name = "reload2";
	Locations[FindLocation(locationID)].reload.l2.emerge = "";
	Locations[FindLocation(locationID)].reload.l2.autoreload = "0";
}

void InitBank(string locationID)
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Inside\Bank01";
	Locations[FindLocation(locationID)].image = "Bank.tga";
	//Models
	Locations[FindLocation(locationID)].models.back = "..\back\inside_back_";
	//Always
	Locations[FindLocation(locationID)].models.always.cave = "Bank01";
	Locations[FindLocation(locationID)].models.always.locators = "Bank01_locators";
	Locations[FindLocation(locationID)].models.always.window = "Bank01_windows";
	Locations[FindLocation(locationID)].models.always.window.tech = "LocationWindows";
	Locations[FindLocation(locationID)].models.always.window.level = 50;
	//Day
	Locations[FindLocation(locationID)].models.day.charactersPatch = "Bank01_patch";
	//Night
	Locations[FindLocation(locationID)].models.night.charactersPatch = "Bank01_patch";
	//Environment
	Locations[FindLocation(locationID)].environment.weather = "false";
	Locations[FindLocation(locationID)].environment.sea = "false";

	//Reload map
	Locations[FindLocation(locationID)].reload.l1.name = "reload1";
	Locations[FindLocation(locationID)].reload.l1.emerge = "reload8_back";
	Locations[FindLocation(locationID)].reload.l1.autoreload = "0";
}

void InitResidence(string locationID)
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Inside\residence04";
	Locations[FindLocation(locationID)].image = "Residence.tga";

	//Models
	Locations[FindLocation(locationID)].models.back = "..\back\inside_back_";
	//Always
	Locations[FindLocation(locationID)].models.always.cave = "residence04";
	Locations[FindLocation(locationID)].models.always.locators = "residence04_locators";
	Locations[FindLocation(locationID)].models.always.window = "residence04_window";
	Locations[FindLocation(locationID)].models.always.window.tech = "LocationWindows";
	Locations[FindLocation(locationID)].models.always.window.level = 50;
	//Day
	Locations[FindLocation(locationID)].models.day.charactersPatch = "residence04_patch";
	//Night
	Locations[FindLocation(locationID)].models.night.charactersPatch = "residence04_patch";
	//Environment
	Locations[FindLocation(locationID)].environment.weather = "false";
	Locations[FindLocation(locationID)].environment.sea = "false";

	//Reload map
	Locations[FindLocation(locationID)].reload.l1.emerge = "reload3_back";
	Locations[FindLocation(locationID)].reload.l1.name = "reload1";
	Locations[FindLocation(locationID)].reload.l1.autoreload = "0";

	LAi_LocationFightDisable(&Locations[FindLocation(locationID)], true);
}

void InitChurch(string locationID)
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Inside\church01";
	Locations[FindLocation(locationID)].image = "Church.tga";

	//Models
	Locations[FindLocation(locationID)].models.back = "..\back\inside_back_";
	//Always
	Locations[FindLocation(locationID)].models.always.cave = "church01";
	Locations[FindLocation(locationID)].models.always.locators = "church01_locators";
	Locations[FindLocation(locationID)].models.always.window = "church01_window";
	Locations[FindLocation(locationID)].models.always.window.tech = "LocationWindows";
	Locations[FindLocation(locationID)].models.always.window.level = 50;
	//Day
	Locations[FindLocation(locationID)].models.day.charactersPatch = "church01_patch";
	//Night
	Locations[FindLocation(locationID)].models.night.charactersPatch = "church01_patch";
	//Environment
	Locations[FindLocation(locationID)].environment.weather = "false";
	Locations[FindLocation(locationID)].environment.sea = "false";

	//Reload map
	Locations[FindLocation(locationID)].reload.l1.emerge = "reload7_back";
	Locations[FindLocation(locationID)].reload.l1.name = "reload1";
	Locations[FindLocation(locationID)].reload.l1.autoreload = "0";

	LAi_LocationFightDisable(&Locations[FindLocation(locationID)], true);
}

void InitStorehouse(string locationID)
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Inside\residence05";
	Locations[FindLocation(locationID)].image = "Storehouse.tga";

	//Models
	Locations[FindLocation(locationID)].models.back = "..\back\inside_back_";
	//Always
	Locations[FindLocation(locationID)].models.always.cave = "residence05";
	Locations[FindLocation(locationID)].models.always.locators = "residence05_locators";
	Locations[FindLocation(locationID)].models.always.window = "";
	Locations[FindLocation(locationID)].models.always.window.tech = "LocationWindows";
	Locations[FindLocation(locationID)].models.always.window.level = 65531;
	//Day
	Locations[FindLocation(locationID)].models.day.charactersPatch = "residence05_patch";
	//Night
	Locations[FindLocation(locationID)].models.night.charactersPatch = "residence05_patch";
	//Environment
	Locations[FindLocation(locationID)].environment.weather = "false";
	Locations[FindLocation(locationID)].environment.sea = "false";

	//Reload map
	Locations[FindLocation(locationID)].reload.l1.emerge = "storehouse";
	Locations[FindLocation(locationID)].reload.l1.name = "reload1";
	Locations[FindLocation(locationID)].reload.l1.autoreload = "0";

	LAi_LocationFightDisable(&Locations[FindLocation(locationID)], true);
}

void InitStore3(string locationID)//originally from AOP Antigua town
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Inside\store03";
	Locations[FindLocation(locationID)].image = "Store03.tga";

	//Models
	Locations[FindLocation(locationID)].models.back = "..\back\inside_back_";
	//Always
	Locations[FindLocation(locationID)].models.always.cave = "store03";
	Locations[FindLocation(locationID)].models.always.locators = "store03_locators";
	Locations[FindLocation(locationID)].models.always.window = "store03_window";
	Locations[FindLocation(locationID)].models.always.window.tech = "LocationWindows";
	Locations[FindLocation(locationID)].models.always.window.level = 50;
	//Day
	Locations[FindLocation(locationID)].models.day.charactersPatch = "store03_patch";
	//Night
	Locations[FindLocation(locationID)].models.night.charactersPatch = "store03_patch";
	//Environment
	Locations[FindLocation(locationID)].environment.weather = "false";
	Locations[FindLocation(locationID)].environment.sea = "false";

	//Reload map
	Locations[FindLocation(locationID)].reload.l1.emerge = "reload6_back";
	Locations[FindLocation(locationID)].reload.l1.name = "reload1";
	Locations[FindLocation(locationID)].reload.l1.autoreload = "0";

	LAi_LocationFightDisable(&Locations[FindLocation(locationID)], true);
}

void InitStore2(string locationID)//originally from AOP Guadeloupe town
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Inside\store02";
	Locations[FindLocation(locationID)].image = "Store02.tga";

	//Models
	Locations[FindLocation(locationID)].models.back = "..\back\inside_back_";
	//Always
	Locations[FindLocation(locationID)].models.always.cave = "store02";
	Locations[FindLocation(locationID)].models.always.locators = "store02_locators";
	Locations[FindLocation(locationID)].models.always.window = "store02_window";
	Locations[FindLocation(locationID)].models.always.window.tech = "LocationWindows";
	Locations[FindLocation(locationID)].models.always.window.level = 50;
	//Day
	Locations[FindLocation(locationID)].models.day.charactersPatch = "store02_patch";
	//Night
	Locations[FindLocation(locationID)].models.night.charactersPatch = "store02_patch";
	//Environment
	Locations[FindLocation(locationID)].environment.weather = "false";
	Locations[FindLocation(locationID)].environment.sea = "false";

	//Reload map
	Locations[FindLocation(locationID)].reload.l1.emerge = "reload6_back";
	Locations[FindLocation(locationID)].reload.l1.name = "reload1";
	Locations[FindLocation(locationID)].reload.l1.autoreload = "0";

	LAi_LocationFightDisable(&Locations[FindLocation(locationID)], true);
}

void InitStore1(string locationID)//originally from AOP Montserrat town
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Inside\store01";
	Locations[FindLocation(locationID)].image = "Store01.tga";

	//Models
	Locations[FindLocation(locationID)].models.back = "..\back\inside_back_";
	//Always
	Locations[FindLocation(locationID)].models.always.cave = "store01";
	Locations[FindLocation(locationID)].models.always.locators = "store01_locators";
	Locations[FindLocation(locationID)].models.always.window = "store01_window";
	Locations[FindLocation(locationID)].models.always.window.tech = "LocationWindows";
	Locations[FindLocation(locationID)].models.always.window.level = 50;
	//Day
	Locations[FindLocation(locationID)].models.day.charactersPatch = "store01_patch";
	//Night
	Locations[FindLocation(locationID)].models.night.charactersPatch = "store01_patch";
	//Environment
	Locations[FindLocation(locationID)].environment.weather = "false";
	Locations[FindLocation(locationID)].environment.sea = "false";

	//Reload map
	Locations[FindLocation(locationID)].reload.l1.emerge = "reload6_back";
	Locations[FindLocation(locationID)].reload.l1.name = "reload1";
	Locations[FindLocation(locationID)].reload.l1.autoreload = "0";

	LAi_LocationFightDisable(&Locations[FindLocation(locationID)], true);
}

void InitShipHoll(string locationID)
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Inside\Shipyard03";
	Locations[FindLocation(locationID)].image = "Academy.tga";
	//Models
	Locations[FindLocation(locationID)].models.back = "..\back\inside_back_";
	//Always
	Locations[FindLocation(locationID)].models.always.cave = "Shipyard03";
	Locations[FindLocation(locationID)].models.always.locators = "Shipyard03_locators";
	Locations[FindLocation(locationID)].models.always.window = "Shipyard03_window";
	Locations[FindLocation(locationID)].models.always.window.tech = "LocationWindows";
	Locations[FindLocation(locationID)].models.always.window.level = 50;
	//Day
	Locations[FindLocation(locationID)].models.day.charactersPatch = "Shipyard03_patch";
	//Night
	Locations[FindLocation(locationID)].models.night.charactersPatch = "Shipyard03_patch";
	//Environment
	Locations[FindLocation(locationID)].environment.weather = "false";
	Locations[FindLocation(locationID)].environment.sea = "false";

	//Reload map
	Locations[FindLocation(locationID)].reload.l1.name = "reload1";
	Locations[FindLocation(locationID)].reload.l1.autoreload = "0";
}

void InitBrothel(string locationID)
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Inside\Brothel";
	Locations[FindLocation(locationID)].image = "Brothel.tga";
	//Models
	Locations[FindLocation(locationID)].models.back = "..\back\inside_back_";
	//Always
	Locations[FindLocation(locationID)].models.always.cave = "Brothel";
	Locations[FindLocation(locationID)].models.always.locators = "Brothel_locators";
	Locations[FindLocation(locationID)].models.always.window = "Brothel_window";
	Locations[FindLocation(locationID)].models.always.window.tech = "LocationWindows";
	Locations[FindLocation(locationID)].models.always.window.level = 50;
	//Day
	Locations[FindLocation(locationID)].models.day.charactersPatch = "Brothel_patch";
	//Night
	Locations[FindLocation(locationID)].models.night.charactersPatch = "Brothel_patch";
	//Environment
	Locations[FindLocation(locationID)].environment.weather = "false";
	Locations[FindLocation(locationID)].environment.sea = "false";

	//Reload map
	Locations[FindLocation(locationID)].reload.l1.name = "reload1";
	Locations[FindLocation(locationID)].reload.l1.autoreload = "0";
	
	Locations[FindLocation(locationID)].reload.l2.name = "reload1_back";
	Locations[FindLocation(locationID)].reload.l2.autoreload = "0";
	
	Locations[FindLocation(locationID)].reload.l3.name = "reload2_back";
	Locations[FindLocation(locationID)].reload.l3.autoreload = "0";
	Locations[FindLocation(locationID)].monsters = "0";
	LAi_LocationFightDisable(Locations[FindLocation(locationID)], true);
}

void InitBrothelRoom(string locationID)
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Inside\brothel_room";
	Locations[FindLocation(locationID)].image = "Brothel_room.tga";
	//Models
	Locations[FindLocation(locationID)].models.back = "..\back\inside_back_";
	//Always
	Locations[FindLocation(locationID)].models.always.cave = "brothel_room";
	Locations[FindLocation(locationID)].models.always.locators = "brothel_room_locators";
	Locations[FindLocation(locationID)].models.always.window = "brothel_room_window";
	Locations[FindLocation(locationID)].models.always.window.tech = "LocationWindows";
	Locations[FindLocation(locationID)].models.always.window.level = 50;
	//Day
	Locations[FindLocation(locationID)].models.day.charactersPatch = "brothel_room_patch";
	//Night
	Locations[FindLocation(locationID)].models.night.charactersPatch = "brothel_room_patch";
	//Environment
	Locations[FindLocation(locationID)].environment.weather = "false";
	Locations[FindLocation(locationID)].environment.sea = "false";

	//Reload map
	Locations[FindLocation(locationID)].reload.l1.name = "reload1";
	Locations[FindLocation(locationID)].reload.l1.autoreload = "0";
	LAi_LocationFightDisable(&Locations[FindLocation(locationID)], true);
	LAi_LocationMonstersGen(&Locations[FindLocation(locationID)], false);
}

void InitTavern4(string locationID)//originally from AOP Guadeloupe town
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Inside\Tavern04";
	Locations[FindLocation(locationID)].image = "Tavern04.tga";
	//Models
	Locations[FindLocation(locationID)].models.back = "..\back\inside_back_";
	//Always
	Locations[FindLocation(locationID)].models.always.cave = "Tavern04";
	Locations[FindLocation(locationID)].models.always.locators = "Tavern04_locators";
	Locations[FindLocation(locationID)].models.always.window = "Tavern04_window";
	Locations[FindLocation(locationID)].models.always.window.tech = "LocationWindows";
	Locations[FindLocation(locationID)].models.always.window.level = 50;
	//Day
	Locations[FindLocation(locationID)].models.day.charactersPatch = "Tavern04_patch";
	//Night
	Locations[FindLocation(locationID)].models.night.charactersPatch = "Tavern04_patch";
	//Environment
	Locations[FindLocation(locationID)].environment.weather = "false";
	Locations[FindLocation(locationID)].environment.sea = "false";

	//Reload map
	Locations[FindLocation(locationID)].reload.l1.name = "reload1";
	Locations[FindLocation(locationID)].reload.l1.emerge = "reload4_back";
	Locations[FindLocation(locationID)].reload.l1.autoreload = "0";

	Locations[FindLocation(locationID)].reload.l2.name = "reload2";
	Locations[FindLocation(locationID)].reload.l2.emerge = "reload1";
	Locations[FindLocation(locationID)].reload.l2.autoreload = "0";
}

void InitTavern1(string locationID)//originally from AOP Montserrat town
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Inside\Tavern01";
	Locations[FindLocation(locationID)].image = "Tavern01.tga";
	//Models
	Locations[FindLocation(locationID)].models.back = "..\back\inside_back_";
	//Always
	Locations[FindLocation(locationID)].models.always.cave = "Tavern01";
	Locations[FindLocation(locationID)].models.always.locators = "Tavern01_locators";
	Locations[FindLocation(locationID)].models.always.window = "Tavern01_windows";
	Locations[FindLocation(locationID)].models.always.window.tech = "LocationWindows";
	Locations[FindLocation(locationID)].models.always.window.level = 50;
	//Day
	Locations[FindLocation(locationID)].models.day.charactersPatch = "Tavern01_patch";
	//Night
	Locations[FindLocation(locationID)].models.night.charactersPatch = "Tavern01_patch";
	//Environment
	Locations[FindLocation(locationID)].environment.weather = "false";
	Locations[FindLocation(locationID)].environment.sea = "false";

	//Reload map
	Locations[FindLocation(locationID)].reload.l1.name = "reload1";
	Locations[FindLocation(locationID)].reload.l1.emerge = "reload4_back";
	Locations[FindLocation(locationID)].reload.l1.autoreload = "0";

	Locations[FindLocation(locationID)].reload.l2.name = "reload2";
	Locations[FindLocation(locationID)].reload.l2.emerge = "reload1";
	Locations[FindLocation(locationID)].reload.l2.autoreload = "0";
}

void InitStoneHouse(string locationID)
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Inside\StoneHouse";
	Locations[FindLocation(locationID)].image = "Stonehouse.tga";
	//Models
	Locations[FindLocation(locationID)].models.back = "..\back\inside_back_";
	//Always
	Locations[FindLocation(locationID)].models.always.cave = "StoneHouse";
	Locations[FindLocation(locationID)].models.always.locators = "StoneHouse_locators";
	Locations[FindLocation(locationID)].models.always.window = "StoneHouse_window";
	Locations[FindLocation(locationID)].models.always.window.tech = "LocationWindows";
	Locations[FindLocation(locationID)].models.always.window.level = 50;
	//Day
	Locations[FindLocation(locationID)].models.day.charactersPatch = "StoneHouse_patch";
	//Night
	Locations[FindLocation(locationID)].models.night.charactersPatch = "StoneHouse_patch";
	//Environment
	Locations[FindLocation(locationID)].environment.weather = "false";
	Locations[FindLocation(locationID)].environment.sea = "false";

	//Reload map
	Locations[FindLocation(locationID)].reload.l1.name = "reload1";
	Locations[FindLocation(locationID)].reload.l1.autoreload = "0";
}

void InitHut(string locationID)
{
	Locations[FindLocation(locationID)].filespath.models = "locations\AOPtowns\Inside\hut";
	Locations[FindLocation(locationID)].image = "hut.tga";
	//Models
	Locations[FindLocation(locationID)].models.back = "..\back\inside_back_";
	//Always
	Locations[FindLocation(locationID)].models.always.cave = "hut";
	Locations[FindLocation(locationID)].models.always.locators = "hut_locators";
	Locations[FindLocation(locationID)].models.always.window = "hut_window";
	Locations[FindLocation(locationID)].models.always.window.tech = "LocationWindows";
	Locations[FindLocation(locationID)].models.always.window.level = 50;
	//Day
	Locations[FindLocation(locationID)].models.day.charactersPatch = "hut_patch";
	//Night
	Locations[FindLocation(locationID)].models.night.charactersPatch = "hut_patch";
	//Environment
	Locations[FindLocation(locationID)].environment.weather = "false";
	Locations[FindLocation(locationID)].environment.sea = "false";

	//Reload map
	Locations[FindLocation(locationID)].reload.l1.name = "reload2";
	Locations[FindLocation(locationID)].reload.l1.emerge = "";
	Locations[FindLocation(locationID)].reload.l1.autoreload = "0";

	Locations[FindLocation(locationID)].reload.l2.name = "reload1";
	Locations[FindLocation(locationID)].reload.l2.emerge = "";
	Locations[FindLocation(locationID)].reload.l2.autoreload = "0";

	LAi_LocationMonstersGen(&Locations[FindLocation(locationID)], false);
}
//======================================| NEW AOP TOWNS |======================================//

//=========================| ISLA DE MUERTE (based on AOP Isla Mona) |=========================//
void CreateIslaDeMuerte()
{
	if(FindIsland("IslaDeMuerte")!=-1) { IslaDeMuerteWorldMapInit(); return; }
	DirectsailAddBattle_Rocks();
	object	locator;
	CreateEntity(&locator,"locator");

	Islands[ISLANDS_QUANTITY].reload_enable = true;
	Islands[ISLANDS_QUANTITY].visible = true;

	Islands[ISLANDS_QUANTITY].id = "IslaDeMuerte";
	Islands[ISLANDS_QUANTITY].model = "islamona";
	Islands[ISLANDS_QUANTITY].filespath.models = "islands\IslaDeMuerte";
	Islands[ISLANDS_QUANTITY].refl_model = "islamona_refl";
	Islands[ISLANDS_QUANTITY].locators = "islamona_locators";
	Islands[ISLANDS_QUANTITY].visible = false;
	Islands[ISLANDS_QUANTITY].Enc_enable = false;
	Islands[ISLANDS_QUANTITY].smuggling_nation = PIRATE;
	Islands[ISLANDS_QUANTITY].towns.quantity = 10;//Cities - way for adding new model into the WorldMap

	Islands[ISLANDS_QUANTITY].reload.l1.old.label = "Deserted shore";
	Islands[ISLANDS_QUANTITY].reload.l1.label = TranslateString("","Deserted shore");
	Islands[ISLANDS_QUANTITY].reload.l1.name = "reload_1";
	Islands[ISLANDS_QUANTITY].reload.l1.go = "IslaDeMuerte_shore_01";
	Islands[ISLANDS_QUANTITY].reload.l1.emerge = "reload1";
	Islands[ISLANDS_QUANTITY].reload.l1.radius = 200.0;
	Islands[ISLANDS_QUANTITY].reload.l1.pic = 2;
	Islands[ISLANDS_QUANTITY].reload.l1.tex = "t1";
	Islands[ISLANDS_QUANTITY].reload.l1.ships.l0.x = 430.0;
	Islands[ISLANDS_QUANTITY].reload.l1.ships.l0.z = -680.0;
	Islands[ISLANDS_QUANTITY].reload.l1.ships.l0.ay = 0.0;

	Islands[ISLANDS_QUANTITY].reload.l2.old.label = "Dead Man's Bay";
	Islands[ISLANDS_QUANTITY].reload.l2.label = TranslateString("","Dead Man's Bay");
	Islands[ISLANDS_QUANTITY].reload.l2.name = "reload_2";
	Islands[ISLANDS_QUANTITY].reload.l2.go = "IslaDeMuerte_shore_02";
	Islands[ISLANDS_QUANTITY].reload.l2.emerge = "sea_back";
	Islands[ISLANDS_QUANTITY].reload.l2.radius = 200.0;
	Islands[ISLANDS_QUANTITY].reload.l2.pic = 2;
	Islands[ISLANDS_QUANTITY].reload.l2.tex = "t2";
	Islands[ISLANDS_QUANTITY].reload.l2.ships.l0.x = 430.0;
	Islands[ISLANDS_QUANTITY].reload.l2.ships.l0.z = -680.0;
	Islands[ISLANDS_QUANTITY].reload.l2.ships.l0.ay = 0.0;

	Islands[ISLANDS_QUANTITY].reload.l3.old.label = "Witch's Rock";
	Islands[ISLANDS_QUANTITY].reload.l3.label = TranslateString("","Witch's Rock");
	Islands[ISLANDS_QUANTITY].reload.l3.name = "reload_3";
	Islands[ISLANDS_QUANTITY].reload.l3.go = "IslaDeMuerte_shore_03";
	Islands[ISLANDS_QUANTITY].reload.l3.emerge = "reload1";
	Islands[ISLANDS_QUANTITY].reload.l3.radius = 200.0;
	Islands[ISLANDS_QUANTITY].reload.l3.pic = 2;
	Islands[ISLANDS_QUANTITY].reload.l3.tex = "t3";
	Islands[ISLANDS_QUANTITY].reload.l3.ships.l0.x = 430.0;
	Islands[ISLANDS_QUANTITY].reload.l3.ships.l0.z = -680.0;
	Islands[ISLANDS_QUANTITY].reload.l3.ships.l0.ay = 0.0;

	Islands[ISLANDS_QUANTITY].InterfaceTextures.t1 = "battle_interface\moor_7.tga";
	Islands[ISLANDS_QUANTITY].InterfaceTextures.t1.h = 4;
	Islands[ISLANDS_QUANTITY].InterfaceTextures.t1.v = 1;

	Islands[ISLANDS_QUANTITY].InterfaceTextures.t2 = "battle_interface\moor_8.tga";
	Islands[ISLANDS_QUANTITY].InterfaceTextures.t2.h = 4;
	Islands[ISLANDS_QUANTITY].InterfaceTextures.t2.v = 1;

	Islands[ISLANDS_QUANTITY].InterfaceTextures.t3 = "battle_interface\moor_3.tga";
	Islands[ISLANDS_QUANTITY].InterfaceTextures.t3.h = 4;
	Islands[ISLANDS_QUANTITY].InterfaceTextures.t3.v = 1;

	SendMessage(&locator,"le",LM_LOCATE_I,&Islands[ISLANDS_QUANTITY]);
	ISLANDS_QUANTITY = ISLANDS_QUANTITY+1;

	DeleteClass(&locator);
	nLocationsNum = InitIslaDeMuerte(nLocationsNum);
	IslaDeMuerteWorldMapInit();
}

int InitIslaDeMuerte(int n)
{
	if(GetLocationIndex("IslaDeMuerte_shore_01")!=-1) return n;
	// -------------------------------------------------
	Locations[n].id = "IslaDeMuerte_shore_01";
	locations[n].id.label = "Deserted shore";
	locations[n].worldmap = "IslaDeMuerte";
	Locations[n].name = "Deserted shore";
	Locations[n].image = "Deserted_shore.tga";
	locations[n].filespath.models = "locations\Outside\Shore_7";

	//Sound
	locations[n].type = "treasure_cave";

	//Models
	//Always
	Locations[n].models.always.locators = "Shore07_l";
	Locations[n].models.always.shore = "Shore07";
	Locations[n].models.always.shore.foam = "1";
	Locations[n].models.always.seabed = "Shore07_sb";
	Locations[n].models.always.grassPatch = "Shore07_g";
	
	//Day
	locations[n].models.day.charactersPatch = "Shore07_p";
	//Night
	locations[n].models.night.charactersPatch = "Shore07_p";

	//Environment
	locations[n].environment.weather = "true";
	locations[n].environment.sea = "true";
	Locations[n].lockWeather = "IslaDeMuerte";

	//Reload map
	locations[n].reload.l1.name = "reload1";
	Locations[n].reload.l1.go = "IslaDeMuerte";
	Locations[n].reload.l1.emerge = "reload_1";
// KK -->
	if (VISIT_DECK == 1)
		Locations[n].reload.l1.label = "Ship.";
	else
		Locations[n].reload.l1.label = "Sea.";
// <-- KK
	locations[n].reload.l1.autoreload = "0";
	locations[n].locators_radius.reload.reload1 = 2.0;

	locations[n].reload.l2.name = "reload2_back";
	Locations[n].reload.l2.go = "Grotto";
	Locations[n].reload.l2.emerge = "reload2_back";
	Locations[n].reload.l2.label = "Treasure Cave Entrance";
	locations[n].reload.l2.autoreload = "1";
	locations[n].locators_radius.reload.reload2_back = 0.8;

	Locations[n].island = "IslaDeMuerte";
	n = n + 1;

	if(GetLocationIndex("Grotto")!=-1) return n;
	//  -------------------------------------------------
	Locations[n].id = "Grotto";
	locations[n].id.label = "Cave";
	Locations[n].image = "Treasure_cave.tga";
	locations[n].filespath.models = "locations\AOPtowns\Outside\Grotto";

	//Sound
	locations[n].type = "treasure_cave";

	//Models
	//Always
	Locations[n].models.always.town = "Grotto";
	Locations[n].models.always.seabed = "Grotto_sb";
	Locations[n].models.always.grassPatch = "Grotto_grass";
	Locations[n].models.always.locators = "Grotto_locators";
		
	Locations[n].models.always.l2 = "Gold";
	Locations[n].models.always.l2.tech = "EnvironmentShader";
	Locations[n].models.always.l2.reflection = 1;
		
	Locations[n].models.always.Water1 = "water";
	Locations[n].models.always.Water1.uvslide.v0 = 0.0;
	Locations[n].models.always.Water1.uvslide.v1 = 0.0;
	Locations[n].models.always.Water1.tech = "LocationWaterFall";
	Locations[n].models.always.Water1.level = 50;

	Locations[n].models.always.Water2 = "cfall";
	Locations[n].models.always.Water2.uvslide.v0 = 0.3;
	Locations[n].models.always.Water2.uvslide.v1 = 0.0;
	Locations[n].models.always.Water2.tech = "LocationWaterFall";
	Locations[n].models.always.Water2.level = 50;
	
	//Day
	locations[n].models.day.charactersPatch = "Grotto_patch_day";
	//Night
	locations[n].models.night.charactersPatch = "Grotto_patch_day";

	//Environment
	locations[n].environment.weather = "true";
	locations[n].environment.sea = "true";
	Locations[n].lockWeather = "IslaDeMuerte";

	//Reload map
	locations[n].reload.l1.name = "reload1_back";
	Locations[n].reload.l1.go = "IslaDeMuerte";
	Locations[n].reload.l1.emerge = "reload_1";
// KK -->
	if (VISIT_DECK == 1)
		Locations[n].reload.l1.label = "Ship.";
	else
		Locations[n].reload.l1.label = "Sea.";
// <-- KK
	Locations[n].reload.l1.desable = 1;
	locations[n].reload.l1.autoreload = "0";
	locations[n].locators_radius.reload.reload1_back = 3.0;

	locations[n].reload.l2.name = "reload2_back";
	Locations[n].reload.l2.go = "IslaDeMuerte_shore_01";
	Locations[n].reload.l2.emerge = "reload2_back";
	Locations[n].reload.l2.label = "Deserted shore";
	locations[n].reload.l2.autoreload = "1";
	locations[n].locators_radius.reload.reload2_back = 0.8;

	Locations[n].island = "IslaDeMuerte";
	n = n + 1;

	if(GetLocationIndex("IslaDeMuerte_shore_02")!=-1) return n;
	//  -------------------------------------------------
	Locations[n].filespath.models = "locations\Outside\Shore_ship";

	Locations[n].id = "IslaDeMuerte_shore_02";
	locations[n].id.label = "Dead Man's Bay";
	Locations[n].image = "IslaDeMuerte_Ship.tga";
	//Sound
	locations[n].type = "treasure_cave";

	//Models
	//Always
	Locations[n].models.always.jungle = "ShoreShip";
	Locations[n].models.always.jungle.foam = "1";
	Locations[n].models.always.locators = "ShoreShip_l";
	Locations[n].models.always.grassPatch = "ShoreShip_g";
	Locations[n].models.always.seabed = "ShoreShip_sb";
	Locations[n].models.always.seabed.foam = "1";
	Locations[n].models.always.l1 = "plan_1";
	Locations[n].models.always.l1.level = 9;
	Locations[n].models.always.l1.tech = "LocationModelBlend";
	Locations[n].models.always.l2 = "plan_2";
	Locations[n].models.always.l2.level = 8;
	Locations[n].models.always.l2.tech = "LocationModelBlend";
	Locations[n].models.always.l3 = "plan_3";
	Locations[n].models.always.l3.level = 7;
	Locations[n].models.always.l3.tech = "LocationModelBlend";

	//Day
	Locations[n].models.day.charactersPatch = "ShoreShip_p";
	//Night
	Locations[n].models.night.charactersPatch = "ShoreShip_p";

	//Environment
	Locations[n].environment.weather = "true";
	Locations[n].environment.sea = "true";
	Locations[n].lockWeather = "IslaDeMuerte";

	//Reload map
	Locations[n].reload.l1.name = "reload1";
	Locations[n].reload.l1.go = "IslaDeMuerte_cavern_1";
	Locations[n].reload.l1.emerge = "reload2";
	Locations[n].reload.l1.autoreload = "1";
	Locations[n].reload.l1.label = "The cavern";
	Locations[n].reload.l1.disable = "0";
	Locations[n].locators_radius.reload.reload1 = 0.8;

	Locations[n].reload.l2.name = "reload1_back";
	Locations[n].reload.l2.go = "IslaDeMuerte_cavern_1";
	Locations[n].reload.l2.emerge = "reload2";
	Locations[n].reload.l2.autoreload = "1";
	Locations[n].reload.l2.label = "The cavern";
	Locations[n].reload.l2.disable = "0";
	Locations[n].locators_radius.reload.reload1_back = 0.8;

	Locations[n].reload.l3.name = "reload1_cabin";
	Locations[n].reload.l3.go = "IslaDeMuerte_Cabin";
	Locations[n].reload.l3.emerge = "reload1_back";
	Locations[n].reload.l3.autoreload = "0";
	Locations[n].reload.l3.label = "Captain's Cabin";
	Locations[n].reload.l3.disable = "0";
	Locations[n].locators_radius.reload.reload1_cabin = 1.1;

	Locations[n].reload.l4.name = "reload2_cabin";
	Locations[n].reload.l4.go = "IslaDeMuerte_Cabin";
	Locations[n].reload.l4.emerge = "reload2_back";
	Locations[n].reload.l4.autoreload = "0";
	Locations[n].reload.l4.label = "Captain's Cabin";
	Locations[n].reload.l4.disable = "0";
	Locations[n].locators_radius.reload.reload2_cabin = 1.1;

	Locations[n].reload.l5.name = "sea_back";
	Locations[n].reload.l5.go = "IslaDeMuerte";
	Locations[n].reload.l5.emerge = "reload_2";
	Locations[n].reload.l5.autoreload = "0";
// KK -->
	if (VISIT_DECK == 1)
		Locations[n].reload.l5.label = "Ship.";
	else
		Locations[n].reload.l5.label = "Sea.";
// <-- KK
	Locations[n].locators_radius.reload.sea_back = 3.0;

	Locations[n].island = "IslaDeMuerte";
	n = n + 1;

	if(GetLocationIndex("IslaDeMuerte_Cabin")!=-1) return n;
	//  -------------------------------------------------
	locations[n].id = "IslaDeMuerte_Cabin";
	locations[n].id.label = "Captain's Cabin";
	locations[n].filespath.models = "locations\AOPtowns\Inside\ShipyardPirates\";
	locations[n].image = "IslaDeMuerte_Cabin.tga";

	//Sound
	locations[n].type = "treasure_cave";

	//Models	
	//Always
	locations[n].models.always.locators = "ShipyardPirates_locators";
	locations[n].models.always.shipyard = "ShipyardPirates";
	locations[n].models.always.window = "ShipyardPirates_fn";
	Locations[n].models.always.window.tech = "LocationWindows";
	Locations[n].models.always.window.level = 65532;

	//Day
	locations[n].models.day.charactersPatch = "ShipyardPirates_patch";	
	//Night
	locations[n].models.night.charactersPatch = "ShipyardPirates_patch";
	

	//Environment
	locations[n].environment.weather = "true";
	locations[n].environment.sea = "true";
	Locations[n].lockWeather = "IslaDeMuerte";

	//Reload map
	locations[n].reload.l1.name = "reload1_back";
	locations[n].reload.l1.go = "IslaDeMuerte_shore_02";
	locations[n].reload.l1.emerge = "reload1_cabin";
	locations[n].reload.l1.autoreload = "0";
	locations[n].reload.l1.label = "Dead Man's Bay";

	locations[n].reload.l2.name = "reload2_back";
	locations[n].reload.l2.go = "IslaDeMuerte_shore_02";
	locations[n].reload.l2.emerge = "reload2_cabin";
	locations[n].reload.l2.autoreload = "0";
	locations[n].reload.l2.label = "Dead Man's Bay";

	Locations[n].island = "IslaDeMuerte";
	n = n + 1;

	if(GetLocationIndex("IslaDeMuerte_Cavern_1")!=-1) return n;
	//  -------------------------------------------------
	Locations[n].filespath.models = "locations\Inside\Cavern";

	Locations[n].id = "IslaDeMuerte_Cavern_1";
	locations[n].id.label = "Cavern";
	Locations[n].image = "Douwesen_Cavern.tga";

	//Sound
	locations[n].type = "treasure_cave";

	//Models
	//Always
	Locations[n].models.always.locators = "cavern_l";
	Locations[n].models.always.l1 = "cavern";
	Locations[n].models.always.l2 = "Crystals";
	Locations[n].models.always.l2.tech = "EnvironmentShader";
	Locations[n].models.always.l2.reflection = 0.25;

	Locations[n].models.always.Waterfall1 = "water";
	Locations[n].models.always.Waterfall1.uvslide.v0 = 0.0;
    Locations[n].models.always.Waterfall1.uvslide.v1 = 0.0;
    Locations[n].models.always.Waterfall1.tech = "LocationWaterFall";
	Locations[n].models.always.Waterfall1.level = 50;

	Locations[n].models.always.Waterfall2 = "cfall";
	Locations[n].models.always.Waterfall2.uvslide.v0 = 0.3;
    Locations[n].models.always.Waterfall2.uvslide.v1 = 0.0;
	Locations[n].models.always.Waterfall2.tech = "LocationWaterFall";
	Locations[n].models.always.Waterfall2.level = 50;

	//Day
	Locations[n].models.day.charactersPatch = "cavern_p";
	//Night
	Locations[n].models.night.charactersPatch = "cavern_p";

	//Environment
	Locations[n].environment.weather = "true";
	Locations[n].environment.sea = "false";
	Locations[n].lockWeather = "IslaDeMuerte";

	//Reload map
	//Reload map
	Locations[n].reload.l1.name = "reload2";
	Locations[n].reload.l1.go = "IslaDeMuerte_shore_02";
	Locations[n].reload.l1.emerge = "reload1";
	Locations[n].reload.l1.autoreload = "1";
	Locations[n].reload.l1.disable = "0";
	Locations[n].reload.l1.label = "Dead Man's Bay";
	Locations[n].locators_radius.reload.reload2 = 0.8;

	Locations[n].reload.l2.name = "reload2_back";
	Locations[n].reload.l2.go = "IslaDeMuerte_shore_02";
	Locations[n].reload.l2.emerge = "reload1";
	Locations[n].reload.l2.autoreload = "1";
	Locations[n].reload.l2.disable = "0";
	Locations[n].reload.l2.label = "Dead Man's Bay";
	Locations[n].locators_radius.reload.reload2_back = 0.8;

	Locations[n].reload.l3.name = "reload1";
	Locations[n].reload.l3.go = "IslaDeMuerte_Cavern_2";
	Locations[n].reload.l3.emerge = "reload1";
	Locations[n].reload.l3.autoreload = "1";
	Locations[n].reload.l3.label = "Dead Man's Bay";
	Locations[n].reload.l3.disable = "0";
	Locations[n].locators_radius.reload.reload1 = 0.8;

	Locations[n].reload.l4.name = "reload1_back";
	Locations[n].reload.l4.go = "IslaDeMuerte_Cavern_2";
	Locations[n].reload.l4.emerge = "reload1";
	Locations[n].reload.l4.autoreload = "1";
	Locations[n].reload.l4.label = "Dead Man's Bay";
	Locations[n].reload.l4.disable = "0";
	Locations[n].locators_radius.reload.reload1_back = 0.8;

	Locations[n].island = "IslaDeMuerte";
	n = n + 1;

	if(GetLocationIndex("IslaDeMuerte_Cavern_2")!=-1) return n;
	//  -------------------------------------------------
	Locations[n].filespath.models = "locations\Inside\Grot";

	Locations[n].id = "IslaDeMuerte_Cavern_2";
	locations[n].id.label = "Cavern";
	Locations[n].image = "Conceicao_Cave.tga";

	//Sound
	locations[n].type = "treasure_cave";

	//Models
	Locations[n].models.back = "back\grotenv_";
	//Always
	Locations[n].models.always.cave = "Grot";
	Locations[n].models.always.locators = "Grot_l";

	//Day
	Locations[n].models.day.charactersPatch = "Grot_p";
	//Night
	Locations[n].models.night.charactersPatch = "Grot_p";

	//Environment
	Locations[n].environment.weather = "true";
	Locations[n].environment.sea = "false";
	Locations[n].lockWeather = "IslaDeMuerte";

	//Reload map
	Locations[n].reload.l1.name = "reload1";
	Locations[n].reload.l1.go = "IslaDeMuerte_Cavern_1";
	Locations[n].reload.l1.emerge = "reload1";
	Locations[n].reload.l1.autoreload = "1";
	Locations[n].reload.l1.disable = "0";
	Locations[n].reload.l1.label = "Cavern";
	Locations[n].locators_radius.reload.reload1 = 0.8;

	Locations[n].reload.l2.name = "reload1_back";
	Locations[n].reload.l2.go = "IslaDeMuerte_Cavern_1";
	Locations[n].reload.l2.emerge = "reload1";
	Locations[n].reload.l2.autoreload = "1";
	Locations[n].reload.l2.disable = "0";
	Locations[n].reload.l2.label = "Cavern";
	Locations[n].locators_radius.reload.reload1_back = 0.8;

	Locations[n].island = "IslaDeMuerte";
	n = n + 1;

	if(GetLocationIndex("IslaDeMuerte_shore_03")!=-1) return n;
   	// -------------------------------------------------
    Locations[n].id = "IslaDeMuerte_shore_03";
	locations[n].id.label = "Witch's Rock";
	Locations[n].filespath.models = "locations\Outside\Shore_3";
	Locations[n].image = "Witch_rock.tga";
	Locations[n].name = "Witch's Rock";

 	//Sound
	locations[n].type = "treasure_cave";

   	//Models
	//Always
	Locations[n].models.always.jungle = "shore03";
	Locations[n].models.always.jungle.foam = "1";
	Locations[n].models.always.locators = "shore03_l";
    Locations[n].models.always.seabed = "shore03_sb";
	Locations[n].models.always.seabed.foam = "1";
	Locations[n].models.always.grassPatch = "Shore03_g";

	Locations[n].models.always.l1 = "plan_1";
	Locations[n].models.always.l1.level = 9;
	Locations[n].models.always.l1.tech = "LocationModelBlend";
	Locations[n].models.always.l2 = "plan_2";
	Locations[n].models.always.l2.level = 8;
	Locations[n].models.always.l2.tech = "LocationModelBlend";
	Locations[n].models.always.l3 = "plan_3";
	Locations[n].models.always.l3.level = 7;
	Locations[n].models.always.l3.tech = "LocationModelBlend";

	//Day
	Locations[n].models.day.charactersPatch = "shore03_p";
	//Night
	Locations[n].models.night.charactersPatch = "shore03_p";

	//Environment
	Locations[n].environment.weather = "true";
	Locations[n].environment.sea = "true";
	Locations[n].lockWeather = "IslaDeMuerte";

	//Reload map
	Locations[n].reload.l1.name = "reload2";
	Locations[n].reload.l1.go = "";
	Locations[n].reload.l1.emerge = "";
	Locations[n].reload.l1.autoreload = "1";
	Locations[n].reload.l1.label = "";
	Locations[n].locators_radius.reload.reload2 = 0.8;

	Locations[n].reload.l3.name = "reload2_back";
	Locations[n].reload.l3.go = "";
	Locations[n].reload.l3.emerge = "";
	Locations[n].reload.l3.autoreload = "1";
	Locations[n].reload.l3.label = "";
	Locations[n].locators_radius.reload.reload2_back = 0.8;

 	Locations[n].reload.l2.name = "reload1";
	Locations[n].reload.l2.go = "IslaDeMuerte";
	Locations[n].reload.l2.emerge = "reload_3";
	Locations[n].reload.l2.autoreload = "0";
// KK -->
	if (VISIT_DECK == 1)
		Locations[n].reload.l2.label = "Ship.";
	else
		Locations[n].reload.l2.label = "Sea.";
// <-- KK
	Locations[n].locators_radius.reload.reload1 = 9.0;

	Locations[n].island = "IslaDeMuerte";
	n = n + 1;

	return n;
}

void IslaDeMuerteWorldMapInit()
{
	if(CheckAttribute(worldMap.islands,"IslaDeMuerte")) return;
	//Name
	worldMap.islands.IslaDeMuerte.name = "IslaDeMuerte";
	//Geometry parameters
	worldMap.islands.IslaDeMuerte.position.x = 303.0;
	worldMap.islands.IslaDeMuerte.position.y = 30.0;
	worldMap.islands.IslaDeMuerte.position.z = -596.0;
	worldMap.islands.IslaDeMuerte.position.rx = 306.7;
	worldMap.islands.IslaDeMuerte.position.rz = -587.6;
	worldMap.islands.IslaDeMuerte.radius = 40.0;
	worldMap.islands.IslaDeMuerte.kradius = 0.75;
	//Island label
	worldMap.islands.IslaDeMuerte.old.label.text = "Isla De Muerte";
	worldMap.islands.IslaDeMuerte.label.text = TranslateString("","Isla De Muerte");
	worldMap.islands.IslaDeMuerte.label.icon = -1;
	worldMap.islands.IslaDeMuerte.label.visible = "true";

	//Cities - way for adding new fake island-model into the WorldMap
	//Geometry parameters
	worldMap.islands.IslaDeMuerte.locations.city0.position.x = 303.0;
	worldMap.islands.IslaDeMuerte.locations.city0.position.y = 0.0;
	worldMap.islands.IslaDeMuerte.locations.city0.position.z = -581.0;
	worldMap.islands.IslaDeMuerte.locations.city0.position.ay = 0.0;
	worldMap.islands.IslaDeMuerte.locations.city0.modelName = "leaf";
	worldMap.islands.IslaDeMuerte.locations.city0.visible = "true";
	worldMap.islands.IslaDeMuerte.locations.city0.move = "false";
	//Geometry parameters
	worldMap.islands.IslaDeMuerte.locations.city1.position.x = 306.0;
	worldMap.islands.IslaDeMuerte.locations.city1.position.y = 0.0;
	worldMap.islands.IslaDeMuerte.locations.city1.position.z = -584.0;
	worldMap.islands.IslaDeMuerte.locations.city1.position.ay = 0.0;
	worldMap.islands.IslaDeMuerte.locations.city1.modelName = "leaf";
	worldMap.islands.IslaDeMuerte.locations.city1.visible = "true";
	worldMap.islands.IslaDeMuerte.locations.city1.move = "false";
	//Geometry parameters
	worldMap.islands.IslaDeMuerte.locations.city2.position.x = 306.0;
	worldMap.islands.IslaDeMuerte.locations.city2.position.y = 0.0;
	worldMap.islands.IslaDeMuerte.locations.city2.position.z = -587.0;
	worldMap.islands.IslaDeMuerte.locations.city2.position.ay = 0.0;
	worldMap.islands.IslaDeMuerte.locations.city2.modelName = "leaf";
	worldMap.islands.IslaDeMuerte.locations.city2.visible = "true";
	worldMap.islands.IslaDeMuerte.locations.city2.move = "false";
	//Geometry parameters
	worldMap.islands.IslaDeMuerte.locations.city3.position.x = 303.0;
	worldMap.islands.IslaDeMuerte.locations.city3.position.y = 0.0;
	worldMap.islands.IslaDeMuerte.locations.city3.position.z = -591.0;
	worldMap.islands.IslaDeMuerte.locations.city3.position.ay = 0.0;
	worldMap.islands.IslaDeMuerte.locations.city3.modelName = "leaf";
	worldMap.islands.IslaDeMuerte.locations.city3.visible = "true";
	worldMap.islands.IslaDeMuerte.locations.city3.move = "false";
	//Geometry parameters
	worldMap.islands.IslaDeMuerte.locations.city4.position.x = 303.0;
	worldMap.islands.IslaDeMuerte.locations.city4.position.y = 0.0;
	worldMap.islands.IslaDeMuerte.locations.city4.position.z = -596.0;
	worldMap.islands.IslaDeMuerte.locations.city4.position.ay = 0.0;
	worldMap.islands.IslaDeMuerte.locations.city4.modelName = "leaf";
	worldMap.islands.IslaDeMuerte.locations.city4.visible = "true";
	worldMap.islands.IslaDeMuerte.locations.city4.move = "false";
	//Geometry parameters
	worldMap.islands.IslaDeMuerte.locations.city5.position.x = 305.0;
	worldMap.islands.IslaDeMuerte.locations.city5.position.y = 0.0;
	worldMap.islands.IslaDeMuerte.locations.city5.position.z = -581.0;
	worldMap.islands.IslaDeMuerte.locations.city5.position.ay = 2.0;
	worldMap.islands.IslaDeMuerte.locations.city5.modelName = "leaf";
	worldMap.islands.IslaDeMuerte.locations.city5.visible = "true";
	worldMap.islands.IslaDeMuerte.locations.city5.move = "false";
	//Geometry parameters
	worldMap.islands.IslaDeMuerte.locations.city6.position.x = 308.0;
	worldMap.islands.IslaDeMuerte.locations.city6.position.y = 0.0;
	worldMap.islands.IslaDeMuerte.locations.city6.position.z = -584.0;
	worldMap.islands.IslaDeMuerte.locations.city6.position.ay = 2.0;
	worldMap.islands.IslaDeMuerte.locations.city6.modelName = "leaf";
	worldMap.islands.IslaDeMuerte.locations.city6.visible = "true";
	worldMap.islands.IslaDeMuerte.locations.city6.move = "false";
	//Geometry parameters
	worldMap.islands.IslaDeMuerte.locations.city7.position.x = 309.0;
	worldMap.islands.IslaDeMuerte.locations.city7.position.y = 0.0;
	worldMap.islands.IslaDeMuerte.locations.city7.position.z = -587.0;
	worldMap.islands.IslaDeMuerte.locations.city7.position.ay = 3.0;
	worldMap.islands.IslaDeMuerte.locations.city7.modelName = "leaf";
	worldMap.islands.IslaDeMuerte.locations.city7.visible = "true";
	worldMap.islands.IslaDeMuerte.locations.city7.move = "false";
	//Geometry parameters
	worldMap.islands.IslaDeMuerte.locations.city8.position.x = 303.0;
	worldMap.islands.IslaDeMuerte.locations.city8.position.y = 0.0;
	worldMap.islands.IslaDeMuerte.locations.city8.position.z = -591.0;
	worldMap.islands.IslaDeMuerte.locations.city8.position.ay = 1.0;
	worldMap.islands.IslaDeMuerte.locations.city8.modelName = "leaf";
	worldMap.islands.IslaDeMuerte.locations.city8.visible = "true";
	worldMap.islands.IslaDeMuerte.locations.city8.move = "false";
	//Geometry parameters
	worldMap.islands.IslaDeMuerte.locations.city9.position.x = 305.0;
	worldMap.islands.IslaDeMuerte.locations.city9.position.y = 0.0;
	worldMap.islands.IslaDeMuerte.locations.city9.position.z = -596.0;
	worldMap.islands.IslaDeMuerte.locations.city9.position.ay = 2.0;
	worldMap.islands.IslaDeMuerte.locations.city9.modelName = "leaf";
	worldMap.islands.IslaDeMuerte.locations.city9.visible = "true";
	worldMap.islands.IslaDeMuerte.locations.city9.move = "false";
}

void DeleteIslaDeMuerte()
{
	if(FindIsland("IslaDeMuerte")!=-1)
	{
		Islands[FindIsland("IslaDeMuerte")].reload_enable = false;
		Islands[FindIsland("IslaDeMuerte")].visible = false;
		aref ourMap; makearef(ourMap,worldMap.islands);
		DeleteAttribute(ourMap,"IslaDeMuerte");
		if(wdmCurrentIsland=="IslaDeMuerte") wdmCurrentIsland = WDM_NONE_ISLAND;
	}
}
//=========================| ISLA DE MUERTE (based on AOP Isla Mona) |=========================//

//=====================| CODE BELOW WILL BE USED FOR AI OF ALL CHARACTERS |=====================//
void CharacterSideStepControl(ref chr, float mag, bool onoff)
{
	if(onoff)
	{
		if(!CheckAttribute(chr, "sidestep"))
		{
			chr.sidestep = mag;
			event("sidestep_event", "l", sti(chr.index));
		}
	}
	else { DeleteAttribute(chr, "sidestep"); }
}

void Lai_ReturnToNormal()
{
	aref chr = GetEventData();
	string curAction = GetEventData();
	DelEventHandler("Lai_EndStraifAction","Lai_ReturnToNormal");

	CharacterPlayAction(chr, "");
	CharacterSideStepControl(chr, -STRAIF_DIST, false);
	CharacterSideStepControl(chr, STRAIF_DIST, false);

	if(!CheckAttribute(chr,"straif")) return;

	if(HasSubStr(curAction, "left"))
	{
		LAi_EventDelay("DoStraifLeft","CharacterDoStraifLeft",600, chr, curAction);
	}
	if(HasSubStr(curAction, "right"))
	{
		LAi_EventDelay("DoStraifRight","CharacterDoStraifRight",600, chr, curAction);
	}
}

#event_handler("DoSideStep", "CheckSideStep");
void CheckSideStep()
{
	aref chr = GetEventData();
	if(CharacterIsDead(chr) || !IsEntity(chr)) return;

	string leftAnimation, rightAnimation, bAction;

	if(LAi_IsFightMode(chr))
	{
		leftAnimation = "straif_weapon_left";
		rightAnimation = "straif_weapon_right";
	}
	else
	{
		leftAnimation = "straif_left";
		rightAnimation = "straif_right";
	}
	bAction = leftAnimation+","+rightAnimation;
	chr.straif = true;

	string curAction = GetRandSubString(bAction);

	if(HasSubStr(curAction, "left"))
	{
		SetEventHandler("DoStraifLeft","CharacterDoStraifLeft",0);
		PostEvent("DoStraifLeft", 0, "is", chr, curAction);
	}
	if(HasSubStr(curAction, "right"))
	{
		SetEventHandler("DoStraifRight","CharacterDoStraifRight",0);
		PostEvent("DoStraifRight", 0, "is", chr, curAction);
	}
}

void CharacterDoStraifLeft()
{
	aref chr = GetEventData();
	string leftAnimation = GetEventData();
	DelEventHandler("DoStraifLeft","CharacterDoStraifLeft");

	string curAction;
	float stepDist = SIDESTEP_DIST;

	if(HasSubStr(leftAnimation, "weapon")) { curAction = "straif_weapon_right"; stepDist = 0.1; }
	else curAction = "straif_right";

	if(StraifCharacter(chr) && CheckAttribute(chr,"location") && FindLocation(chr.location)!=-1) 
	{
		stepDist = STRAIF_DIST;
		if(HasSubStr(leftAnimation, "weapon")) { stepDist = 0.1; }
		CharacterPlayAction(chr, leftAnimation); 
		CharacterSideStepControl(chr, -stepDist, true);
	}
	else 
	{ 
		if(CheckAttribute(chr,"location") && FindLocation(chr.location)!=-1) CharacterSideStepControl(chr, -stepDist, true);
	}

	SetEventHandler("Lai_EndStraifAction", "Lai_ReturnToNormal",0);
	PostEvent("Lai_EndStraifAction", 250, "is", chr, curAction);
}

void CharacterDoStraifRight()
{
	aref chr = GetEventData();
	string rightAnimation = GetEventData();
	DelEventHandler("DoStraifRight","CharacterDoStraifRight");

	string curAction;
	float stepDist = SIDESTEP_DIST;

	if(HasSubStr(rightAnimation, "weapon")) { curAction = "straif_weapon_left"; stepDist = 0.1; }
	else curAction = "straif_left";

	if(StraifCharacter(chr) && CheckAttribute(chr,"location") && FindLocation(chr.location)!=-1) 
	{
		stepDist = STRAIF_DIST;
		if(HasSubStr(rightAnimation, "weapon")) { stepDist = 0.1; }
		CharacterPlayAction(chr, rightAnimation); 
		CharacterSideStepControl(chr, stepDist, true);
	}
	else 
	{ 
		if(CheckAttribute(chr,"location") && FindLocation(chr.location)!=-1) CharacterSideStepControl(chr, stepDist, true);
	}

	SetEventHandler("Lai_EndStraifAction", "Lai_ReturnToNormal",0);
	PostEvent("Lai_EndStraifAction", 250, "is", chr, curAction);
}

void LAi_EventDelay(string evName, string evFunction, int evDelay, ref evChr, string evAction)
{
	DeleteAttribute(evChr,"straif");
	SetEventHandler(evName,evFunction,0);
	PostEvent(evName, sti(evDelay+200), "is", evChr, evAction);
}
//========================| CODE WILL BE USED FOR AI OF ALL CHARACTERS |========================//

int DeleteLocation(int n, string locID)
{
	int locNum = n;
	if(GetLocationIndex(locID)<sti(n-1))
	{
		for(int i=GetLocationIndex(locID); i<n; i++)
		{
			DeleteAttribute(&locations[i],"");
			if(sti(i+1)<n) CopyAttributes(&locations[i],&locations[sti(i+1)]);
			locNum = i;
		}
	}
	else
	{
		DeleteAttribute(&locations[GetLocationIndex(locID)],"");
		locNum = locNum - 1;
	}

	return locNum;
}

void CharacterIntoLocationLocator(int idx, string locationID)
{
	string offLocat = "";
	string offGroup = "";
	offLocat = LAi_FindIndexedLocator(locationID, "officers","reload");
	if(offLocat!="") { offGroup = "officers"; }
	else
	{
		offLocat = LAi_FindIndexedLocator(locationID, "reload","reload");
		if(offLocat!="") { offGroup = "reload"; }
		else
		{
			offLocat = LAi_FindIndexedLocator(locationID, "goto","goto");
			if(offLocat!="") { offGroup = "goto"; }
			else
			{
				offLocat = LAi_FindIndexedLocator(locationID, "rld","loc");
				if(offLocat!="") { offGroup = "rld"; }
				else { offLocat = ""; }
			}
		}
	}
	if(offLocat!="")
	{
		if(offLocat!=Characters[GetMainCharacterIndex()].location.locator)
		{
			ChangeCharacterAddressGroup(GetCharacter(idx), locationID, offGroup, offLocat);
		}
	}
	else { trace("No free locators in location "+locationID); }
}

string LAi_FindFirstLocationLocator(string locId, string group)//Function [LAi_FindFirstLocator] already declared in elrapido.c, but seems to be not working
{
	string at = "locators." + group;
	if(CheckAttribute(&locations[FindLocation(locId)], at) == 0) return "";
	aref grp;
	makearef(grp, locations[FindLocation(locId)].(at));
	int num = GetAttributesNum(grp);
	if(num <= 0) return "";
	return GetAttributeName(GetAttributeN(grp, 1));
}

string LAi_FindIndexedLocator(string locId, string group, string locname)
{
	string at = "locators." + group;
	if(CheckAttribute(&locations[FindLocation(locId)], at) == 0) return "";
	aref grp;
	makearef(grp, locations[FindLocation(locId)].(at));
	int num = GetAttributesNum(grp);
	if(num <= 0) return "";
	string curLocLocator = "";
	for(int i=0; i<num; i++)
	{
		curLocLocator = GetAttributeName(GetAttributeN(grp, i));
		if(curLocLocator=="") return "";
		if(locname=="") return "";
		if(!CheckAttribute(grp,curLocLocator+".indexed"))
		{
			if(strleft(curLocLocator,3)==locname || strleft(curLocLocator,4)==locname || strleft(curLocLocator,6)==locname || strleft(curLocLocator,7)==locname)
			{
				grp.(curLocLocator).indexed = true;
				return curLocLocator;
			}
		}
	}
	return "";
}

void LAi_ClearIndexedLocators(string locId, string group)
{
	string at = "locators." + group;
	if(CheckAttribute(&locations[FindLocation(locId)], at) == 0) return;
	aref grp;
	makearef(grp, locations[FindLocation(locId)].(at));
	int num = GetAttributesNum(grp);
	if(num <= 0) return; // KK
	string curLocLocator = "";
	for(int i=0; i<num; i++)
	{
		curLocLocator = GetAttributeName(GetAttributeN(grp, i));
		if(CheckAttribute(grp,curLocLocator+".indexed"))
		{
			DeleteAttribute(grp,curLocLocator+".indexed");
		}
	}
}

//MAXIMUS: coded by KK, changed by MAXIMUS ;) changes made by MAXIMUS changed by KK :) and changed by MAXIMUS ;b -->
void CheckReloadAction(ref chr, string actionType)
{
	//MAXIMUS: changes made here, will prevent showing of empty-reloads and showing reloads on enemy's ship
	if (FindLoadedLocation() == -1) {
		Log_SetActiveAction("Nothing");
		return;
	}

	if (bMutinyDeckStarted) {
		if (LAi_group_IsActivePlayerAlarm()) {
			Log_SetActiveAction("Nothing");
			return;
		}
		Log_SetActiveAction("ToSea");
		return;
	}

	if (LAi_IsBoardingProcess()) {
		if (LAi_group_IsActivePlayerAlarm()) {
			Log_SetActiveAction("Nothing");
			return;
		}
		if (CheckAttribute(chr, "boardingReload") && sti(chr.boardingReload) == 1) {
			if (CheckAttribute(chr, "TalkWithSurrenderedCaptain")) {
				Log_SetActiveAction("Nothing");
				return;
			}
			if (Locations[boarding_location].id == GetCharacterShipCabin(boarding_enemy) || CharacterIsDead(refEnCharacter) || IsPassenger(refEnCharacter) || IsCompanion(refEnCharacter)) {
				if (!isFort && !isTown) {
					Log_SetActiveAction("ToSea");
					return;
				}
			}
			if (isFort) {
				if (nfort == GetFortBoardingLocationsCount()) {
					Log_SetActiveAction("ToTown");
					return;
				}
			}
			if (isTown) {
				string sdistrict = "l" + (cdistrict + 1);
				if (GetTownIndex(boarding_enemy.town) >= 0) {
					if (!CheckAttribute(Towns[GetTownIndex(boarding_enemy.town)], "boarding." + sdistrict)) {
						if (GetTownGovernorIndex(boarding_enemy.town) > 0)
							Log_SetActiveAction("ToResidence");
						else
							Log_SetActiveAction("ToTown");
						return;
					}
				}
			}
			Log_SetActiveAction("ToFightDeck");
			return;
		}
	}

	if (bAbordageStarted && !ownDeckStarted()) {
		Log_SetActiveAction("Nothing");
		return;
	}
	if (chrWaitReloadLocator == "") {
		Log_SetActiveAction("Nothing");
		return;
	}

	string reloadType = actionType;
	if (!chrIsNowEnableReload()) reloadType = "Closed";

	if (actionType == "" && reloadType != "Closed") {
		reloadType = "Reload";
		if (CheckAttribute(chr, "reloadStatus"))
		{
			reloadType = chr.reloadStatus;
		}
	}

	if (reloadType == "Closed" && chrCheckReloadLink(&Locations[FindLocation(chr.location)], chrWaitReloadLocator) == 0) reloadType = "Nothing"; // MAXIMUS
	if (reloadType == "ToSea" || reloadType == "ToBoat") {
		if (GetCharacterShipType(chr) == SHIP_NOTUSED) reloadType = "Nothing";
	}

	Log_SetActiveAction(reloadType);
}
//MAXIMUS: coded by KK, changed by MAXIMUS <--

void CheckCharacterAction()
{
	ref mchref = GetMainCharacter();
	if(FindLocation(mchref.location)==-1)
	{
		Log_SetActiveAction("Nothing");
		CheckReloadAction(mchref, "");
		return;
	}

	bool bUpdate = !CheckAttribute(mchref,"reloadStatus.update") && !CheckAttribute(mchref,"Interlocutor.update") && !CheckAttribute(mchref,"BoxName.update") && !CheckAttribute(mchref,"activeItem.update") && !dialogRun && !dialogSelf;
	if(CheckAttribute(mchref,"boxname"))
	{
		if(mchref.boxname == "WeaponsLocker") { Log_SetActiveAction("OpenWeaponsLocker"); }
		else
		{
			if(HasSubStr(mchref.boxname, "gunpowder")) { Log_SetActiveAction("OpenBarrel"); }
			else
			{
				if(HasSubStr(mchref.boxname, "box"))
				{
					if(HasSubStr(mchref.boxname, "corpse_box")) { Log_SetActiveAction("Corpse"); }
					else { Log_SetActiveAction("OpenBox"); }
				}
				else { if(bUpdate) { DeleteAttribute(mchref, "boxname"); Log_SetActiveAction("Nothing"); CheckReloadAction(mchref, ""); return; } }
			}
		}
		if(CheckAttribute(mchref,"boxname.boxlabel") && !CheckAttribute(mchref,"boxname.update")) PostEvent("procChrOpenBox",0,"s",mchref.boxname.boxlabel);
	}
	else
	{
		if(!bUpdate) return;
		if(CheckAttribute(mchref,"activeItem.Action"))
		{
			Log_SetActiveAction(mchref.activeItem.Action);
		}
		else
		{
			Log_SetActiveAction("Nothing");
			CheckReloadAction(mchref, "");
		}
	}
}
/*
#event_handler("charUpdateItemLocator","ShowLabel");
void ShowLabel()
{
	aref chr = GetEventData();
	string label = GetEventData();
	if(IsMainCharacter(chr) && CheckAttribute(chr,"activeItem.Action") && label!="" && !dialogRun && !dialogSelf)
	{
		SetUpLogInterface(label,COLOR_GREEN_LIGHT,16,80);
		ClearAllLogStrings();
		chr.activeItem.update = true;
		PostEvent("charUpdateItemLocator",150,"is",chr,label);
		return;
	}
	if(chrWaitReloadLocator=="" && !CheckAttribute(chr,"boxname") && !CheckAttribute(chr,"Interlocutor.update"))
	{
		RestoreLogInterface();
	}
	if(CheckAttribute(chr,"activeItem.update")) DeleteAttribute(chr,"activeItem.update");
}
*/
object LocationDirectory;//finding any needed file -->

string FindFile(string dirName, string fileMask, string fileName)
{
	DeleteAttribute(&LocationDirectory, "");

	LocationDirectory.dir = dirName+"\"; // KK
	if(dirName=="") { LocationDirectory.dir = "Program\"; }
	LocationDirectory.mask = fileMask;
	CreateEntity(&LocationDirectory,"FINDFILESINTODIRECTORY");
	DeleteClass(&LocationDirectory);
	aref arList;
	makearef(arList, LocationDirectory.filelist);
	for(int i = 0; i < GetAttributesNum(arList); i++)
	{
		aref arCur = GetAttributeN(arList, i);
		string fname = GetAttributeValue(arCur);
		if(fname==fileName)
		{
			string fullname = dirName+"\"+fname;
			return fullname;
		}
	}
	return "";
}//finding any needed file <--

// KK -->
int CheckDirectory(string dirName, string fileMask)
{
	DeleteAttribute(&LocationDirectory, "");

	LocationDirectory.dir = dirName+"\\";
	if(dirName=="") { LocationDirectory.dir = "Program\\"; }
	LocationDirectory.mask = fileMask;
	CreateEntity(&LocationDirectory,"FINDFILESINTODIRECTORY");
	DeleteClass(&LocationDirectory);
	aref arList;
	makearef(arList, LocationDirectory.filelist);
	return GetAttributesNum(arList);
}

aref GetFiles(string dirName, string fileMask)
{
	DeleteAttribute(&LocationDirectory, "");

	LocationDirectory.dir = dirName+"\\";
	if(dirName=="") { LocationDirectory.dir = "Program\\"; }
	LocationDirectory.mask = fileMask;
	CreateEntity(&LocationDirectory,"FINDFILESINTODIRECTORY");
	DeleteClass(&LocationDirectory);
	aref arList;
	makearef(arList, LocationDirectory.filelist);
	return arList;
}
// <-- KK
// MAXIMUS -->
string strlefttosymbol(string fName, string eSymbol, int bCorrection)
{
	int q = findSubStr(&fName, eSymbol, 0);
	q = sti(q-bCorrection);
	return strleft(fName, q);
}

string strrightfromsymbol(string fName, string sName, int bCorrection)
{
	return strcut(fName,strlen(sName)+bCorrection,strlen(fName)-1);
}

string GetMyFullOldName(ref chr)
{
	string name = "";
	if(!CheckAttribute(chr,"old.name")) chr.old.name = name;
	if(!CheckAttribute(chr,"old.lastname")) chr.old.lastname = name;
	if(CheckAttribute(chr,"name") && chr.old.name=="") chr.old.name = chr.name;
	if(CheckAttribute(chr,"lastname") && chr.old.lastname=="") chr.old.lastname = chr.lastname;
	if(CheckAttribute(chr,"old.title")) { name = chr.old.title + " "; }
	if(CheckAttribute(chr,"old.firstname"))
	{
		if(CheckAttribute(chr,"old.middlename")) name += chr.old.middlename;
		else name += chr.old.firstname;
	}
	else
	{
		name += chr.old.name;
		if(CheckAttribute(chr,"old.middlename"))
		{
			if(name!="") name += " " + chr.old.middlename;
			else name += chr.old.middlename;
		}
	}
	if(chr.old.lastname!="") name += " " + chr.old.lastname;
	return name;
}

string GetMySimpleOldName(ref chr)
{
	string name = "";
	if(!CheckAttribute(chr,"old.name")) chr.old.name = name;
	if(!CheckAttribute(chr,"old.lastname")) chr.old.lastname = name;
	if(CheckAttribute(chr,"name") && chr.old.name=="") chr.old.name = chr.name;
	if(CheckAttribute(chr,"lastname") && chr.old.lastname=="") chr.old.lastname = chr.lastname;
	if(CheckAttribute(chr,"old.firstname"))
	{
		if(CheckAttribute(chr,"old.middlename")) name += chr.old.middlename;
		else name += chr.old.firstname;
	}
	else
	{
		name += chr.old.name;
		if(CheckAttribute(chr,"old.middlename"))
		{
			if(name!="") name += " " + chr.old.middlename;
			else name += chr.old.middlename;
		}
	}
	if(chr.old.lastname!="") name += " " + chr.old.lastname;
	return name;
}

string StoreString(string strName, string strAdd)
{
	string retstring = strName;

	if(retstring=="") retstring += strAdd;
	else retstring += ","+strAdd;

	return retstring;
}

string RemoveString(string instr, string cutstr)
{
	if(instr==cutstr) return "";
	string bret = instr;
	int fndNum = findSubStr(instr,cutstr,0);
	int symbol;
	if(instr!=cutstr) symbol = sti(strlen(cutstr)+1);
	else symbol = 0;
	string part1 = "";
	string part2 = "";
	if(fndNum>0)
	{
		part1 = strcut(instr,0,fndNum-1);
		if(strcut(part1,strlen(part1)-1,strlen(part1)-1)==",") part1 = strcut(instr,0,fndNum-2);
		if(sti(strlen(instr)-strlen(cutstr))!=fndNum) part2 = strcut(instr,fndNum+strlen(cutstr),strlen(instr)-1);
	}
	else
	{
		part2 = strcut(instr,symbol,strlen(instr)-1);
		if(strcut(part2,0,0)==",") part2 = strcut(part2,1,strlen(part2)-1);
	}
	bret = part1 + part2;
	return bret;
}

string GetSpecialString(string strName, int numStr)
{
	string retstr = "";
	int symCount = 0;
	int symStr = 0;
	int num = 0;
	for(int i=0; i<strlen(strName); i++)
	{
		if(GetSymbol(strName,i)!=",") { symStr++; }
		else
		{
			num++;
			retstr = strcut(strName,symCount-symStr,i-1);
			if(num==numStr) return retstr;
			symStr = 0;
		}
		symCount++;
		if(i==sti(strlen(strName)-1))
		{
			if(num<numStr)
			{
				retstr = strcut(strName,symCount-symStr,strlen(strName)-1);
			}
		}
	}
	return retstr;
}

int GetWordsNumWithComma(string strName)
{
	int symStr = 0;
	for(int i=0; i<strlen(strName); i++)
	{
		if(GetSymbol(strName,i)!=",") { symStr++; }
	}
	return sti(symStr+1);
}

string FirstLetter(string strData)
{
	return ToUpper(strleft(strData,1))+strcut(strData,1,strlen(strData)-1);
}

string FirstLetterUp(string strData)
{
	return ToUpperEng(strleft(strData,1))+strcut(strData,1,strlen(strData)-1);
}

string GetLingvo(string strData)
{
	if(LanguageGetLanguage()=="Russian")
	{
		if(strcut(strData, strlen(strData)-1, strlen(strData)-1)=="à")
		{
			strData = strcut(strData, 0, strlen(strData)-2)+"ó";
		}
		if(strcut(strData, strlen(strData)-1, strlen(strData)-1)=="À")
		{
			strData = strcut(strData, 0, strlen(strData)-2)+"Ó";
		}
	}

	return strData;
}
// MAXIMUS <--

extern int InitAdditionalLocators();//adding not prescribed locators -->
extern void AddNewLocators();
string systemStatus = "down";

void WriteAdditionalLocators(int locIdx)
{
	string loadFilePath = FindFile("PROGRAM\Locations", "*_locators.c", "locations_locators.c");
	if(loadFilePath=="") return;
	//loadFilePath = strcut(loadFilePath, 8, strlen(loadFilePath) - 1); // KK
	loadFilePath = "Locations\locations_locators.c"; // KK
	if(LoadSegment(loadFilePath))
	{
		ref mchr = GetMainCharacter();
		mchr.locIndex = locIdx;
		if(InitAdditionalLocators()!=-1)
		{
			if(CheckAttribute(mchr,"newGameStart") && sti(mchr.newGameStart)==1)
			{
				AddNewLocators();
				DeleteAttribute(mchr, "newGameStart");
			}
		}
		UnloadSegment(loadFilePath);
		DeleteAttribute(mchr, "locIndex");
	}
}

object wholeWorld;

void WriteLocatorGlobal(string locationID, string locatorGroup, string locatorName, int charIndex, float posX, float posY, float posZ, bool bTempLocator)
{
	if (FindLocation(locationID) < 0) return; // KK

	wholeWorld.(locationID).locators.(locatorGroup).(locatorName).tmpLocator = bTempLocator;
	wholeWorld.(locationID).locators.(locatorGroup).(locatorName).x = posX;
	wholeWorld.(locationID).locators.(locatorGroup).(locatorName).y = posY;
	wholeWorld.(locationID).locators.(locatorGroup).(locatorName).z = posZ;

	wholeWorld.(locationID).locators.(locatorGroup).(locatorName).vx.x = 0.0;
	wholeWorld.(locationID).locators.(locatorGroup).(locatorName).vx.y = 0.0;
	wholeWorld.(locationID).locators.(locatorGroup).(locatorName).vx.z = 0.0;

	wholeWorld.(locationID).locators.(locatorGroup).(locatorName).vy.x = 0.0;
	wholeWorld.(locationID).locators.(locatorGroup).(locatorName).vy.y = 0.0;
	wholeWorld.(locationID).locators.(locatorGroup).(locatorName).vy.z = 0.0;

	wholeWorld.(locationID).locators.(locatorGroup).(locatorName).vz.x = 0.0;
	wholeWorld.(locationID).locators.(locatorGroup).(locatorName).vz.y = 0.0;
	wholeWorld.(locationID).locators.(locatorGroup).(locatorName).vz.z = 0.0;

	wholeWorld.(locationID).locators_radius.(locatorGroup).(locatorName) = 2.0;
	wholeWorld.(locationID).locators.(locatorGroup).(locatorName).radius = 1.5;

	locations[FindLocation(locationID)].locators.(locatorGroup).(locatorName).corpseIdx = charIndex;
	if(sti(charIndex)<=0) { locations[FindLocation(locationID)].locators.(locatorGroup).(locatorName).corpseIdx = -1; }
	locations[FindLocation(locationID)].locators.(locatorGroup).(locatorName).tmpLocator = bTempLocator;
	locations[FindLocation(locationID)].locators.(locatorGroup).(locatorName).x = posX;
	locations[FindLocation(locationID)].locators.(locatorGroup).(locatorName).y = posY;
	locations[FindLocation(locationID)].locators.(locatorGroup).(locatorName).z = posZ;

	locations[FindLocation(locationID)].locators.(locatorGroup).(locatorName).vx.x = 0.0;
	locations[FindLocation(locationID)].locators.(locatorGroup).(locatorName).vx.y = 0.0;
	locations[FindLocation(locationID)].locators.(locatorGroup).(locatorName).vx.z = 0.0;

	locations[FindLocation(locationID)].locators.(locatorGroup).(locatorName).vy.x = 0.0;
	locations[FindLocation(locationID)].locators.(locatorGroup).(locatorName).vy.y = 0.0;
	locations[FindLocation(locationID)].locators.(locatorGroup).(locatorName).vy.z = 0.0;

	locations[FindLocation(locationID)].locators.(locatorGroup).(locatorName).vz.x = 0.0;
	locations[FindLocation(locationID)].locators.(locatorGroup).(locatorName).vz.y = 0.0;
	locations[FindLocation(locationID)].locators.(locatorGroup).(locatorName).vz.z = 0.0;

	locations[FindLocation(locationID)].locators_radius.(locatorGroup).(locatorName) = 2.0;
	locations[FindLocation(locationID)].locators.(locatorGroup).(locatorName).radius = 1.5;
}

void DeleteLocatorGlobal(string locationID, string locatorGroup, string locatorName)
{
	aref rootLocs;

	makearef(rootLocs, locations[FindLocation(characters[GetMainCharacterIndex()].location)].locators);
	if(CheckAttribute(rootLocs, locatorGroup+"."+locatorName)) { DeleteAttribute(rootLocs, locatorGroup+"."+locatorName); }

	makearef(rootLocs, wholeWorld.(locationID).locators);
	if(CheckAttribute(rootLocs, locatorGroup+"."+locatorName)) { DeleteAttribute(rootLocs, locatorGroup+"."+locatorName); }
}

bool CheckAdditionalLocator(string locationID, string locatorGroup, string locatorName)
{
	string curLocName = "";
	string curLocGroup = "";
	ref lcn = &Locations[FindLocation(locationID)];
	aref rootLocators, curGrp, curLoc;
	int i, j;

	makearef(rootLocators,lcn.locators);
	for(i=0; i<GetAttributesNum(rootLocators); i++)
	{
		curGrp = GetAttributeN(rootLocators,i);
		curLocGroup = GetAttributeName(curGrp);
		if(curLocGroup==locatorGroup)
		{
			for(j=0; j<GetAttributesNum(curGrp); j++)
			{
				curLoc = GetAttributeN(curGrp,j);
				curLocName = GetAttributeName(curLoc);
				if(CheckAttribute(lcn, "locators."+curLocGroup+"."+curLocName+".tmpLocator"))
				{
					if(curLocName==locatorName) return true;
				}
			}
		}
	}
	return false;
}

void ClearTempParticles(string locationID, string locatorGroup, string locatorName)
{
	string partId = locationID+".locators."+locatorGroup+"."+locatorName+".pID";
	if(CheckAttribute(wholeWorld, partId))
	{
		aref rootIDs; makearef(rootIDs, wholeWorld.partId);
		for(int i=0; i<GetAttributesNum(rootIDs); i++)
		{
			string idNum = i+1;
			partId = partId+"."+idNum;
			if(CheckAttribute(wholeWorld, partId) && sti(wholeWorld.partId)!=-1)
			{
				string tmpID = locatorGroup+"."+locatorName+".pID"+idNum;
				int prtID = sti(wholeWorld.(partId));
				DeleteParticleSystem(prtID);
				DeleteAttribute(wholeWorld, partId);
			}
		}
	}
}

bool CheckCharPosition(float posX, float posY, float posZ)
{
	float x, y, z;
	bool bX, bY, bZ;
	GetCharacterPos(GetMainCharacter(), &x, &y, &z);

	float curXplus = makefloat(posX+makeint(1)));
	float curYplus = makefloat(posY+makeint(1));
	float curZplus = makefloat(posZ+makeint(1));
	float curXminus = makefloat(posX-makeint(1));
	float curYminus = makefloat(posY-makeint(1));
	float curZminus = makefloat(posZ-makeint(1));

	if(x>=curXminus && x<=curXplus) { bX = true; }
	else { bX = false; }
	if(y>=curYminus && y<=curYplus) { bY = true; }
	else { bY = false; }
	if(z>=curZminus && z<=curZplus) { bZ = true; }
	else { bZ = false; }
	if(bX && bY && bZ) return true;
	return false;
}

void EnterToReloadLocator(ref chr)
{
	string locator = "";
	int result;
	aref locFake;

	if(CheckAttribute(chr,"fakereload.locator"))
	{
		makearef(locFake, locations[FindLoadedLocation()]);
		locator = chr.fakereload.locator;
	}
	if(locator=="") { ExitFromReloadLocator(chr); return; }

	chrWaitReloadIsNoLink = false;
	chrWaitReloadLocator = locator;
	chrWaitLocationRef = locFake;
	makearef(chrWaitReloadRef, locFake.reload);
	result = chrCheckReloadLink(locFake, locator);
	string reloadType = "Reload";

	if(CheckAttribute(chr,"reloadStatus"))
	{
		reloadType = chr.reloadStatus;/*
		if(HasSubStr(chr.reloadStatus,"sea") && !HasSubStr(chr.reloadStatus,"seadog")) { reloadType = "ToSea"; }
		if(HasSubStr(chr.reloadStatus,"brothel")) { reloadType = "ToBrothel"; }
		if(HasSubStr(chr.reloadStatus,"tavern")) { reloadType = "ToTavern"; }
		if(HasSubStr(chr.reloadStatus,"residence") || HasSubStr(chr.reloadStatus,"townhall")) { reloadType = "ToResidence"; }
		if(HasSubStr(chr.reloadStatus,"shipyard")) { reloadType = "ToShipyard"; }
		if(HasSubStr(chr.reloadStatus,"store")) { reloadType = "ToStore"; }
		if(HasSubStr(chr.reloadStatus,"usurer")) { reloadType = "ToUsurer"; }
		if(HasSubStr(chr.reloadStatus,"church")) { reloadType = "ToChurch"; }
		if(HasSubStr(chr.reloadStatus,"academy")) { reloadType = "ToAcademy"; }
		if(HasSubStr(chr.reloadStatus,"arsenal")) { reloadType = "ToArsenal"; }
		if(HasSubStr(chr.reloadStatus,"tailor")) { reloadType = "ToTailor"; }
		if(HasSubStr(chr.reloadStatus,"blacksmith")) { reloadType = "ToBlacksmith"; }
		if(HasSubStr(chr.reloadStatus,"prison")) { reloadType = "ToPrison"; }
		if(HasSubStr(chr.reloadStatus,"fort")) { reloadType = "ToFort"; }
		if(HasSubStr(chr.reloadStatus,"port")) { reloadType = "ToPort"; }
		if(HasSubStr(chr.reloadStatus,"shore")) { reloadType = "ToShore"; }//MAXIMUS
		if(HasSubStr(chr.reloadStatus,"town")) { reloadType = "ToTown"; }
		if(HasSubStr(chr.reloadStatus,"jungle")) { reloadType = "ToJungle"; }
		if(HasSubStr(chr.reloadStatus,"boat")) { reloadType = "ToBoat"; }
		if(HasSubStr(chr.reloadStatus,"shipdeck")) { reloadType = "ToShipDeck"; }
		if(HasSubStr(chr.reloadStatus,"cabin")) { reloadType = "ToCabin"; }
		if(HasSubStr(chr.reloadStatus,"cannonsdeck")) { reloadType = "ToCannonsDeck"; }
		if(HasSubStr(chr.reloadStatus,"cargohold")) { reloadType = "ToCargoHold"; }
		if(HasSubStr(chr.reloadStatus,"seadogs")) { reloadType = "ToSeadogs"; }
		if(HasSubStr(chr.reloadStatus,"reload")) { reloadType = "Reload"; }*/
	}
	chr.reloadStatus = reloadType;

	if(result != 1)
	{
		chrWaitReloadIsNoLink = true;
		if(result == 0)
		{
			Log_SetActiveAction("Closed");
			return;
		}
	}

	if(chrCheckAutoReload(locFake, locator) == true)
	{
		if(chrIsNowEnableReload() != true)
		{
			lockedReloadLocator = "";
			Log_SetActiveAction("Closed");
			return;
		}
		Reload(chrWaitReloadRef, chrWaitReloadLocator, chr.location);
		chrWaitReloadLocator = "";
		chrWaitReloadIsNoLink = false;
	}
	else { lockedReloadLocator = ""; CheckReloadAction(chr, reloadType); }
}

void ExitFromReloadLocator(ref chr)
{
	if(CheckAttribute(chr,"fakereload.locator")) DeleteAttribute(chr,"fakereload.locator");
	DeleteAttribute(chr,"reloadStatus");
	Log_SetActiveAction("Nothing");
	chrWaitReloadLocator = "";
	chrWaitReloadIsNoLink = false;
	lockedReloadLocator = "";
}

string FindFreeRandomLocatorForCharacter(ref chr, ref loc, string group)
{
	string freeLocators = "";
	string usedLocators = "";
	string at = "locators." + group;
	if(!CheckAttribute(loc,at) || loc.at=="") return "";
	aref grp; makearef(grp, loc.(at));
	if(GetAttributesNum(grp)<=0) return "";

	int num = GetAttributesNum(grp);
	for(int n=1; n<TOTAL_CHARACTERS; n++)
	{
		if(n==GetCharacterIndex(chr)) continue;
		ref rCharacter = GetCharacter(n);
		if(CheckAttribute(rCharacter,"location") && rCharacter.location==chr.location)
		{
			if(CheckAttribute(rCharacter,"group") && rCharacter.location.group==group)
			{
				if(CheckAttribute(rCharacter,"location.locator") && rCharacter.location.locator!="") usedLocators = StoreString(usedLocators, rCharacter.location.locator);
			}
		}
	}
	for(int i=0; i<num; i++)
	{
		aref locRef = GetAttributeN(grp, i);
		string locName = GetAttributeName(locRef);
		if(!HasSubStr(usedLocators,locName)) freeLocators = StoreString(freeLocators, locName);
	}
	return GetRandSubString(freeLocators);
}

string LocatorExitSence(string locationID, string locType, string toLocation)
{
	string attrib = locType;
	switch(locType)
	{
		case "from": attrib = "name"; break;
		case "to": attrib = "emerge"; break;
		return "reload1";
	}
	aref cLoctr; makearef(cLoctr,locations[FindLocation(locationID)].reload);
	for(int i=0; i<GetAttributesNum(cLoctr); i++)
	{
		aref curItem1 = GetAttributeN(cLoctr,i);
		string attrName1 = GetAttributeName(curItem1);
		if(CheckAttribute(cLoctr,attrName1+".go") && HasSubStr(cLoctr.(attrName1).go,toLocation))
		{
			bool check = true;
			if(toLocation=="town" && HasSubStr(cLoctr.(attrName1).go,"townhall")) check = false;
			if(CheckAttribute(cLoctr,attrName1+"."+attrib) && check) return cLoctr.(attrName1).(attrib);
		}
	}
	return "reload1";
}//adding not prescribed locators <--

ref MalteseKnight()
{
	//int tmpNameFileID = LanguageOpenFile("characters_names.txt");
	ref mainChar = GetMainCharacter();
	ref tmpChar = LAi_CreateFantomCharacterEx(false, 3, true, false, 0.0, "skelt", "man", "", "");
	tmpChar.HeadModel = "h_skel4";

	if(CheckAttribute(mainChar,"disableDlg")) { mainChar.old.disableDlg = sti(mainChar.disableDlg); mainChar.disableDlg = 0; }

	tmpChar.name = TranslateString("","The late");
	tmpChar.lastname = TranslateString("","monk");
	tmpChar.Dialog.Filename = "Maltese_corpse_dialog.c";
	tmpChar.Dialog.Currentnode = "First time";

	string curBox = mainChar.boxname;
	float x,y,z;
	x = locations[FindLocation(mainChar.location)].locators.box.(curBox).x;
	y = locations[FindLocation(mainChar.location)].locators.box.(curBox).y;
	z = locations[FindLocation(mainChar.location)].locators.box.(curBox).z;
	TeleportCharacterToPos(tmpChar, x,y,z);
	LAi_SetStayType(tmpChar);

	//LanguageCloseFile(tmpNameFileID);
	return tmpChar;
}

void WriteAttributes(ref chr)
{
	if(IsMainCharacter(chr)) return;
	if(CheckAttribute(chr,"storedAttributes") && sti(chr.storedAttributes)==true) return;

	int bCorpseMode = CORPSEMODE;
	if(CheckAttribute(chr,"CORPSEMODE") && sti(chr.CORPSEMODE)==4) bCorpseMode = 4;

	float x,y,z,ay;
	GetCharacterPos(chr, &x, &y, &z);
	GetCharacterAY(chr, &ay);
	chr.deathx = x
	chr.deathy = y
	chr.deathz = z
	chr.deathay = ay;
	chr.corpse = true;
	if(!CheckAttribute(chr, "old.name")) { chr.old.name = chr.name; }
	if(!CheckAttribute(chr, "old.lastname")) { chr.old.lastname = chr.lastname; }
	if(CheckAttribute(chr, "firstname") && !CheckAttribute(chr, "old.firstname")) { chr.old.firstname = chr.firstname; }
	if(CheckAttribute(chr, "middlename") && !CheckAttribute(chr, "old.middlename")) { chr.old.middlename = chr.middlename; }
	if(CheckAttribute(chr, "title") && !CheckAttribute(chr, "old.title")) { chr.old.title = chr.title; }

	if(bCorpseMode!=4)
	{
//		if(CheckAttribute(chr,"corpse")) DeleteAttribute(chr,"corpse");
		return;
	}

	for(int c = 0; c < 10; c++)
	{
		string curSkillName = GetSkillName(c);
		if(CheckAttribute(chr, "skill."+curSkillName+".mod")) { chr.old.skill.(curSkillName).mod = chr.skill.(curSkillName).mod; }
	}

	if(CheckAttribute(chr, "dialog.filename")) { chr.old.dialog.filename = chr.dialog.filename; }
	if(CheckAttribute(chr, "dialog.currentnode")) { chr.old.dialog.currentnode = chr.dialog.currentnode; }
	if(CheckAttribute(chr, "dialog.tempnode")) { chr.old.dialog.tempnode = chr.dialog.tempnode; }
	if(CheckAttribute(chr, "chr_ai.type")) { chr.old.chr_ai.type = chr.chr_ai.type; }
	if(CheckAttribute(chr, "chr_ai.group")) { chr.old.chr_ai.group = chr.chr_ai.group; }
	if(CheckAttribute(chr, "chr_ai.type.dialog")) { chr.old.chr_ai.type.dialog = chr.chr_ai.type.dialog; }
	if(CheckAttribute(chr, "chr_ai.dmgbldmin")) { chr.old.chr_ai.dmgbldmin = chr.chr_ai.dmgbldmin; }
	if(CheckAttribute(chr, "chr_ai.dmgbldmax")) { chr.old.chr_ai.dmgbldmax = chr.chr_ai.dmgbldmax; }
	if(CheckAttribute(chr, "chr_ai.piercing")) { chr.old.chr_ai.piercing = chr.chr_ai.piercing; }
	if(CheckAttribute(chr, "chr_ai.block")) { chr.old.chr_ai.block = chr.chr_ai.block; }
	if(CheckAttribute(chr, "chr_ai.charge_max")) { chr.old.chr_ai.charge_max = chr.chr_ai.charge_max; }
	if(CheckAttribute(chr, "chr_ai.charge_dlt")) { chr.old.chr_ai.charge_dlt = chr.chr_ai.charge_dlt; }
	if(CheckAttribute(chr, "chr_ai.dmggunmin")) { chr.old.chr_ai.dmggunmin = chr.chr_ai.dmggunmin; }
	if(CheckAttribute(chr, "chr_ai.dmggunmax")) { chr.old.chr_ai.dmggunmax = chr.chr_ai.dmggunmax; }
	if(CheckAttribute(chr, "chr_ai.accuracy")) { chr.old.chr_ai.accuracy = chr.chr_ai.accuracy; }
	if(CheckAttribute(chr, "items"))//MAXIMUS: I'm not sure that it's needed
	{
		aref ifrom; makearef(ifrom, chr.items);
		DeleteAttribute(chr,"old.items");
		chr.old.items = "";
		aref ito; makearef(ito, chr.old.items);
		CopyAttributes(&ito, &ifrom);
	}

	chr.storedAttributes = true;
}

void RestoreCharacter(ref chCorpse)
{
	if(!CheckAttribute(chCorpse,"corpse")) return;
	else DeleteAttribute(chCorpse,"corpse");
	if(CharacterIsDead(chCorpse)) { LAi_CharacterLogoff(chCorpse); return; }

	int tmpNameFileID = LanguageOpenFile("characters_names.txt");
	bool bNoName;

	if(CheckAttribute(chCorpse,"old.name"))
	{
		if(chCorpse.old.name!="")
		{
			if(LanguageConvertString(tmpNameFileID,chCorpse.old.name)!="") { chCorpse.name = LanguageConvertString(tmpNameFileID,chCorpse.old.name); bNoName = false; }
			else { chCorpse.name = chCorpse.old.name; bNoName = false; }
		}
		else { chCorpse.name = chCorpse.old.name; bNoName = false; }
	}
	else { bNoName = true; }

	if(CheckAttribute(chCorpse,"old.lastname"))
	{
		if(chCorpse.old.lastname!="")
		{
			if(LanguageConvertString(tmpNameFileID,chCorpse.old.lastname)!="") { chCorpse.lastname = LanguageConvertString(tmpNameFileID,chCorpse.old.lastname); bNoName = false; }
			else { chCorpse.lastname = chCorpse.old.lastname; }
		}
		else { chCorpse.lastname = chCorpse.old.lastname; bNoName = false; }
	}
	else { bNoName = true; }

	if(CheckAttribute(chCorpse,"old.firstname"))
	{
		if(chCorpse.old.firstname!="")
		{
			if(LanguageConvertString(tmpNameFileID,chCorpse.old.firstname)!="") { chCorpse.firstname = LanguageConvertString(tmpNameFileID,chCorpse.old.firstname); }
			else { chCorpse.firstname = chCorpse.old.firstname; }
		}
		else { chCorpse.firstname = chCorpse.old.firstname; }
	}

	if(CheckAttribute(chCorpse,"old.middlename"))
	{
		if(chCorpse.old.middlename!="")
		{
			//if(LanguageConvertString(tmpNameFileID,chCorpse.old.middlename)!="") { chCorpse.middlename = LanguageConvertString(tmpNameFileID,chCorpse.old.middlename); }
			//else { chCorpse.middlename = chCorpse.old.middlename; }
			chCorpse.middlename = TranslateString("", chCorpse.old.middlename); // KK
		}
		else { chCorpse.middlename = chCorpse.old.middlename; }
	}
	LanguageCloseFile(tmpNameFileID);

	if(CheckAttribute(chCorpse,"old.title"))
	{
		if(chCorpse.old.title!="")
		{
			if(TranslateString("",chCorpse.old.title)!="") { chCorpse.title = TranslateString("",chCorpse.old.title); }
			else { chCorpse.title = chCorpse.old.title; }
		}
		else { chCorpse.title = chCorpse.old.title; }
	}

	if(bNoName) { SetRandomNameToCharacter(chCorpse); }
	if(CheckAttribute(chCorpse,"deathx")) { DeleteAttribute(chCorpse,"deathx"); }
	if(CheckAttribute(chCorpse,"deathy")) { DeleteAttribute(chCorpse,"deathy"); }
	if(CheckAttribute(chCorpse,"deathz")) { DeleteAttribute(chCorpse,"deathz"); }
	if(CheckAttribute(chCorpse,"deathay")) { DeleteAttribute(chCorpse,"deathay"); }
	if(!CheckAttribute(chCorpse,"storedAttributes")) { LAi_CharacterLogoff(chCorpse); return; }
	if(bAllies(chCorpse)) { DeleteAttribute(chCorpse,"storedAttributes"); LAi_CharacterLogoff(chCorpse); return; }
	if(LAi_IsBoardingProcess()) { DeleteAttribute(chCorpse,"storedAttributes"); LAi_CharacterLogoff(chCorpse); return; }

	if(CheckAttribute(chCorpse,"old.dialog.filename")) { chCorpse.dialog.filename = chCorpse.old.dialog.filename; }
	if(CheckAttribute(chCorpse,"old.dialog.currentnode")) { chCorpse.dialog.currentnode = chCorpse.old.dialog.currentnode; }
	if(CheckAttribute(chCorpse,"old.dialog.tempnode")) { chCorpse.dialog.tempnode = chCorpse.old.dialog.tempnode; }
	if(CheckAttribute(chCorpse,"old.chr_ai.type.dialog")) { chCorpse.chr_ai.type.dialog = chCorpse.old.chr_ai.type.dialog; }
	if(CheckAttribute(chCorpse,"old.chr_ai.dmgbldmin")) { chCorpse.chr_ai.dmgbldmin = chCorpse.old.chr_ai.dmgbldmin; }
	if(CheckAttribute(chCorpse,"old.chr_ai.dmgbldmax")) { chCorpse.chr_ai.dmgbldmax = chCorpse.old.chr_ai.dmgbldmax; }
	if(CheckAttribute(chCorpse,"old.chr_ai.piercing")) { chCorpse.chr_ai.piercing = chCorpse.old.chr_ai.piercing; }
	if(CheckAttribute(chCorpse,"old.chr_ai.block")) { chCorpse.chr_ai.block = chCorpse.old.chr_ai.block; }
	if(CheckAttribute(chCorpse,"old.chr_ai.charge_max")) { chCorpse.chr_ai.charge_max = chCorpse.old.chr_ai.charge_max; }
	if(CheckAttribute(chCorpse,"old.chr_ai.charge_dlt")) { chCorpse.chr_ai.charge_dlt = chCorpse.old.chr_ai.charge_dlt; }
	if(CheckAttribute(chCorpse,"old.chr_ai.dmggunmin")) { chCorpse.chr_ai.dmggunmin = chCorpse.old.chr_ai.dmggunmin; }
	if(CheckAttribute(chCorpse,"old.chr_ai.dmggunmax")) { chCorpse.chr_ai.dmggunmax = chCorpse.old.chr_ai.dmggunmax; }
	if(CheckAttribute(chCorpse,"old.chr_ai.accuracy")) { chCorpse.chr_ai.accuracy = chCorpse.old.chr_ai.accuracy; }
	if(CheckAttribute(chCorpse,"old.items"))//MAXIMUS: I'm not sure that it's needed
	{
		aref ifrom; makearef(ifrom, chCorpse.old.items);
		DeleteAttribute(chCorpse,"items");
		chCorpse.items = "";
		aref ito; makearef(ito, chCorpse.items);
		CopyAttributes(&ito, &ifrom);
	}
// KK -->
	if (CheckAttribute(chCorpse, "old.chr_ai.group")) {
		if (chCorpse.old.chr_ai.group != LAI_GROUP_CORPSES) {
			chCorpse.chr_ai.group = chCorpse.old.chr_ai.group;
		} else {
			DeleteAttribute(chCorpse, "old.chr_ai.group");
			LAi_group_MoveCharacter(chCorpse, LAI_DEFAULT_GROUP);
		}
	}
	if (CheckAttribute(chCorpse, "old.chr_ai.type")) { LAi_group_MoveCharacter(chCorpse, chCorpse.old.chr_ai.type); }
	if (CheckAttribute(chCorpse, "old.chr_ai.hp")) { chCorpse.chr_ai.hp = chCorpse.old.chr_ai.hp; }
	if (CheckAttribute(chCorpse, "old.chr_ai.hp_max")) { chCorpse.chr_ai.hp_max = chCorpse.old.chr_ai.hp_max; }
	if (CheckAttribute(chCorpse, "prisoned")) { DeleteAttribute(chCorpse, "prisoned"); }
	if (CheckAttribute(chCorpse, "actions")) { DeleteAttribute(chCorpse, "actions"); }
	/*if (CheckAttribute(chCorpse, "deathx")) { DeleteAttribute(chCorpse, "deathx"); }
	if (CheckAttribute(chCorpse, "deathy")) { DeleteAttribute(chCorpse, "deathy"); }
	if (CheckAttribute(chCorpse, "deathz")) { DeleteAttribute(chCorpse, "deathz"); }
	if (CheckAttribute(chCorpse, "deathay")) { DeleteAttribute(chCorpse, "deathay"); }*/
	if (CheckAttribute(chCorpse, "killer")) { DeleteAttribute(chCorpse, "killer"); }
	if (CheckAttribute(chCorpse, "status")) { DeleteAttribute(chCorpse, "status"); }
	if (CheckAttribute(chCorpse, "position")) { DeleteAttribute(chCorpse, "position"); }
	if (CheckAttribute(chCorpse, "fight")) { DeleteAttribute(chCorpse, "fight"); }
	if (CheckAttribute(chCorpse, "surrendered")) { DeleteAttribute(chCorpse, "surrendered"); }
// <-- KK
	if (CheckAttribute(chCorpse, "corpse")) { DeleteAttribute(chCorpse, "corpse"); }

	for(int c = 0; c < 10; c++)
	{
		string curSkillName = GetSkillName(c);
		if(CheckAttribute(chCorpse,"old.skill."+curSkillName+".mod")) { chCorpse.skill.(curSkillName).mod = chCorpse.old.skill.(curSkillName).mod; }
		else { if(CheckAttribute(chCorpse,"skill."+curSkillName+".mod")) { DeleteAttribute(chCorpse,"skill."+curSkillName+".mod"); } }
	}

	DeleteAttribute(chCorpse,"storedAttributes");
	LAi_CharacterLogoff(chCorpse);
}

void DropCharaterItem(ref refCharacter, int itmIdx)
{
	float x, y, z;
	GetCharacterPos(refCharacter, &x, &y, &z);
	int locNum = 1;
	ref curLoc = &Locations[FindLocation(refCharacter.location)];
	aref rootLocs;
	string newLocName;
	if(CheckAttribute(curLoc,"locators.items"))
	{
		makearef(rootLocs, curLoc.locators.items);
		locNum = GetAttributesNum(rootLocs)+1;
	}
	newLocName = "item"+locNum;
	WriteLocatorGlobal(refCharacter.location, "items", newLocName, itmIdx, x+stf(makeint(Rand(5)+4)/10), y, z+stf(makeint(Rand(5)+4)/10), true);

	Items[itmIdx].startLocator = newLocName;
	Items[itmIdx].shown = "1";
	Items[itmIdx].startLocation = refCharacter.location;

	Item_OnLoadLocation(refCharacter.location);
	ReloadProgressUpdate();

//	AddDroppedItem(refCharacter.location, itmIdx);
}

void AddDroppedItem(string locationID, int itmIdx)
{
	if(!CheckAttribute(Items[itmIdx], "startLocator")) return;
	if(!CheckAttribute(Items[itmIdx], "startLocation")) return;
	if(!CheckAttribute(Items[itmIdx], "shown")) return;

	aref curItem; makearef(curItem, Items[itmIdx]);
	if(curItem.shown == "1")
	{
		if(curItem.startLocation == locationID)
		{
			string itemFolder = "items";
			aref curModel; makearef(curModel, ItemModels[itmIdx]);

			CreateEntity(&curModel, "MODELR");
			ReloadProgressUpdate();
			if(CheckAttribute(curItem, "folder")) { itemFolder = curItem.folder; }
			SendMessage(&curModel, "ls", MSG_MODEL_SET_DIRPATH, itemFolder+"\\");
			SendMessage(&curModel, "ls", MSG_MODEL_LOAD_GEO, itemFolder + "\\" + curItem.model);
			SendMessage(&curModel, "ls", MSG_MODEL_SET_DIRPATH,"");

			if(HasSubStr(curItem.model, "blade") || HasSubStr(curItem.model, "pistol")) SendMessage(&curModel, "ls", MSG_MODEL_SET_TECHNIQUE, "BladeItem");
			else SendMessage(&curModel, "ls", MSG_MODEL_SET_TECHNIQUE, "RandItem");
			
			LayerAddObject("execute", &curModel, ITEMS_LAYER);
			LayerAddObject("realize", &curModel, ITEMS_LAYER);
			
			string curLocName = curItem.startLocator;
			SendMessage(SeaLighter, "ssi", "AddModel", curItem.model, &curModel);
			SendMessage(&curModel, "lffffffffffff", MSG_MODEL_SET_POSITION, stf(locations[FindLocation(locationID)].locators.items.(curLocName).x), stf(locations[FindLocation(locationID)].locators.items.(curLocName).y), stf(locations[FindLocation(locationID)].locators.items.(curLocName).z), 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);

			Trace("LandInterface: Loaded model "+itemFolder+"\\"+curItem.model);
			ReloadProgressUpdate();
		}
	}
}
/*=====================================================|END OF LOCATION-MOD|=====================================================*/

/*=====================================================|START OF INTERFACES|=====================================================*/
void GetInterfaceParameters()
{
	ReinitInterface();
}

ref deadChr;
void ReinitInterface()
{
	Interfaces[INTERFACE_CANNONS].SectionName = "interface\cannons.c";
	Interfaces[INTERFACE_CANNONS].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\cannons.ini";
	Interfaces[INTERFACE_STORE].SectionName = "interface\store.c";
	Interfaces[INTERFACE_STORE].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\store.ini";
	Interfaces[INTERFACE_SHIP_CHOOSE].SectionName = "interface\ship.c";
	Interfaces[INTERFACE_SHIP_CHOOSE].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\ship.ini";
	Interfaces[INTERFACE_SHIPYARD].SectionName = "interface\shipyard.c";
	Interfaces[INTERFACE_SHIPYARD].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\shipyard.ini";
	Interfaces[INTERFACE_CHARACTER].SectionName = "interface\character.c";
	Interfaces[INTERFACE_CHARACTER].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\character.ini";
	Interfaces[INTERFACE_MAINMENU].SectionName = "interface\mainmenu.c";
	Interfaces[INTERFACE_MAINMENU].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\mainmenu.ini";
	Interfaces[INTERFACE_SHIPHOLD].SectionName = "interface\shiphold.c";
	Interfaces[INTERFACE_SHIPHOLD].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\shiphold.ini";
	Interfaces[INTERFACE_HIRECREW].SectionName = "interface\hirecrew.c";
	Interfaces[INTERFACE_HIRECREW].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\hirecrew.ini";
	Interfaces[INTERFACE_PASSENGERS].SectionName = "interface\passengers.c";
	Interfaces[INTERFACE_PASSENGERS].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\passengers.ini";
	Interfaces[INTERFACE_CHARACTER_SELECT].SectionName = "interface\selectCharacter.c";
	Interfaces[INTERFACE_CHARACTER_SELECT].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\selectCharacter.ini";
	Interfaces[INTERFACE_QUESTBOOK].SectionName = "interface\questbook.c";
	Interfaces[INTERFACE_QUESTBOOK].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\questbook.ini";
	Interfaces[INTERFACE_TRADEBOOK].SectionName = "interface\tradebook.c";
	Interfaces[INTERFACE_TRADEBOOK].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\tradebook.ini";
	Interfaces[INTERFACE_NATIONRELATION].SectionName = "interface\NationRelation.c";
	Interfaces[INTERFACE_NATIONRELATION].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\NationRelation.ini";
	Interfaces[INTERFACE_SAVELOAD].SectionName = "interface\save_load.c";
	Interfaces[INTERFACE_SAVELOAD].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\save_load.ini";
	Interfaces[INTERFACE_ITEMS].SectionName = "interface\items.c";
	Interfaces[INTERFACE_ITEMS].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\items.ini";
	Interfaces[INTERFACE_FORTCAPTURE].SectionName = "interface\fortcapture.c";
	Interfaces[INTERFACE_FORTCAPTURE].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\fortcapture.ini";
	Interfaces[INTERFACE_ITEMSBOX].SectionName = "interface\itemsbox.c";
	Interfaces[INTERFACE_ITEMSBOX].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\itemsbox.ini";
	Interfaces[INTERFACE_HELPSCREEN].SectionName = "interface\helpscreen.c";
	Interfaces[INTERFACE_HELPSCREEN].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\helpscreen.ini";
	Interfaces[INTERFACE_OPTIONSCREEN].SectionName = "interface\option_screen.c";
	Interfaces[INTERFACE_OPTIONSCREEN].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\option_screen.ini";
	Interfaces[INTERFACE_SELECTMENU].SectionName = "interface\select_menu.c";
	Interfaces[INTERFACE_SELECTMENU].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\select_menu.ini";
	Interfaces[INTERFACE_ITEMSTRADE].SectionName = "interface\itemstrade.c";
	Interfaces[INTERFACE_ITEMSTRADE].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\itemstrade.ini";
	Interfaces[INTERFACE_CONTROLS].SectionName = "interface\controls.c";
	Interfaces[INTERFACE_CONTROLS].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\controls.ini";
	Interfaces[INTERFACE_PERKS].SectionName = "interface\perks.c";
	Interfaces[INTERFACE_PERKS].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\perks.ini";
	Interfaces[INTERFACE_SALARY].SectionName = "interface\salary.c";
	Interfaces[INTERFACE_SALARY].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\salary.ini";
	Interfaces[INTERFACE_PLAYGAME].SectionName = "interface\playgame.c";
	Interfaces[INTERFACE_PLAYGAME].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\playgame.ini";
	Interfaces[INTERFACE_ENDGAME].SectionName = "interface\endgame.c";
	Interfaces[INTERFACE_ENDGAME].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\endgame.ini";
	Interfaces[INTERFACE_RANSACK_JOIN].SectionName = "interface\ransack_join.c";
	Interfaces[INTERFACE_RANSACK_JOIN].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\ransack_join.ini";
	Interfaces[INTERFACE_RANSACK_CREW].SectionName = "interface\ransack_crew.c";
	Interfaces[INTERFACE_RANSACK_CREW].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\ransack_crew.ini";
	Interfaces[INTERFACE_RANSACK_CAPTAIN].SectionName = "interface\ransack_captain.c";
	Interfaces[INTERFACE_RANSACK_CAPTAIN].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\ransack_captain.ini";
	Interfaces[INTERFACE_RANSACK_MAIN].SectionName = "interface\ransack_main.c";
	Interfaces[INTERFACE_RANSACK_MAIN].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\transfer_main.ini";
	Interfaces[INTERFACE_TRANSFER_MAIN].SectionName = "interface\transfer_main.c";
	Interfaces[INTERFACE_TRANSFER_MAIN].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\transfer_main.ini";
	Interfaces[INTERFACE_TRANSFER_GOODS].SectionName = "interface\transfer_goods.c";
	Interfaces[INTERFACE_TRANSFER_GOODS].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\transfer_goods.ini";
	Interfaces[INTERFACE_TRANSFER_CHARACTER].SectionName = "interface\transfer_characters.c";
	Interfaces[INTERFACE_TRANSFER_CHARACTER].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\transfer_characters.ini";
	Interfaces[INTERFACE_TRANSFER_CREW].SectionName = "interface\transfer_crew.c";
	Interfaces[INTERFACE_TRANSFER_CREW].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\transfer_crew.ini";
// boal -->
	Interfaces[INTERFACE_BOAL_MAP].SectionName = "interface\boal_map.c";
	Interfaces[INTERFACE_BOAL_MAP].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\boal_map.ini";
// boal <--
// GreatZen Interface Mod -->
	Interfaces[INTERFACE_ADV].SectionName = "interface\adv.c";
	Interfaces[INTERFACE_ADV].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\adv.ini";
	Interfaces[INTERFACE_MONEYT].SectionName = "interface\money.c";
	Interfaces[INTERFACE_MONEYT].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\money.ini";
// GreatZen Interface Mod <--
// MAXIMUS interface MOD -->
	Interfaces[INTERFACE_MAP].SectionName = "interface\map.c";
	Interfaces[INTERFACE_MAP].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\map.ini";
	Interfaces[INTERFACE_OFFICER].SectionName = "interface\officer.c";
	Interfaces[INTERFACE_OFFICER].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\officer.ini";
	Interfaces[INTERFACE_TRANSFER_CANNONS].SectionName = "interface\transfer_cannons.c";
	Interfaces[INTERFACE_TRANSFER_CANNONS].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\transfer_cannons.ini";
	Interfaces[INTERFACE_CUSTOMIZATION].SectionName = "interface\customization.c";
	Interfaces[INTERFACE_CUSTOMIZATION].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\customization.ini";
	Interfaces[INTERFACE_ABOUT_BUILD].SectionName = "interface\about_build.c";
	Interfaces[INTERFACE_ABOUT_BUILD].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\about_build.ini";
	Interfaces[INTERFACE_GAMBLE].SectionName = "interface\gamble.c";
	Interfaces[INTERFACE_GAMBLE].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\gamble.ini";
	Interfaces[INTERFACE_MUTINY].SectionName = "interface\mutiny_map.c";
	Interfaces[INTERFACE_MUTINY].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\mutiny_map.ini";
	Interfaces[INTERFACE_PROFILES].SectionName = "interface\profiles.c";
	Interfaces[INTERFACE_PROFILES].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\profiles.ini";
	Interfaces[INTERFACE_A_MAP].SectionName = "interface\a_map.c";
	Interfaces[INTERFACE_A_MAP].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\a_map.ini";
// MAXIMUS interface MOD <--
//added by KAM -->
	Interfaces[INTERFACE_KAM_SELECTMODEL].SectionName = "interface\kam_selectmodel.c";
	Interfaces[INTERFACE_KAM_SELECTMODEL].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\kam_selectmodel.ini";
	Interfaces[INTERFACE_KAM_SELECTSAILS].SectionName = "interface\kam_selectsails.c";
	Interfaces[INTERFACE_KAM_SELECTSAILS].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\kam_selectsails.ini";
	Interfaces[INTERFACE_KAM_RATIONS].SectionName = "interface\kam_rations.c";
	Interfaces[INTERFACE_KAM_RATIONS].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\kam_rations.ini";
	Interfaces[INTERFACE_KAM_ARTICLES].SectionName = "interface\kam_articles.c";
	Interfaces[INTERFACE_KAM_ARTICLES].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\kam_articles.ini";
	Interfaces[INTERFACE_KAM_SHIPTRANSFER].SectionName = "interface\kam_shiptransfer.c";
	Interfaces[INTERFACE_KAM_SHIPTRANSFER].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\kam_shiptransfer.ini";
	Interfaces[INTERFACE_KAM_SHIPBERTHING].SectionName = "interface\kam_shipberthing.c";
	Interfaces[INTERFACE_KAM_SHIPBERTHING].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\kam_shipberthing.ini";
//added by KAM <--
// Inez -->
	Interfaces[INTERFACE_BUILDSETTINGS].SectionName = "interface\buildsettings.c";
	Interfaces[INTERFACE_BUILDSETTINGS].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\buildsettings.ini";
// Inez <--
// KK -->
	Interfaces[INTERFACE_CAPTURE_COLONY].SectionName = "interface\capture_colony.c";
	Interfaces[INTERFACE_CAPTURE_COLONY].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\capture_colony.ini";
	Interfaces[INTERFACE_SELECT_STORYLINE].SectionName = "interface\select_storyline.c";
	Interfaces[INTERFACE_SELECT_STORYLINE].IniFile = "RESOURCE\INI\"+GetCurrentInterfacePath()+"\select_storyline.ini";
// <-- KK
}

string GetCurrentInterfacePath()
{
	string IntCur = "";
	if(bNewInterface==true) { IntCur = "NEW_INTERFACES"; }
	else { IntCur = "INTERFACES"; }
	return IntCur;
}

void EnableQuickControls()
{
	bKeyboardEnabled = true;
	CI_CreateAndSetControls( "", "NK_KB_Shift_on", CI_GetKeyCode("VK_SHIFT"), 0, false);
	CI_CreateAndSetControls( "", "NK_KB_Shift_off", CI_GetKeyCode("VK_SHIFT"), INVERSE_CONTROL, false);
	CI_CreateAndSetControls( "", "NK_KB_Alt_on", CI_GetKeyCode("VK_ALT"), 0, false);
	CI_CreateAndSetControls( "", "NK_KB_Alt_off", CI_GetKeyCode("VK_ALT"), INVERSE_CONTROL, false);
	CI_CreateAndSetControls( "", "NK_KB_Control_on", CI_GetKeyCode("VK_CONTROL"), 0, false);
	CI_CreateAndSetControls( "", "NK_KB_Control_off", CI_GetKeyCode("VK_CONTROL"), INVERSE_CONTROL, false);
}

bool GetQuickControl(string cName)
{
	string controlName = "";
	if(bKeyboardControl && !bKeyboardAlt && !bKeyboardShift) controlName = "control";
	if(bKeyboardAlt && !bKeyboardShift && !bKeyboardControl) controlName = "alt";
	if(bKeyboardShift && !bKeyboardControl && !bKeyboardAlt) controlName = "shift";

	if(controlName==cName) return true;
	return false;
}
/*======================================================|END OF INTERFACES|======================================================*/

/*======================================================|START OF LANGUAGE|======================================================*/
void GetLanguageParameters()
{
	if(bInterfaceRus==true)
	{
		LanguageSetLanguage("Russian");

		if(LoadSegment("Characters\Russian\Characters_names_ru.c"))
		{
		  InitCharactersNamesRu();
		  UnloadSegment("Characters\Russian\Characters_names_ru.c");
		}
	} 
	else
	{// MAXIMUS: characters_names.c for these additional languages will be different, or we can use one English-names file ==>
		if(bInterfaceFra==true) LanguageSetLanguage("French");
		else
		{
			if(bInterfaceGer==true) LanguageSetLanguage("German");
			else
			{
				if(bInterfaceSpa==true) LanguageSetLanguage("Spanish");
				else
				{
					if(bInterfacePol==true) LanguageSetLanguage("Polish");// <== // KK
					else LanguageSetLanguage("English");
				}
			}
		}

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

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

	GetLanguageParameters(); if(LogsToggle) Log_SetStringToLog(TranslateString("","Characters names on") + " " + XI_ConvertString("be_"+LanguageGetLanguage()) + " " + TranslateString("","language..."));
	SetLocalizedLabels(); if(LogsToggle) Log_SetStringToLog(TranslateString("","Islands and locations names on") + " " + XI_ConvertString("be_"+LanguageGetLanguage()) + " " + TranslateString("","language..."));
	BI_InitializeCommands(); if(LogsToggle) Log_SetStringToLog(TranslateString("","Battle-interface commands on") + " " + XI_ConvertString("be_"+LanguageGetLanguage()) + " " + TranslateString("","language..."));
	BLI_SetObjectData(); if(LogsToggle) Log_SetStringToLog(TranslateString("","Land-interface commands on") + " " + XI_ConvertString("be_"+LanguageGetLanguage()) + " " + TranslateString("","language..."));

	//LanguageCloseFile(tmpLangFileID);
	UpdateCharactersNames();
}

void ResetKeyboardCharacters(string curLanguage)
{
	if(curLanguage!="Russian") curLanguage = "English";// temporary. If anyone'll want to make changes - welcome ;)
	switch(curLanguage)
	{
		case "Russian":
			CI_CreateAndSetControls("", "NK_Key_a", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_b", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_c", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_d", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_e", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_f", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_g", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_h", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_i", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_j", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_k", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_l", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_m", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_n", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_o", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_p", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_q", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_r", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_s", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_t", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_u", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_v", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_w", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_x", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_y", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_z", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_[", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_]", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_'", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_`", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_,", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_.", "", 0, false);
		break;

		case "English":
			CI_CreateAndSetControls("", "NK_Key_à", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_á", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_â", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ã", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ä", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_å", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_¸", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_æ", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ç", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_è", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_é", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ê", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ë", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ì", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_í", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_î", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ï", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ð", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ñ", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ò", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ó", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ô", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_õ", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ö", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_÷", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ø", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ù", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_û", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ú", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ý", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ü", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_þ", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_ÿ", "", 0, false);
			CI_CreateAndSetControls("", "NK_Key_.", "", 0, false);
		break;
	}
}

// KK -->
bool FindLocalLanguage(string lang)
{
	string dir = "RESOURCE\INI\TEXTS\" + lang;
	if (FindFile(dir, "*.ini", "common.ini") == "") return false;
	if (CheckDirectory(dir, "*.txt") < 15) return false;
	if (FindFile(dir + "\QUESTBOOK", "*.txt", "quests_texts.txt") == "") return false;
	return true;
}
// <-- KK

void UpdateCharactersNames()
{
	int tmpNameFileID = LanguageOpenFile("characters_names.txt");
	for(int j=0; j<TOTAL_CHARACTERS; j++)
	{
		ref ch = GetCharacter(j);
		if(CheckAttribute(ch,"greeting"))
		{
			string curGree = ch.greeting;
			ch.greeting = curGree;
		}
		bool bRandName;
		bool bPass = false;
		string isFstName, isMdlName, isLstName, isNikName;
		isFstName = "";
		isMdlName = "";
		isLstName = "";
		isNikName = "";
/*
		string isFullName = "Without name";
		if(CheckAttribute(ch,"name")) isFullName = ch.name;
		if(CheckAttribute(ch,"middlename")) isFullName += " " + ch.middlename;
		if(CheckAttribute(ch,"lastname")) isFullName += " " + ch.lastname;
		if(CheckAttribute(ch,"index")) isFullName += "[" + ch.index + "]";
		else isFullName += "[ ]";
		trace(isFullName);
*/
		if(CheckAttribute(ch,"chr_ai.type"))
		{
			if(ch.chr_ai.type==LAI_TYPE_BUILDING) bPass = true;
		}

		if(CheckAttribute(ch,"name"))
		{
			if(ch.name=="") continue;
			if(!CheckAttribute(ch,"old.name"))
			{
				isFstName = ch.name;
				ch.old.name = isFstName;
			}
			else isFstName = ch.old.name;
			if(LanguageConvertString(tmpNameFileID,isFstName)=="")
			{
				if(bPass)
				{
					if(LanguageGetLanguage()!="Russian") ch.name = strcut(XI_ConvertString(isFstName),1,strlen(XI_ConvertString(isFstName))-1);
					else ch.name = XI_ConvertString(isFstName);
				}
				else
				{
					ch.name.assigned = true;
					SetRandomNameToCh(ch);
				}
			}
			else
			{
				if(bPass)
				{
					if(LanguageGetLanguage()!="Russian") ch.name = strcut(XI_ConvertString(isFstName),1,strlen(XI_ConvertString(isFstName))-1);
					else ch.name = XI_ConvertString(isFstName);
				}
				else ch.name = LanguageConvertString(tmpNameFileID,isFstName);
			}
//			trace(" * NAME - " + ch.name);
			DeleteAttribute(ch,"name.assigned");
		}

		if(CheckAttribute(ch,"middlename"))
		{
			if(ch.middlename=="") continue;
			if(!CheckAttribute(ch,"old.middlename"))
			{
				isMdlName = ch.middlename;
				ch.old.middlename = isMdlName;
			}
			else isMdlName = ch.old.middlename;

			ch.middlename = TranslateString("", isMdlName); // KK
//			trace(" * MIDDLE NAME - " + ch.middlename);
		}

		if(CheckAttribute(ch,"lastname"))
		{
			if(ch.lastname=="") continue;
			if(bPass) continue;
			if(!CheckAttribute(ch,"old.lastname"))
			{
				isLstName = ch.lastname;
				ch.old.lastname = isLstName;
			}
			else isLstName = ch.old.lastname;
			if(CheckAttribute(ch,"old.name"))
			{
				if(ch.old.name=="Regulating") isLstName = "R" + isLstName;
			}
			if(LanguageConvertString(tmpNameFileID,isLstName)=="")
			{
				ch.lastname.assigned = true;
				SetRandomNameToCh(ch);
			}
			else
			{
				ch.lastname = LanguageConvertString(tmpNameFileID,isLstName);				
			}
//			trace(" * LAST NAME - " + ch.lastname);
			DeleteAttribute(ch,"lastname.assigned");
		}

		if(CheckAttribute(ch,"nickname"))
		{
			if(ch.nickname=="") continue;
			if(!CheckAttribute(ch,"old.lastname"))
			{
				isNikName = ch.nickname;
				ch.old.nickname = isNikName;
			}
			else isNikName = ch.old.nickname;
			ch.nickname = LanguageConvertString(tmpNameFileID,isNikName);
//			trace(" * NIKNAME - " + ch.nickname);
		}

		if(CheckAttribute(ch,"nation"))
		{
			if(sti(ch.nation)<MAX_NATIONS)
			{
				for(int cNat=0; cNat<MAX_NATIONS; cNat++)
				{
					string sNation = cNat;
					int curRank = GetRank(ch, cNat);
					if(curRank < sti(Nations[cNat].Ranks.Quantity))
					{
						if(curRank==0) continue;
						if(CheckAttribute(ch,"nations."+sNation+".Rank"))
						{
							ch.nations.(sNation).Rank = curRank;
							ch.firstname = ch.name;
							UpdateTitle(&ch);
//							trace(" * NATION - " + XI_ConvertString(GetNationNameByType(cNat)));
//							trace(" * RANKNAME - " + "ch.nations."+sNation+".Rank = "+XI_ConvertString(GetRankName(ch, cNat)));
						}
					}
				}
			}
		}
	}
	LanguageCloseFile(tmpNameFileID);
}

void SetRandomNameToCh(ref rCharacter)
{
	if(systemStatus=="down") return;
	int curCharNation;
	string rfName = "";
	string rlName = "";
	ref rfNames = &Nullcharacter;
	ref rlNames = &Nullcharacter;

	if(!CheckAttribute(rCharacter,"sex")) return;
	if(!CheckAttribute(rCharacter,"nation")) iNation = PIRATE;// MAXIMUS
	int iNation = sti(rCharacter.nation);
	if(iNation == -1) iNation = PIRATE;
	if(iNation == PIRATE) { string allNations = "0,1,2,4,5"; iNation = sti(GetRandSubString(allNations)); }// MAXIMUS

	string rSex = rCharacter.sex;
	switch(iNation)
	{
		case 0:
			if (rSex == "man") { rfNames = &sEnManNames; } else { rfNames = &sEnWomenNames; }
			rlNames = &sEnFamilies;
		break;
		case 1:
			if (rSex == "man") { rfNames = &sFrManNames; } else { rfNames = &sFrWomenNames; }
			rlNames = &sFrFamilies;
		break;
		case 2:
			if (rSex == "man") { rfNames = &sSpManNames; } else { rfNames = &sSpWomenNames; }
			rlNames = &sSpFamilies;
		break;
		case 4:
			if (rSex == "man") { rfNames = &sHoManNames; } else { rfNames = &sHoWomenNames; }
			rlNames = &sHoFamilies;
		break;
		case 5:
			if (rSex == "man") { rfNames = &sPoManNames; } else { rfNames = &sPoWomenNames; }
			rlNames = &sPoFamilies;
		break;
	}

	if (GetArraySize(&rfNames) >= 2)
	{
		rCharacter.nation.name = iNation;//MAXIMUS: used in GetCharacterAddressForm
//		if(CheckAttribute(rCharacter,"name.assigned")) trace("GHANGING NAME...");
//		if(CheckAttribute(rCharacter,"lastname.assigned")) trace("GHANGING LASTNAME...");
		rfName = GetRandSubString(rfNames[rand(GetArraySize(&rfNames) - 2)]);
		rlName = GetRandSubString(rlNames[rand(GetArraySize(&rlNames) - 2)]);
	}
	if(CheckAttribute(rCharacter,"name.assigned")) rCharacter.name = rfName;
	if(CheckAttribute(rCharacter,"lastname.assigned")) rCharacter.lastname = rlName;
//MAXIMUS -[addition, offered by KK]->
	if(!CheckAttribute(rCharacter,"old.name") || rCharacter.old.name=="") rCharacter.old.name = rCharacter.name;
	if(!CheckAttribute(rCharacter,"old.lastname") || rCharacter.old.lastname=="") rCharacter.old.lastname = rCharacter.lastname;
//MAXIMUS <-[addition, offered by KK]-
}

void SetLocalizedLabels()
{
	//int tmpLangFileID = LanguageOpenFile("interface_strings.txt");
	int i, n, j;
	string isIsland = "";
	string isLocLab = "";
	string isCityNm = "";
// KK -->
	aref arIslandReload, arIslandLoc;
	int num;
	string townname;
	ref fortchar = &NullCharacter;
	for(n=0; n<ISLANDS_QUANTITY; n++)
	{
		if(CheckAttribute(Islands[n],"worldmap"))
		{
			isIsland = Islands[n].worldmap;
			worldMap.islands.(isIsland).label.text = XI_ConvertString(FindIslandName(isIsland)); // KK LanguageConvertString(tmpLangFileID,isIsland);
//			trace("ISLAND - "+worldMap.islands.(isIsland).label.text); // MAXIMUS: trace for testing [Pieter, leave it as is]
			arIslandReload; makearef(arIslandReload, WorldMap.islands.(isIsland).locations);
			num = GetAttributesNum(arIslandReload);
			for(i=0; i < num; i++)
			{
				arIslandLoc = GetAttributeN(arIslandReload, i);
				if (CheckAttribute(arIslandLoc, "label.text")) {
					if (!CheckAttribute(arIslandLoc, "label.old.text")) {
						isCityNm = arIslandLoc.label.text;
						arIslandLoc.label.old.text = isCityNm;
					} else {
						isCityNm = arIslandLoc.label.old.text;
					}
					arIslandLoc.label.text = GetTownName(isCityNm); // KK LanguageConvertString(tmpLangFileID, isCityNm);
//					trace(" * BAY - "+arIslandLoc.label.text); // MAXIMUS: trace for testing [Pieter, leave it as is]
				}
			}

			makearef(arIslandReload, Islands[n].reload);
			num = GetAttributesNum(arIslandReload);
			for(j = 0; j < num; j++) {
				arIslandLoc = GetAttributeN(arIslandReload, j);
				if (CheckAttribute(arIslandLoc, "label")) {
					if (!CheckAttribute(arIslandLoc, "old.label")) {
						isLocLab = arIslandLoc.label;
						arIslandLoc.old.label = isLocLab;
					} else {
						isLocLab = arIslandLoc.old.label;
					}
					townname = GetTownIDFromLocID(arIslandLoc.go);
					if (townname != "") {
						Preprocessor_Add("town_name", GetTownName(townname));
						arIslandLoc.label = PreprocessText(arIslandLoc.label);
						Preprocessor_Remove("town_name");
					} else {
						if (arIslandLoc.go == "BOARDING_Fort") {
							fortchar = characterFromID(arIslandLoc.commander);
							if (CheckAttribute(fortchar, "town")) {
								Preprocessor_Add("town_name", GetTownName(fortchar.town));
								arIslandLoc.label = PreprocessText(arIslandLoc.label);
								Preprocessor_Remove("town_name");
							} else {
								arIslandLoc.label = TranslateString("",isLocLab);
							}
						} else {
							arIslandLoc.label = TranslateString("",isLocLab);
						}
					}
//					trace(" * LOCATION - "+arIslandLoc.label); // MAXIMUS: trace for testing [Pieter, leave it as is]
				}
			}
		}
		else
		{
			if(CheckAttribute(Islands[n],"id"))
			{
				isIsland = Islands[n].id;
				worldMap.islands.(isIsland).label.text = XI_ConvertString(FindIslandName(isIsland)); //LanguageConvertString(tmpLangFileID,isIsland);
//				trace("ISLAND - "+worldMap.islands.(isIsland).label.text); // MAXIMUS: trace for testing [Pieter, leave it as is]
				arIslandReload; makearef(arIslandReload, WorldMap.islands.(isIsland).locations);
				num = GetAttributesNum(arIslandReload);
				for (i = 0; i < num; i++) {
					arIslandLoc = GetAttributeN(arIslandReload, i);
					if (CheckAttribute(arIslandLoc, "label.text")) {
						if (!CheckAttribute(arIslandLoc, "label.old.text")) {
							isCityNm = arIslandLoc.label.text;
							arIslandLoc.label.old.text = isCityNm;
						} else {
							isCityNm = arIslandLoc.label.old.text;
						}
						arIslandLoc.label.text = GetTownName(isCityNm);
//						trace(" * BAY - "+arIslandLoc.label.text); // MAXIMUS: trace for testing [Pieter, leave it as is]
					}
				}

				makearef(arIslandReload, Islands[n].reload);
				num = GetAttributesNum(arIslandReload);
				for (j = 0; j < num; j++) {
					arIslandLoc = GetAttributeN(arIslandReload, j);
					if (CheckAttribute(arIslandLoc, "label")) {
						if (!CheckAttribute(arIslandLoc, "old.label")) {
							isLocLab = arIslandLoc.label;
							arIslandLoc.old.label = isLocLab;
						} else {
							isLocLab = arIslandLoc.old.label;
						}
						townname = GetTownIDFromLocID(arIslandLoc.go);
						if (townname != "") {
							Preprocessor_Add("town_name", GetTownName(townname));
							arIslandLoc.label = PreprocessText(arIslandLoc.label);
							Preprocessor_Remove("town_name");
						} else {
							if (arIslandLoc.go == "BOARDING_Fort") {
								fortchar = characterFromID(arIslandLoc.commander);
								if (CheckAttribute(fortchar, "town")) {
									Preprocessor_Add("town_name", GetTownName(fortchar.town));
									arIslandLoc.label = PreprocessText(arIslandLoc.label);
									Preprocessor_Remove("town_name");
								} else {
									arIslandLoc.label = TranslateString("",isLocLab);
								}
							} else {
								arIslandLoc.label = TranslateString("",isLocLab);
							}
						}
//						trace(" * LOCATION - "+arIslandLoc.label); // MAXIMUS: trace for testing [Pieter, leave it as is]
					}
				}
			}
		}
	}
// <-- KK
	//LanguageCloseFile(tmpLangFileID);
}
/*=======================================================|END OF LANGUAGE|=======================================================*/

// KK: Maximus, could you please find another way of dealing with Remy Gatien? Instead of making two characters with the same id (in fact we
// have THREE Remy Gatiens; 3rd is "Belette" captain) try to make characters with identical name and lastname, but different chr.id, for example,
// VERY PLEASE! The way is coded now makes awfull mess...
void CheckSecondCharacter(ref NPChar)//MAXIMUS: we have two characters "Remy Gutien_gov". This section must correct dialog links and NPChar attributes
{
	aref NextDiag; makearef(NextDiag,NPChar.Dialog);
	for(int n=0; n<CHARACTERS_QUANTITY; n++)
	{
		if(CheckAttribute(characters[n],"id") && NPChar.id==characters[n].id)
		{
			if(CheckAttribute(NPChar,"location.stime") && CheckAttribute(characters[n],"location.stime") && NPChar.location.stime!=characters[n].location.stime)
			{
				aref NextDiag2; makearef(NextDiag2, characters[n].Dialog);
				CopyAttributes(&NextDiag2,&NextDiag);

				if(CheckAttribute(NPChar,"locDate")) { characters[n].locDate = sti(NPChar.locDate); }
				if(CheckAttribute(NPChar,"rank")) { characters[n].rank = sti(NPChar.rank); }
				if(CheckAttribute(NPChar,"reputation")) { characters[n].reputation = sti(NPChar.reputation); }
				if(CheckAttribute(NPChar,"money")) { characters[n].money = sti(NPChar.money); }
				if(CheckAttribute(NPChar,"wealth")) { characters[n].wealth = sti(NPChar.wealth); }
				if(CheckAttribute(NPChar,"freepoints")) { characters[n].perks.freepoints = sti(NPChar.freepoints); }

				aref arPerksRoot; makearef(arPerksRoot,ChrPerksList.list);
				int chrPerksQ = GetAttributesNum(arPerksRoot);
				for(int i=0; i<chrPerksQ; i++)
				{
					string perkName = GetAttributeName(GetAttributeN(arPerksRoot,i));
					if(CheckAttribute(NPChar,perkName))
					{
						characters[n].perks.list.(perkName) = sti(NPChar.perks.list.(perkName));
					}
				}

				for(int j=0; j<10; j++)
				{
					string skillName = GetSkillName(j);
					if(CheckAttribute(NPChar,"skill."+skillName))
					{
						characters[n].skill.(skillName) = sti(NPChar.skill.(skillName));
					}

					if(CheckAttribute(NPChar,"experience."+skillName))
					{
						characters[n].experience.(skillName) = sti(NPChar.experience.(skillName));
					}
				}
			}
		}
	}
}

void CalculateEncInfoData()
{
	ref mainCh = GetMainCharacter();
	mainCh.ShipEnc = "none";
	mainCh.CanEscape = 1;
	EncRecalcReloadToSea();

	float modifier = 1.0;
	if(checkAttribute(mainCh,"Perks.List.ShipSpeedUp")) { if(sti(mainCh.Perks.List.ShipSpeedUp)) modifier += 0.2; }
	if(checkAttribute(mainCh,"Perks.List.ShipTurnRateUp")) { if(sti(mainCh.Perks.List.ShipTurnRateUp)) modifier += 0.15; }
	if(checkAttribute(mainCh,"Perks.List.SailingProfessional")) { if(sti(mainCh.Perks.List.SailingProfessional)) modifier += 0.65; }
	ref MyShipType = GetShipByType(GetCharacterShipType(mainCh));
	aref arship; makearef(arship, mainCh.ship);
	float SpeedMod = stf(GetLocalShipAttrib(arship, MyShipType, "SpeedRate")) / 12 / stf(mainCh.EncSpeed);
	float sailmod = sqrt(GetSummonSkillFromName(mainCh, SKILL_SAILING)) * 16 * modifier * SpeedMod;
	if(sti(sqrt(GetSummonSkillFromName(mainCh, SKILL_SNEAK)))!=0)
	{
		if( rand(100) / (sqrt(GetSummonSkillFromName(mainCh, SKILL_SNEAK)) * 3.2) > sailmod ) { mainCh.CanEscape = 0; }
	}
}

void EncRecalcReloadToSea()
{
	//int tmpLangFileID = LanguageOpenFile("interface_strings.txt");
	worldMap.encounter.type = "";
	string totalInfo = "";
	float EncSpeed = 1.0;
	int numEncounters = wdmGetNumberShipEncounters();
	int isShipEncounterType = 0;
	ref rEncounter;
	ref mc = GetMainCharacter();

	for(int i = 0; i < numEncounters; i++)
	{
		if(wdmSetCurrentShipData(i))
		{
			if(MakeInt(worldMap.encounter.select) == 0) continue;			
			isShipEncounterType++;
			if (isShipEncounterType>1)
			{
				totalInfo = totalInfo + " " + XI_ConvertString("vs.") + " ";
			}
			rEncounter = &MapEncounters[sti(worldMap.encounter.type)];
	       		
			if(!CheckAttribute(rEncounter,"RealEncounterType")) totalInfo = totalInfo + TranslateString("","ships");
			else
			{
				switch(sti(rEncounter.RealEncounterType))
	       		{
					case 0:
				        totalInfo = totalInfo + TranslateString("","merchants");
				        EncSpeed = 0.65;
					break;
					case 1:
				        totalInfo = totalInfo + TranslateString("","merchants with a light escort");
				        EncSpeed = 0.7;
					break;
					case 2:
				        totalInfo = totalInfo + TranslateString("","a single merchant with heavy escort");
				        EncSpeed = 0.75;
					break;
					case 3:
				        totalInfo = totalInfo + TranslateString("","a small patrol");
				        EncSpeed = 0.95;
					break;
					case 4:
				        totalInfo = totalInfo + TranslateString("","warships");
				        EncSpeed = 0.75;
					break;
					case 5:
				        totalInfo = totalInfo + TranslateString("","warships");
				        EncSpeed = 0.95;
					break;
					case 6:
				        totalInfo = totalInfo + TranslateString("","small craft");
				        EncSpeed = 0.85;
					break;
					case 7:
				        totalInfo = totalInfo + TranslateString("","a rag-tag bunch");
				        EncSpeed = 0.75;
					break;
					case 8:
				        totalInfo = totalInfo + TranslateString("","a group of merchants");
				        EncSpeed = 0.6;
					break;
					case 9:
				        totalInfo = totalInfo + TranslateString("","an escorted group of merchants");
				        EncSpeed = 0.7;
					break;
					case 10:
				        totalInfo = totalInfo + TranslateString("","a convoy");
				        EncSpeed = 0.75;
					break;
					case 11:
				        totalInfo = totalInfo + TranslateString("","a large patrol");
				        EncSpeed = 0.9;
					break;
					case 12:
				        totalInfo = totalInfo + TranslateString("","a small fleet");
				        EncSpeed = 0.8;
					break;
					case 13:
				        totalInfo = totalInfo + TranslateString("","a battle fleet");
				        EncSpeed = 0.65;
					break;
					case 14:
				        totalInfo = totalInfo + TranslateString("","a rag-tag bunch");
				        EncSpeed = 0.85;
					break;
					case 15:
				        totalInfo = totalInfo + TranslateString("","a scratch patrol");
				        EncSpeed = 0.75;
					break;

					totalInfo = totalInfo + TranslateString("","ships");
	        	}
			}

			if(SAILHO_INFOLEVEL>=2)
			{
				if(sti(rEncounter.Nation) != PIRATE) totalInfo = totalInfo + " " + TranslateString("","flying the colors of") + " " + XI_ConvertString("3"+Nations[sti(rEncounter.Nation)].Name);
				else totalInfo = totalInfo + " " + TranslateString("","flying the Jolly Roger");
			}

			if(SAILHO_INFOLEVEL>=1)
			{
				if(isShipEncounterType>1) totalInfo = TranslateString("","Sail Ho! There's a battle up ahead sir, it looks like") + " " + totalInfo;
				else totalInfo = TranslateString("","Sail Ho! It looks like") + " " + totalInfo;
			}
			else
			{
				if(isShipEncounterType>1) totalInfo = TranslateString("","Sail Ho! And gunfire, there's a battle up ahead!");
				else totalInfo = TranslateString("","Sail Ho!");
			}

			if(mc.ShipEnc!="enemy")
			{
				if(GetNationRelation2MainCharacter(sti(rEncounter.Nation)) == RELATION_ENEMY) mc.ShipEnc = "enemy";
				else mc.ShipEnc = "ship";
			}
		}
	}
	else totalinfo += ".";
	mc.EncInfo = totalinfo;
	mc.EncSpeed = EncSpeed;
	mc.EncNation = GetNationRelation2MainCharacter(sti(rEncounter.Nation));
	
	//LanguageCloseFile(tmpLangFileID);
}

void FillPrison()
{
	if(FindLoadedLocation()<0) return;

	//int tmpNameFileID = LanguageOpenFile("characters_names.txt");
	string modelsList = GetPrisonersList();
	string ani, model;
	ref prisoner;
	for(int i=1; i<17; i++)
	{
		if(i==15) continue;

		if(modelsList != "") {
			model = GetRandSubString(modelsList);
			modelsList = RemoveString(modelsList, model);
		} else {
			model = LAi_GetBoardingModel(GetMainCharacter(), &ani);
		}

		//============================================| PRISONERS |============================================//
		if(i<14 && i!=12 && i!=13)
		{
			if(i==9)
			{
				prisoner = LAi_CreateFantomCharacterEx(true, 0, true, true, 0.25, model, ani, "goto", "goto24");
				LAi_SetPoorType(prisoner);
				DisarmCharacter(prisoner, false, true);
				LAi_group_MoveCharacter(prisoner, GetCurrentCitizenGroup());

				if(modelsList!="")
				{
					model = GetRandSubString(modelsList);
					modelsList = RemoveString(modelsList, model);
				}
				else { model = LAi_GetBoardingModel(GetMainCharacter(), &ani); }

				prisoner = LAi_CreateFantomCharacterEx(true, 0, true, true, 0.25, model, ani, "goto", "goto" + i);
				LAi_SetCitizenType(prisoner);
				DisarmCharacter(prisoner, false, true);
				LAi_group_MoveCharacter(prisoner, GetCurrentCitizenGroup());
			}
			else
			{
				prisoner = LAi_CreateFantomCharacterEx(true, 0, true, true, 0.25, model, ani, "goto", "goto" + i);
				LAi_SetPoorType(prisoner);
				DisarmCharacter(prisoner, false, true);
				LAi_group_MoveCharacter(prisoner, GetCurrentCitizenGroup());
			}
		}
		//=============================================| SOLDIERS |=============================================//
// KK -->
		if (Locations[FindLoadedLocation()].id == "Redmond_prison" || Locations[FindLoadedLocation()].id == "Greenford_prison") {
			if (i == 1 || i == 14 || i == 16) continue;
		}
// <-- KK
		if(i==1)
		{
			prisoner = LAi_CreateFantomCharacterEx(true, 0, true, true, 0.25, SelectSoldierModelByNation(GetCurrentLocationNation(), "officer"), ani, "sit", "sit" + i);
			LAi_SetHuberType(prisoner);
			prisoner.name = TranslateString("","Officer");
			prisoner.lastname = "";
			prisoner.Dialog.Filename = "Soldier_dialog.c";
			prisoner.Dialog.Currentnode = "First time";
			LAi_group_MoveCharacter(prisoner, GetSoldiersName(GetCurrentLocationNation())+"_SOLDIERS");
		}
		if(i>=12 && i<=13)
		{
			prisoner = LAi_CreateFantomCharacterEx(true, 0, true, true, 0.25, SelectSoldierModelByNation(GetCurrentLocationNation(), "soldier"), ani, "goto", "goto" + sti(17 + Rand(6)));
			LAi_SetPatrolType(prisoner);
			prisoner.name = TranslateString("","Soldier");
			prisoner.lastname = "";
			prisoner.Dialog.Filename = "Soldier_dialog.c";
			prisoner.Dialog.Currentnode = "First time";
			LAi_group_MoveCharacter(prisoner, GetSoldiersName(GetCurrentLocationNation())+"_SOLDIERS");
		}
		if(i>=14)
		{
			prisoner = LAi_CreateFantomCharacterEx(true, 0, true, true, 0.25, SelectSoldierModelByNation(GetCurrentLocationNation(), "soldier"), ani, "goto", "goto" + i);
			LAi_SetGuardianType(prisoner);
			prisoner.name = TranslateString("","Soldier");
			prisoner.lastname = "";
			prisoner.Dialog.Filename = "Soldier_dialog.c";
			prisoner.Dialog.Currentnode = "First time";
			LAi_group_MoveCharacter(prisoner, GetSoldiersName(GetCurrentLocationNation())+"_SOLDIERS");
		}
	}

	//LanguageCloseFile(tmpNameFileID);
}

extern string GetPrisonersModels();
extern string GetMansionModels();
extern string GetBrothelModels();

string GetPrisonersList()
{
	string modelsList = "";
	if(LoadSegment("models\initModels.c"))
	{
		modelsList = GetPrisonersModels();
		UnloadSegment("models\initModels.c");
	}
	return modelsList;
}

string GetLadiesList()
{
	string modelsList = "";
	if(LoadSegment("models\initModels.c"))
	{
		modelsList = GetMansionModels();
		UnloadSegment("models\initModels.c");
	}
	return modelsList;
}

string GetWhoresList()
{
	string modelsList = "";
	if(LoadSegment("models\initModels.c"))
	{
		modelsList = GetBrothelModels();
		UnloadSegment("models\initModels.c");
	}
	return modelsList;
}

void DisarmCharacter(ref tmpChr, bool bTake, bool bTakeAll)
{
	string blade, gun, cuirass, flask, pouch;
	if(IsCharacterEquipByGroup(tmpChr,BLADE_ITEM_TYPE))
	{
		blade = GetCharacterEquipByGroup(tmpChr,BLADE_ITEM_TYPE);
		RemoveCharacterEquip(tmpChr, BLADE_ITEM_TYPE);
		TakeItemFromCharacter(tmpChr, blade);
		if(bTake) GiveItem2Character(GetMainCharacter(), gun);
	}
	if(IsCharacterEquipByGroup(tmpChr,GUN_ITEM_TYPE))
	{
		gun = GetCharacterEquipByGroup(tmpChr,GUN_ITEM_TYPE);
		RemoveCharacterEquip(tmpChr, GUN_ITEM_TYPE);
		TakeItemFromCharacter(tmpChr, gun);
		if(bTake) GiveItem2Character(GetMainCharacter(), gun);
	}
	if(IsCharacterEquipByGroup(tmpChr,ARMOR_ITEM_TYPE))
	{
		cuirass = GetCharacterEquipByGroup(tmpChr,ARMOR_ITEM_TYPE);
		RemoveCharacterEquip(tmpChr, ARMOR_ITEM_TYPE);
		TakeItemFromCharacter(tmpChr, cuirass);
		if(bTake) GiveItem2Character(GetMainCharacter(), gun);
	}
	if(IsCharacterEquipByGroup(tmpChr,FLASK_ITEM_TYPE))
	{
		flask = GetCharacterEquipByGroup(tmpChr,FLASK_ITEM_TYPE);
		RemoveCharacterEquip(tmpChr, FLASK_ITEM_TYPE);
		TakeItemFromCharacter(tmpChr, flask);
		if(bTake) GiveItem2Character(GetMainCharacter(), flask);
	}
	if(IsCharacterEquipByGroup(tmpChr,POUCH_ITEM_TYPE))
	{
		pouch = GetCharacterEquipByGroup(tmpChr,POUCH_ITEM_TYPE);
		RemoveCharacterEquip(tmpChr, POUCH_ITEM_TYPE);
		TakeItemFromCharacter(tmpChr, pouch);
		if(bTake) GiveItem2Character(GetMainCharacter(), pouch);
	}
	if(bTakeAll)
	{
		aref chItems; makearef(chItems, tmpChr.items);
		DeleteAttribute(chItems,"");
	}
}
