/* TIH -->
	Jul27'06
		Many adjustments to the handling of how much a ship costs. This was a complete mess.
		All costs are figured for tradeHigh in one spot for each type of cost now:
			Sail repair
			Hull repair
			Buy price
			Sell price
		Cargo goods are better handled if replaced ship with one that has smaller hold.

		RPG_STYLE mod:
		To add more fun to the system in regards to people who actually play the game as an rpg game.
		High class ships will not be sold to low level characters. They will gradually increase ability to purchase higher ships.
		Stolen or pirated ships are sold for MUCH less than sticker price.
		Previously bought ships can be sold back for negligable loss in cost (20% hit by default).
		Bought ships are removed from the shipyard list to prevent buying more of same ship (each ship is fairly unique).
		Sold ships are put back into the shipyard for future purchases (or dismissed due to town changes).
TIH <-- */

#define ISHOW_MODE_VIEW			0
#define ISHOW_MODE_EMPTYVIEW	1
#define ISHOW_MODE_BUY			2
#define ISHOW_MODE_SELL			3
#define ISHOW_MODE_REPAIR		4
#define ISHOW_MODE_COMPANION	5
#define ISHOW_MODE_CHOOSE		6
#define ISHOW_MODE_SKILLS		7

int nShowMode = -1;

int	nCurSScrollNum = -1;
int	nCurFScrollNum = -1;
int	nCurFourNum = -1;
aref arCurShip; // PRS3

string OldNodeName = "";

aref arShipList;

int nAllPassngerQuantity;

int nspRepair;
int nhpRepair;

bool removable = false;

string sPreviouseNode = "";

int nChrIdxForInfo = -1;

// NK -->
int gprice[4];
gprice[0] = -1;
gprice[1] = -1;
gprice[2] = -1;
gprice[3] = -1;
string sTownName = "";
sTownName = GetCurrentTownID(); // NK 04-09-08 //GetTownIDFromGroup(Stores[GetCharacterCurrentStore(GetMainCharacter())].group);
int nStoreMoney = GetTownGold(sTownName);

ref shipwright;
int daystowait = 0;
// NK <--

void InitInterface_R(string iniName,ref shipmaster)
{
	shipwright = &shipmaster; // NK
// KK -->
	if (!LAi_IsCapturedLocation) {
	  GameInterface.title = "titleShipyard";
		nStoreMoney = GetTownGold(sTownName);
  } else {
  	GameInterface.title = "titleRansack";
  	nStoreMoney = 0;
	}
// <-- KK
	makearef(arShipList,shipmaster.shipyard);

	FillFScroll();
	FillSScroll();
	FillFourImages();

	SendMessage(&GameInterface,"ls",MSG_INTERFACE_INIT,iniName);
	CreateExitString();//MAXIMUS: standard exit-string for exit-button

// KK -->
	if (LAi_IsCapturedLocation) {
	  	SendMessage(&GameInterface, "lsls", MSG_INTERFACE_MSG_TO_NODE, "BUY_BUTTON", 0, XI_ConvertString("Take"));
	  	SendMessage(&GameInterface, "lsls", MSG_INTERFACE_MSG_TO_NODE, "SELLSHIP_BUTTON", 0, XI_ConvertString("Leave"));
	}
// <-- KK

	// NK -->
	gprice[0] = -1;
	gprice[1] = -1;
	gprice[2] = -1;
	gprice[3] = -1;
	sTownName = GetCurrentTownID(); // NK 04-09-08 //GetTownIDFromGroup(Stores[GetCharacterCurrentStore(GetMainCharacter())].group);
	//rStoreTown = GetTownFromID(sTownName); // NK, add aref 05-04-15, this particular one 05-04-19.
	//nStoreMoney = GetTownGold(sTownName);
	CreateString(true,"Money",MakeMoneyShow(sti(Characters[GetMainCharacterIndex()].money),MONEY_SIGN,MONEY_DELIVER),FONT_NORMAL,COLOR_MONEY,175,409,SCRIPT_ALIGN_LEFT,1.0);
	CreateString(true,"SMoney",MakeMoneyShow(nStoreMoney,MONEY_SIGN,MONEY_DELIVER),FONT_NORMAL,COLOR_MONEY,465,409,SCRIPT_ALIGN_RIGHT,1.0);
	//CreateString(true,"Store",Stores[GetCharacterCurrentStore(GetMainCharacter())].group + ":",FONT_NORMAL,COLOR_MONEY,320,436,SCRIPT_ALIGN_CENTER,1.0);
	// NK -->
	CreateString(true,"ShipName","",FONT_NORMAL,COLOR_NORMAL,320,201,SCRIPT_ALIGN_CENTER,1.0);

	// changed by KAM -->
	CreateString(true,"ShipClass","",FONT_NORMAL,COLOR_NORMAL,208,236,SCRIPT_ALIGN_LEFT,1.0);
	CreateString(true,"HullPoints","",FONT_NORMAL,COLOR_NORMAL,208,270,SCRIPT_ALIGN_LEFT,1.0);
	CreateString(true,"Speed","",FONT_NORMAL,COLOR_NORMAL,208,304,SCRIPT_ALIGN_LEFT,1.0);
	CreateString(true,"Maneuver","",FONT_NORMAL,COLOR_NORMAL,208,338,SCRIPT_ALIGN_LEFT,1.0);
	CreateString(true,"Capacity","",FONT_NORMAL,COLOR_NORMAL,208,372,SCRIPT_ALIGN_LEFT,1.0);
	CreateString(true,"MaxCrew","",FONT_NORMAL,COLOR_NORMAL,336,236,SCRIPT_ALIGN_LEFT,1.0);
	CreateString(true,"MinCrew","",FONT_NORMAL,COLOR_NORMAL,336,270,SCRIPT_ALIGN_LEFT,1.0);
	CreateString(true,"CannonsQuantity","",FONT_NORMAL,COLOR_NORMAL,336,304,SCRIPT_ALIGN_LEFT,1.0);
	CreateString(true,"MaxCaliber","",FONT_NORMAL,COLOR_NORMAL,336,338,SCRIPT_ALIGN_LEFT,1.0);
	CreateString(true,"ShipCost","",FONT_NORMAL,COLOR_NORMAL,336,372,SCRIPT_ALIGN_LEFT,1.0);
	// <-- changed by KAM

	// TIH --> rpg_style
	CreateString(false,"NoBuyString","",FONT_NORMAL,COLOR_NORMAL,320,176,SCRIPT_ALIGN_CENTER,0.5);
	SetNodeUsing("NOBUYBOX1",false);
	SetNodeUsing("NOBUYBOX2",false);
	// TIH <--

	CreateString(false,"RepairAllCost","",FONT_NORMAL,COLOR_NORMAL,366,238,SCRIPT_ALIGN_LEFT,1.0);
	CreateString(false,"HullPercent","",FONT_NORMAL,COLOR_NORMAL,320,282,SCRIPT_ALIGN_CENTER,1.0);
	CreateString(false,"RepairHullCost","",FONT_NORMAL,COLOR_NORMAL,426,282,SCRIPT_ALIGN_LEFT,1.0);
	CreateString(false,"SailsPercent","",FONT_NORMAL,COLOR_NORMAL,320,326,SCRIPT_ALIGN_CENTER,1.0);
	CreateString(false,"RepairSailsCost","",FONT_NORMAL,COLOR_NORMAL,426,326,SCRIPT_ALIGN_LEFT,1.0);

	CreateString(false,"TradePrice","",FONT_NORMAL,COLOR_NORMAL,320,255,SCRIPT_ALIGN_LEFT,1.0);

	CreateString(false,"CharacterName","",FONT_NORMAL,COLOR_NORMAL,320,200,SCRIPT_ALIGN_CENTER,1.0);
	CreateString(false,"skillLeadership","",FONT_BOLD_NUMBERS,COLOR_NORMAL,300,232,SCRIPT_ALIGN_RIGHT,1.0);
	CreateString(false,"skillFencing","",FONT_BOLD_NUMBERS,COLOR_NORMAL,300,266,SCRIPT_ALIGN_RIGHT,1.0);
	CreateString(false,"skillSailing","",FONT_BOLD_NUMBERS,COLOR_NORMAL,300,300,SCRIPT_ALIGN_RIGHT,1.0);
	CreateString(false,"skillAccuracy","",FONT_BOLD_NUMBERS,COLOR_NORMAL,300,334,SCRIPT_ALIGN_RIGHT,1.0);
	CreateString(false,"skillCannons","",FONT_BOLD_NUMBERS,COLOR_NORMAL,300,368,SCRIPT_ALIGN_RIGHT,1.0);
	CreateString(false,"skillGrappling","",FONT_BOLD_NUMBERS,COLOR_NORMAL,434,232,SCRIPT_ALIGN_RIGHT,1.0);
	CreateString(false,"skillRepair","",FONT_BOLD_NUMBERS,COLOR_NORMAL,434,266,SCRIPT_ALIGN_RIGHT,1.0);
	CreateString(false,"skillDefence","",FONT_BOLD_NUMBERS,COLOR_NORMAL,434,300,SCRIPT_ALIGN_RIGHT,1.0);
	CreateString(false,"skillCommerce","",FONT_BOLD_NUMBERS,COLOR_NORMAL,434,334,SCRIPT_ALIGN_RIGHT,1.0);
	CreateString(false,"skillSneak","",FONT_BOLD_NUMBERS,COLOR_NORMAL,434,368,SCRIPT_ALIGN_RIGHT,1.0);

	SetSelectable("EXIT_BUTTON",true);

	SetEventHandler("InterfaceBreak","ProcessCancelExit",0);
	SetEventHandler("frame","ProcessFrame",1);
	SetEventHandler("exitCancel","ProcessCancelExit",0);
	SetEventHandler("ievnt_command","ProcessCommandExecute",0);
}

void ProcessCancelExit()
{
	int tmpLangFileID = LanguageOpenFile("interface_strings.txt");
	// NK -->
	if(nStoreMoney < 0) nStoreMoney = 0;
	if(!LAi_IsCapturedLocation) SetTownGold(sTownName, nStoreMoney); // KK
	gprice[0] = -1;
	gprice[1] = -1;
	gprice[2] = -1;
	gprice[3] = -1;
	// NK <--
	DelEventHandler("InterfaceBreak","ProcessCancelExit");
	DelEventHandler("frame","ProcessFrame");
	DelEventHandler("exitCancel","ProcessCancelExit");
	DelEventHandler("ievnt_command","ProcessCommandExecute");

	DoShipParametersClamp();

	interfaceResultCommand = RC_INTERFACE_SHIPYARD_EXIT;
	if(daystowait > 0) // NK do day-waiting after everything 05-07-08
	{
		WaitDate("", 0, 0, daystowait, 0, 0);
		PlaySound("ambient\shipyard\axe.wav");	//just earcandy :)
		PlaySound("ambient\shipyard\vehicle.wav"); 
		Log_SetStringToLog(LanguageConvertString(tmpLangFileID,"Repairs are completed") + " " + daystowait + " " + XI_ConvertString("day") + stringret(daystowait > 1, XI_ConvertString("s"),"") + " " + LanguageConvertString(tmpLangFileID,"later."));
		LogIt(XI_ConvertString("Time") + ": " + GetStringTime(GetTime()));		// LDH 15Oct06 added time display
	}
	// NK <--
	LanguageCloseFile(tmpLangFileID);
	EndCancelInterface(true);
	if(tradeHigh==true) tradeHigh = false; // added by MAXIMUS [possibility to repair your ship by double price]
	if(CheckAttribute(GetMainCharacter(),"gained_repair_hull")) DeleteAttribute(GetMainCharacter(),"gained_repair_hull");
	if(CheckAttribute(GetMainCharacter(),"gained_repair_sail")) DeleteAttribute(GetMainCharacter(),"gained_repair_sail");
	if(CheckAttribute(GetMainCharacter(),"gained_repair_cannon")) DeleteAttribute(GetMainCharacter(),"gained_repair_cannon");
}

void ProcessFrame()
{
	if(OldNodeName!=GetCurrentNode())
	{
		OldNodeName = GetCurrentNode();
		switch(OldNodeName)
		{
		case "SHIPSLIST":	nCurFourNum=-1; break;
		case "SCROLLITEMS":	nCurSScrollNum=-1; break;
		case "PASSENGERS":	nCurFScrollNum=-1; break;
		}
	}
	if(nCurFScrollNum!=sti(GameInterface.passengers.current))
	{
		nCurFScrollNum = sti(GameInterface.passengers.current);
		UpdateFScrollData();
	}
	if(nCurSScrollNum!=sti(GameInterface.scrollitems.current))
	{
		nCurSScrollNum = sti(GameInterface.scrollitems.current);
		UpdateSScrollData();
	}
	if(nCurFourNum!=sti(GameInterface.FourImage.current))
	{
		nCurFourNum = sti(GameInterface.FourImage.current);
		UpdateFourData();
	}
}

void UpdateFourData()
{
	int cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
	SetCharacterToInfoCharacter(cn);
	removable = true;
	if(cn<0)
	{
		if(nAllPassngerQuantity>0)
		{
			SetShowMode(ISHOW_MODE_COMPANION);
			SetCaptainButtonsEnable();
		}
		else
		{
			SetShowMode(ISHOW_MODE_EMPTYVIEW);
		}
		GameInterface.strings.ShipName = "";
	}
	else
	{
		removable = GetRemovable(GetCharacter(cn));
		if(CheckAttribute(GetCharacter(cn),"ship.name"))
		{
			GameInterface.strings.ShipName = Characters[cn].ship.name;
		}
		else
		{
			GameInterface.strings.ShipName = "";
		}
		int st = GetCharacterShipType(GetCharacter(cn));
		if(st==SHIP_NOTUSED)
		{
			SetShowMode(ISHOW_MODE_EMPTYVIEW);
		}
		else
		{
			SetShowMode(ISHOW_MODE_VIEW);
			makearef(arCurShip, Characters[cn].ship); // PRS3
			SetViewShipData(st,GetSellPrice(nCurFourNum,"includecargo")); // TIH added handler Jul27'06 // PRS3
		}
	}
}

void UpdateFScrollData()
{
	if(nAllPassngerQuantity<=0) return;
	SetCharacterToInfoCharacter( GetPassengerFromScroll(nCurFScrollNum) );
	SetShowMode(ISHOW_MODE_COMPANION);
	SetCaptainButtonsEnable();
}

void SetRepairData()
{
	int cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
	int st = GetCharacterShipType(GetCharacter(cn));
	makearef(arCurShip, Characters[cn].ship); // PRS3

	int hp = MakeInt(GetHullPercent(GetCharacter(cn)));
	int sp = MakeInt(GetSailPercent(GetCharacter(cn)));

	// TIH --> handled properly now  Jul27'06
	int hcost = GetHullRepairCost(GetCharacter(cn), GetHullDamagePercent(nCurFourNum)); // KK
	int scost = GetSailRepairCost(GetCharacter(cn), GetSailDamagePercent(nCurFourNum)); // KK

	// LDH --> 27Sep06
	int gcost = 0;
	ref chref = GetCharacter(cn);
	if (cn>=0) gcost = (GetCannonMaxQuantity(chref) - GetCannonQuantity(chref)) * GetCannonPrice(sti(chref.ship.cannons.type));
	if (tradeHigh) gcost *= 2;
	// LDH <--

	/* prior broken method
	// changed by MAXIMUS [possibility to repair your ship by double price] -->
	int hcost;
	int scost;
	if(tradeHigh==true)
	{
		hcost = GetHullRepairCost(st,GetHullDamagePercent(nCurFourNum))*2;
		scost = GetSailRepairCost(st,GetSailDamagePercent(nCurFourNum))*2;
	}
	else
	{
		hcost = GetHullRepairCost(st,GetHullDamagePercent(nCurFourNum));
		scost = GetSailRepairCost(st,GetSailDamagePercent(nCurFourNum));
	}
	// changed by MAXIMUS [possibility to repair your ship by double price] <--
	*/
	// TIH <--

    GameInterface.strings.HullPercent = hp + "%";
    GameInterface.strings.SailsPercent = sp + "%";
    GameInterface.strings.RepairHullCost = hcost;
    GameInterface.strings.RepairSailsCost = scost;
    GameInterface.strings.RepairAllCost = MakeMoneyShow(hcost + scost + gcost,MONEY_SIGN,MONEY_DELIVER); // NK

	nhpRepair = hp;
	nspRepair = sp;
	SetRapairButtonSelected();
}

void SetRapairButtonSelected()
{
	int cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
	int st = GetCharacterShipType(GetCharacter(cn));
	makearef(arCurShip, Characters[cn].ship); // PRS3

	int hp = MakeInt(GetHullPercent(GetCharacter(cn)));
	int sp = MakeInt(GetSailPercent(GetCharacter(cn)));

	// TIH --> handled properly now Jul27'06
	int hcost = GetHullRepairCost(GetCharacter(cn), GetHullDamagePercent(nCurFourNum)); // KK
	int scost = GetSailRepairCost(GetCharacter(cn), GetSailDamagePercent(nCurFourNum)); // KK

	// LDH --> 27Sep06
	int gcost = 0;
	ref chref = GetCharacter(cn);
	if (cn>=0) gcost = (GetCannonMaxQuantity(chref) - GetCannonQuantity(chref)) * GetCannonPrice(sti(chref.ship.cannons.type));
	if (tradeHigh) gcost *= 2;
	// LDH <--

	/* prior broken method
	// changed by MAXIMUS [possibility to repair your ship by double price] -->
	int hcost;
	int scost;
	if(tradeHigh==true)
	{
		hcost = GetHullRepairCost(st,GetHullDamagePercent(nCurFourNum))*2;
		scost = GetSailRepairCost(st,GetSailDamagePercent(nCurFourNum))*2;
	}
	else
	{
		hcost = GetHullRepairCost(st,GetHullDamagePercent(nCurFourNum));
		scost = GetSailRepairCost(st,GetSailDamagePercent(nCurFourNum));
	}
	// changed by MAXIMUS [possibility to repair your ship by double price] <--
	*/
	// TIH <--

	SetSelectable("FIXALL_BUTTON",hp<100 || sp<100 || gcost>0);	// LDH 27Sep06
	SetSelectable("HULLQUANTITY",hp<100);
	SetSelectable("SAILSQUANTITY",sp<100);
	SetSelectable("REPAIR_OK",nhpRepair>hp || nspRepair>sp || gcost>0);	// LDH 27Sep06

	int color = COLOR_DESELECT;
	if(hp<100)	color = COLOR_NORMAL;
	GameInterface.strings.HullPercent = hp+"%";
//    CreateString(true,"HullPercent",hp+"%",FONT_NORMAL,color,320,282,SCRIPT_ALIGN_CENTER,1.0); // removed by MAXIMUS
	color = COLOR_DESELECT;
	if(sp<100)	color = COLOR_NORMAL;
	GameInterface.strings.SailsPercent = sp+"%";
//    CreateString(true,"SailsPercent",sp+"%",FONT_NORMAL,color,320,326,SCRIPT_ALIGN_CENTER,1.0); // removed by MAXIMUS

	string curNod = GetCurrentNode();
	if( curNod=="FIXALL_BUTTON" || curNod=="HULLQUANTITY" ||
		curNod=="SAILSQUANTITY" || curNod=="REPAIR_OK" )
	{
		Event("ievnt_command","ss","downstep",curNod);
	}
}

void SetViewShipData(int shipType, int shipCost) // modded to PRS3, adding the aref.
{
	ref shref = GetShipByType(shipType);
	GameInterface.strings.ShipClass = sti(GetLocalShipAttrib(arCurShip, shref, "Class"));
	GameInterface.strings.HullPoints = sti(GetLocalShipAttrib(arCurShip, shref, "HP"));
	GameInterface.strings.Speed = FloatToString(stf(GetLocalShipAttrib(arCurShip, shref, "SpeedRate")),2);
	GameInterface.strings.Maneuver = FloatToString(stf(GetLocalShipAttrib(arCurShip, shref, "TurnRate")),2);
	GameInterface.strings.Capacity = sti(GetLocalShipAttrib(arCurShip, shref, "Capacity"));
	GameInterface.strings.MaxCrew = sti(GetLocalShipAttrib(arCurShip, shref, "MaxCrew"));
	GameInterface.strings.MinCrew = sti(GetLocalShipAttrib(arCurShip, shref, "MinCrew"));
	GameInterface.strings.CannonsQuantity = sti(GetLocalShipAttrib(arCurShip, shref, "CurCanQty")); //NK can qty 05-04-18 "CannonsQuantity"));
	GameInterface.strings.MaxCaliber = sti(GetLocalShipAttrib(arCurShip, shref, "MaxCaliber"));

	// TIH --> no... this shipcost is ALREADY FIGURED by now Jul27'06
	// changed by MAXIMUS [possibility to repair your ship by double price] -->
	//if(tradeHigh==true) GameInterface.strings.ShipCost = MakeMoneyShow(shipCost*2,MONEY_SIGN,MONEY_DELIVER); // NK
	//else 				GameInterface.strings.ShipCost = MakeMoneyShow(shipCost,MONEY_SIGN,MONEY_DELIVER); // NK
	// changed by MAXIMUS [possibility to repair your ship by double price] <--
	GameInterface.strings.ShipCost = MakeMoneyShow(shipCost,MONEY_SIGN,MONEY_DELIVER);
	// TIH <--

	// TIH --> rpg_style Jul27'06
	if ( SY_RPG_STYLE ) {
		string attributeName = "pic" + (nCurSScrollNum+1);
		if ( CheckAttribute(GameInterface,"scrollitems."+(attributeName)+".skipsell") && GameInterface.scrollitems.(attributeName).skipsell==true ) {
			EnableString("NoBuyString");
			//SetNodeUsing("NOBUYBOX1",true);
			SetNodeUsing("NOBUYBOX2",true);
			// PB: Realistic Ship Purchase -->
			if( CheckAttribute(GameInterface,"scrollitems."+(attributeName)+".pirateship") && GameInterface.scrollitems.(attributeName).pirateship==true )
			{GameInterface.strings.NoBuyString = XI_ConvertString("Cannot Buy - Pirate Ship");}
			else
			{
				if( CheckAttribute(GameInterface,"scrollitems."+(attributeName)+".navyship") && GameInterface.scrollitems.(attributeName).navyship==true )
				{GameInterface.strings.NoBuyString = XI_ConvertString("Cannot Buy - Navy Ship");}
				else
				{GameInterface.strings.NoBuyString = XI_ConvertString("Cannot Buy - Class Too High");}
			}
			// PB: Realistic Ship Purchase <--
		} else {
			DisableString("NoBuyString");
			//SetNodeUsing("NOBUYBOX1",false);
			SetNodeUsing("NOBUYBOX2",false);
			GameInterface.strings.NoBuyString = "";
		}
	}
	// TIH <--

	// added by KAM -->
	// PRS3 modded
	int tempnation;
	if (!CheckShipAttribute(arCurShip, shref, "Nation"))
	{
		tempnation = -1;
	}
	else
	{
		tempnation = GetLocalShipAttrib(arCurShip, shref, "Nation");
	}

	string tempnationstr;
	if (tempnation == 5 || tempnation == 2)
	{
		tempnationstr = Nations[tempnation].name;
		CreateImage("NationalDesignFlag","NATIONS_1",tempnationstr,420,250,460,290);
		SetFormatedText("NATIONALDESIGN",XI_ConvertString("2"+Nations[tempnation].desc) + " " + XI_ConvertString("design"));
	}
	else
	{
		if (tempnation == 3 || tempnation == 0 || tempnation == 4 || tempnation == 1)
		{
			tempnationstr = Nations[tempnation].name;
			if (tempnationstr == "Britain") { tempnationstr = "England"; }
			CreateImage("NationalDesignFlag","NATIONS_2",tempnationstr,420,250,460,290);
// KK -->
			if (tempnation != 3)
				SetFormatedText("NATIONALDESIGN",XI_ConvertString("2"+Nations[tempnation].desc) + " " + XI_ConvertString("design"));
			else
				SetFormatedText("NATIONALDESIGN",XI_ConvertString("2"+"Pirates") + " " + XI_ConvertString("design"));
// <-- KK
		}
		else
		{
			CreateImage("NationalDesignFlag","NATIONS_3","Neutral",420,250,460,290);
			SetFormatedText("NATIONALDESIGN",XI_ConvertString("Individual design"));
		}
	}

	// <-- added by KAM
}

void UpdateSScrollData()
{
	int st = GetScrollShipType(nCurSScrollNum);
	//unneeded, modified above func. makearef(arCurShip, GetScrollShipAttr(nCurSScrollNum)); // PRS3
	if(st==SHIP_NOTUSED)
	{
		SetShowMode(ISHOW_MODE_EMPTYVIEW);
	}
	else
	{
		SetShowMode(ISHOW_MODE_VIEW);
		SetViewShipData(st,GetBuyPrice(nCurSScrollNum));
	}
}

void SetCurrentRepairButton()
{
	if(GetSelectable("FIXALL_BUTTON"))
	{
		SetCurrentNode("FIXALL_BUTTON");
	}
}

void ProcessCommandExecute()
{
	int i,cn;

	string comName = GetEventData();
	string nodName = GetEventData();

	switch(nodName)
	{
	case "SCROLLITEMS":
		if(comName=="activate")
		{
// KK -->
			if(!LAi_IsCapturedLocation)
			{
				if(IsEnableBuyShip() && IsMoneyForBuyEnable())
				{
					SetShowMode(ISHOW_MODE_BUY);
					SetCurrentNode("OK_BUTTON");
					GameInterface.strings.TradePrice = MakeMoneyShow(GetBuyPrice(nCurSScrollNum)-GetSellPrice(nCurFourNum,"skipcargo"),MONEY_SIGN,MONEY_DELIVER); // TIH added handler Jul27'06 // Viper - Add Cargo Value to Ship Price
				}
			}
			else
			{
				DoBuyShip();
				UpdateFourImages();
				UpdateShipScroll();
				SetCurrentNode("SHIPSLIST");
				nCurSScrollNum = -1;
				nCurFourNum = -1;
			}
// <-- KK
		}
	break;

	case "PASSENGERS":
		if(comName=="activate" || comName=="downstep")
		{
			SelectCaptainButton();
		}
	break;

	case "SHIPSLIST":
		if(comName=="activate")
		{
			if(nShowMode!=ISHOW_MODE_COMPANION)
			{
				SetShowMode(ISHOW_MODE_CHOOSE);
				EnableChooseButtons();
				ChooseButtonTopSelect();
			} else {SelectCaptainButton();}
		}
	break;

	case "LEFTSCROLLBUTTON":
		switch(comName)
		{
		case "click":
			if(GetSelectable("SCROLLITEMS"))
			{
				SetCurrentNode("SCROLLITEMS");
				SendMessage(&GameInterface,"lslll",MSG_INTERFACE_MSG_TO_NODE,"SCROLLITEMS",-1, 0,ACTION_LEFTSTEP);
			}
			else
			{
				SetCurrentNode("PASSENGERS");
				SendMessage(&GameInterface,"lslll",MSG_INTERFACE_MSG_TO_NODE,"PASSENGERS",-1, 0,ACTION_LEFTSTEP);
			}
		break;
		}
	break;

	case "RIGHTSCROLLBUTTON":
		switch(comName)
		{
		case "click":
			if(GetSelectable("SCROLLITEMS"))
			{
				SetCurrentNode("SCROLLITEMS");
				SendMessage(&GameInterface,"lslll",MSG_INTERFACE_MSG_TO_NODE,"SCROLLITEMS",-1, 0,ACTION_RIGHTSTEP);
			}
			else
			{
				SetCurrentNode("PASSENGERS");
				SendMessage(&GameInterface,"lslll",MSG_INTERFACE_MSG_TO_NODE,"PASSENGERS",-1, 0,ACTION_RIGHTSTEP);
			}
		break;
		}
	break;

	case "FIXALL_BUTTON":
		if(comName=="downstep")
		{
			if(GetSelectable("HULLQUANTITY"))
			{
				SetCurrentNode("HULLQUANTITY");
			}
			else
			{
				Event("ievnt_command","ss",comName,"HULLQUANTITY");
			}
		}
		if(comName=="activate" || comName=="click")
		{
			cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
			if(cn>=0)
			{
				makearef(arCurShip, Characters[cn].ship); // PRS3
				DoHullRepairToPercent(GetCharacter(cn),100);
				DoSailRepairToPercent(GetCharacter(cn),100);
				DoCannonRepair(GetCharacter(cn));	// LDH 27Sep06
				SetRepairData();
				SetCurrentNode("SHIPSLIST");
			}
		}
	break;

	case "HULLQUANTITY":
		switch(comName)
		{
		case "downstep":
			if(GetSelectable("SAILSQUANTITY"))
			{
				SetCurrentNode("SAILSQUANTITY");
			}
			else
			{
				Event("ievnt_command","ss",comName,"SAILSQUANTITY");
			}
		break;
		case "upstep":
			if(GetSelectable("FIXALL_BUTTON"))
			{
				SetCurrentNode("FIXALL_BUTTON");
			}
		break;
		case "rightstep":
			ChangeHullRepair(1);
			cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
			if(cn<0) {SetSelectable("REPAIR_OK",false);}
			else
			{
				makearef(arCurShip, Characters[cn].ship); // PRS3
				SetSelectable("REPAIR_OK",
					nhpRepair>MakeInt(GetHullPercent(GetCharacter(cn))) ||
					nspRepair>MakeInt(GetSailPercent(GetCharacter(cn))) );
			}
			if(OldNodeName!="HULLQUANTITY")
			{
				OldNodeName="HULLQUANTITY";
				SetCurrentNode("HULLQUANTITY");
			}
		break;
		case "leftstep":
			ChangeHullRepair(-1);
			cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
			if(cn<0) {SetSelectable("REPAIR_OK",false);}
			else
			{
				makearef(arCurShip, Characters[cn].ship); // PRS3
				SetSelectable("REPAIR_OK",
					nhpRepair>MakeInt(GetHullPercent(GetCharacter(cn))) ||
					nspRepair>MakeInt(GetSailPercent(GetCharacter(cn))) );
			}
			if(OldNodeName!="HULLQUANTITY")
			{
				OldNodeName="HULLQUANTITY";
				SetCurrentNode("HULLQUANTITY");
			}
		break;
		}
	break;

	case "SAILSQUANTITY":
		switch(comName)
		{
		case "downstep":
			if(GetSelectable("REPAIR_OK"))
			{
				SetCurrentNode("REPAIR_OK");
			}
			else
			{
				Event("ievnt_command","ss",comName,"REPAIR_OK");
			}
		break;
		case "upstep":
			if(GetSelectable("HULLQUANTITY"))
			{
				SetCurrentNode("HULLQUANTITY");
			}
			else
			{
				Event("ievnt_command","ss",comName,"HULLQUANTITY");
			}
		break;
		case "rightstep":
			ChangeSailRepair(1);
			cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
			if(cn<0) {SetSelectable("REPAIR_OK",false);}
			else
			{
				makearef(arCurShip, Characters[cn].ship); // PRS3
				SetSelectable("REPAIR_OK",
					nhpRepair>MakeInt(GetHullPercent(GetCharacter(cn))) ||
					nspRepair>MakeInt(GetSailPercent(GetCharacter(cn))) );
			}
			if(OldNodeName!="SAILSQUANTITY")
			{
				OldNodeName="SAILSQUANTITY";
				SetCurrentNode("SAILSQUANTITY");
			}
		break;
		case "leftstep":
			ChangeSailRepair(-1);
			cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
			if(cn<0) {SetSelectable("REPAIR_OK",false);}
			else
			{
				makearef(arCurShip, Characters[cn].ship); // PRS3
				SetSelectable("REPAIR_OK",
					nhpRepair>MakeInt(GetHullPercent(GetCharacter(cn))) ||
					nspRepair>MakeInt(GetSailPercent(GetCharacter(cn))) );
			}
			if(OldNodeName!="SAILSQUANTITY")
			{
				OldNodeName="SAILSQUANTITY";
				SetCurrentNode("SAILSQUANTITY");
			}
		break;
		}
	break;

	case "REPAIR_OK":
		switch(comName)
		{
		case "upstep":
			if(GetSelectable("SAILSQUANTITY"))
			{
				SetCurrentNode("SAILSQUANTITY");
			}
			else
			{
				Event("ievnt_command","ss",comName,"SAILSQUANTITY");
			}
		break;
		}
		if(comName=="activate" || comName=="click")
		{
			cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
			if(cn>=0)
			{
				makearef(arCurShip, Characters[cn].ship); // PRS3
				DoHullRepairToPercent(GetCharacter(cn),nhpRepair);
				DoSailRepairToPercent(GetCharacter(cn),nspRepair);
				SetRepairData();
				if( !IsEnableRepairShip() ) {
					SetCurrentNode("SHIPSLIST");
				}
				else {
					SetCurrentNode("FIXALL_BUTTON");
				}
			}
		}
	break;

	case "OK_BUTTON":
		if(comName=="activate" || comName=="click")
		{
			if(nShowMode==ISHOW_MODE_SELL)
			{
				DoSellShip("firecrew","includecargo");// TIH added handlers Jul27'06
			}
			if(nShowMode==ISHOW_MODE_BUY)
			{
				DoBuyShip();
			}
			UpdateFourImages();
			UpdateShipScroll();
			SetCurrentNode("SHIPSLIST");
			nCurSScrollNum = -1;
			nCurFourNum = -1;
		}
	break;

	case "CANCEL_BUTTON":
	break;

	case "SKILLINFO_BUTTON":
		if(comName=="activate" || comName=="click")
		{
			SetShowMode(ISHOW_MODE_SKILLS);
			SetSkillData();
			SetCurrentNode("SKILLS_IMAGES");
		}
		if(comName=="upstep")	{SetNextCaptainButton(nodName,true);}
		if(comName=="downstep")	{SetNextCaptainButton(nodName,false);}
	break;

	case "REMOVEC_BUTTON":
		if(comName=="activate" || comName=="click")
		{
			FireCaptain();
			SetCurrentNode("SHIPSLIST");
		}
		if(comName=="upstep")	{SetNextCaptainButton(nodName,true);}
		if(comName=="downstep")	{SetNextCaptainButton(nodName,false);}
	break;

	case "SETC_BUTTON":
		if(comName=="activate" || comName=="click")
		{
			UpdateCompanionCharacter();
			SetCurrentNode("SHIPSLIST");
		}
		if(comName=="upstep")	{SetNextCaptainButton(nodName,true);}
	break;

	case "BUY_BUTTON":
		if(comName=="activate" || comName=="click")
		{
			SetShowMode(ISHOW_MODE_VIEW);
			SetCurrentNode("SCROLLITEMS");
		}
		if(comName=="upstep")	{ChooseButtonNextSelect(nodName,true);}
		if(comName=="downstep")	{ChooseButtonNextSelect(nodName,false);}
	break;

	case "REPAIR_BUTTON":
		if(comName=="activate" || comName=="click")
		{
			SetShowMode(ISHOW_MODE_REPAIR);
			SetRepairData();
			SetCurrentRepairButton();
		}
		if(comName=="upstep")	{ChooseButtonNextSelect(nodName,true);}
		if(comName=="downstep")	{ChooseButtonNextSelect(nodName,false);}
	break;

	case "SELLSHIP_BUTTON":
		if(comName=="activate" || comName=="click")
		{
			// NK -->
// KK -->
			if(!LAi_IsCapturedLocation)
			{
				if(IsMoneyForSellEnable())
				{
					SetShowMode(ISHOW_MODE_SELL);
					SetCurrentNode("OK_BUTTON");
					makearef(arCurShip, Characters[GetCompanionIndex(GetMainCharacter(),nCurFourNum)].ship); // PRS3
					GameInterface.strings.TradePrice = MakeMoneyShow(GetSellPrice(nCurFourNum,"includecargo"),MONEY_SIGN,MONEY_DELIVER);// TIH added handler Jul27'06
				}
			}
			else
			{
				DoSellShip("firecrew","includecargo");// TIH added handlers Jul27'06
				UpdateFourImages();
				UpdateShipScroll();
				SetCurrentNode("SHIPSLIST");
				nCurSScrollNum = -1;
				nCurFourNum = -1;
			}
// <-- KK
			// NK <--
		}
		if(comName=="upstep")	{ChooseButtonNextSelect(nodName,true);}
		if(comName=="downstep")	{ChooseButtonNextSelect(nodName,false);}
	break;

	case "CHANGE_CAPTAIN":
		if(comName=="activate" || comName=="click")
		{
			SetShowMode(ISHOW_MODE_COMPANION);
			SetCaptainButtonsEnable();
			SetCurrentNode("PASSENGERS");
		}
		if(comName=="upstep")	{ChooseButtonNextSelect(nodName,true);}
		if(comName=="downstep")	{ChooseButtonNextSelect(nodName,false);}
	break;
	}
}

void SetShowMode(int newMode)
{
	if(newMode==nShowMode) return;
	switch(nShowMode)
	{
	case ISHOW_MODE_VIEW:
		DisableString("ShipClass");
		DisableString("HullPoints");
		DisableString("Speed");
		DisableString("Maneuver");
		DisableString("Capacity");
		DisableString("MaxCrew");
		DisableString("MinCrew");
		DisableString("CannonsQuantity");
		DisableString("MaxCaliber");
		DisableString("ShipCost");
		DisableString("ShipName");
		SetNodeUsing("SHIPNAMETITLE",false);
		SetNodeUsing("MAINPICTURES",false);
		GameInterface.pictures.NationalDesignFlag.pic = -1;		// added by KAM
		GameInterface.pictures.NationalDesignFlag.tex = -1;		// added by KAM
		SetNodeUsing("NATIONALDESIGN",false);				// added by KAM
	break;

	case ISHOW_MODE_EMPTYVIEW:
		SetNodeUsing("SHIPNAMETITLE",false);
		DisableString("ShipName");
	break;

	case ISHOW_MODE_BUY:
		SetNodeUsing("BUYCONFIRM",false);
		SetNodeUsing("OK_BUTTON",false);
		SetNodeUsing("CANCEL_BUTTON",false);
		DisableString("TradePrice");
	break;

	case ISHOW_MODE_SELL:
		SetNodeUsing("SELLCONFIRM",false);
		SetNodeUsing("OK_BUTTON",false);
		SetNodeUsing("CANCEL_BUTTON",false);
		DisableString("TradePrice");
	break;

	case ISHOW_MODE_REPAIR:
		DisableString("RepairAllCost");
		DisableString("HullPercent");
		DisableString("RepairHullCost");
		DisableString("SailsPercent");
		DisableString("RepairSailsCost");
		DisableString("ShipName");

		SetNodeUsing("SHIPNAMETITLE",false);
		SetNodeUsing("REPAIRSTRINGS",false);
		SetNodeUsing("FIXALL_BUTTON",false);
		SetNodeUsing("HULLQUANTITY",false);
		SetNodeUsing("SAILSQUANTITY",false);
		SetNodeUsing("REPAIR_OK",false);
		SetNodeUsing("RECT_FIXALL_PRICE",false);
		SetNodeUsing("RECT_HULL_PRICE",false);
		SetNodeUsing("RECT_SAILS_PRICE",false);
		SetNodeUsing("RECT_SELL_PRICE",false);
		SetNodeUsing("REPAIRIMAGES",false);
	break;

	case ISHOW_MODE_COMPANION:
		DisableString("CharacterName");
		SetNodeUsing("SHIPNAMETITLE",false);
		SetNodeUsing("SCROLLITEMS",true);
		SetNodeUsing("PASSENGERS",false);
		SetNodeUsing("SKILLINFO_BUTTON",false);
		SetNodeUsing("REMOVEC_BUTTON",false);
		SetNodeUsing("SETC_BUTTON",false);
	break;

	case ISHOW_MODE_CHOOSE:
		SetNodeUsing("BUY_BUTTON",false);
		SetNodeUsing("REPAIR_BUTTON",false);
		SetNodeUsing("SELLSHIP_BUTTON",false);
		SetNodeUsing("CHANGE_CAPTAIN",false);
	break;

	case ISHOW_MODE_SKILLS:
		DisableString("CharacterName");
		DisableString("skillLeadership");
		DisableString("skillFencing");
		DisableString("skillSailing");
		DisableString("skillAccuracy");
		DisableString("skillCannons");
		DisableString("skillGrappling");
		DisableString("skillRepair");
		DisableString("skillDefence");
		DisableString("skillCommerce");
		DisableString("skillSneak");
		SetNodeUsing("SHIPNAMETITLE",false);
		SetNodeUsing("SKILLS_IMAGES",false);
		SetNodeUsing("SCROLLITEMS",true);
		SetNodeUsing("PASSENGERS",false);
	break;
	}

	nShowMode = newMode;
	switch(nShowMode)
	{
	case ISHOW_MODE_VIEW:
		EnableString("ShipClass");
		EnableString("HullPoints");
		EnableString("Speed");
		EnableString("Maneuver");
		EnableString("Capacity");
		EnableString("MaxCrew");
		EnableString("MinCrew");
		EnableString("CannonsQuantity");
		EnableString("MaxCaliber");
		EnableString("ShipCost");
		EnableString("ShipName");
		SetNodeUsing("SHIPNAMETITLE",true);
		SetNodeUsing("MAINPICTURES",true);
		SetNodeUsing("NATIONALDESIGN",true);		// added by KAM
	break;

	case ISHOW_MODE_EMPTYVIEW:
		SetNodeUsing("SHIPNAMETITLE",true);
		EnableString("ShipName");
	break;

	case ISHOW_MODE_BUY:
		SetNodeUsing("BUYCONFIRM",true);
		SetNodeUsing("OK_BUTTON",true);
		SetNodeUsing("CANCEL_BUTTON",true);
		EnableString("TradePrice");
	break;

	case ISHOW_MODE_SELL:
		SetNodeUsing("SELLCONFIRM",true);
		SetNodeUsing("OK_BUTTON",true);
		SetNodeUsing("CANCEL_BUTTON",true);
		EnableString("TradePrice");
	break;

	case ISHOW_MODE_REPAIR:
		EnableString("RepairAllCost");
		EnableString("HullPercent");
		EnableString("RepairHullCost");
		EnableString("SailsPercent");
		EnableString("RepairSailsCost");
		EnableString("ShipName");

		SetNodeUsing("SHIPNAMETITLE",true);
		SetNodeUsing("REPAIRSTRINGS",true);
		SetNodeUsing("FIXALL_BUTTON",true);
		SetNodeUsing("HULLQUANTITY",true);
		SetNodeUsing("SAILSQUANTITY",true);
		SetNodeUsing("REPAIR_OK",true);
		SetNodeUsing("RECT_FIXALL_PRICE",true);
		SetNodeUsing("RECT_HULL_PRICE",true);
		SetNodeUsing("RECT_SAILS_PRICE",true);
		SetNodeUsing("RECT_SELL_PRICE",true);
		SetNodeUsing("REPAIRIMAGES",true);
	break;

	case ISHOW_MODE_COMPANION:
		EnableString("CharacterName");
		SetNodeUsing("SHIPNAMETITLE",true);
		SetNodeUsing("SCROLLITEMS",false);
		SetNodeUsing("PASSENGERS",true);
		SetNodeUsing("SKILLINFO_BUTTON",true);
		SetNodeUsing("REMOVEC_BUTTON",true);
		SetNodeUsing("SETC_BUTTON",true);
	break;

	case ISHOW_MODE_CHOOSE:
		sPreviouseNode = GetCurrentNode();
		SetNodeUsing("BUY_BUTTON",true);
		SetNodeUsing("REPAIR_BUTTON",true);
		SetNodeUsing("SELLSHIP_BUTTON",true);
		SetNodeUsing("CHANGE_CAPTAIN",true);
	break;

	case ISHOW_MODE_SKILLS:
		EnableString("CharacterName");
		EnableString("skillLeadership");
		EnableString("skillFencing");
		EnableString("skillSailing");
		EnableString("skillAccuracy");
		EnableString("skillCannons");
		EnableString("skillGrappling");
		EnableString("skillRepair");
		EnableString("skillDefence");
		EnableString("skillCommerce");
		EnableString("skillSneak");
		SetNodeUsing("SHIPNAMETITLE",true);
		SetNodeUsing("SKILLS_IMAGES",true);
		SetNodeUsing("SCROLLITEMS",false);
		SetNodeUsing("PASSENGERS",true);
	break;
	}
}

void FillSScroll()
{
	nCurSScrollNum = -1;
	if(!CheckAttribute(&GameInterface,"scrollitems.current"))
		GameInterface.scrollitems.current = 0;

    string attributeName;
    string shipName;
	ref PChar = GetMainCharacter();
	GameInterface.scrollitems.BadPicture2 = "interfaces\blank_ship.tga";
	GameInterface.scrollitems.ImagesGroup.t0 = "ICONS";
	GameInterface.scrollitems.ImagesGroup.t1 = "SHIPS16";
	GameInterface.scrollitems.ImagesGroup.t2 = "SHIPS1";

	// TIH --> sy_rpg_style selection visual adjustment Jul27'06
	if ( SY_RPG_STYLE ) {
		GameInterface.scrollitems.SpecTechniqueColor = argb(80,255,255,255);
		GameInterface.scrollitems.SpecTechniqueName = "iSpec1";
		float mcL = makefloat(GetLevel(GetMainCharacter()));
		int allowedClass = iclamp(1,7 , makeint( 7 - roundup(mcL / makefloat(SHIPYARD_RPG_LPC)) ));
		// for every SHIPYARD_RPG_LPC levels, they gain access to next class (7 is always available)
		trace("SY player level "+mcL+" gains access to class "+allowedClass+" and below");
	}
	// TIH <--

	aref curref;
	int st; // PRS3
    for(int i=0;i<GetAttributesNum(arShipList);i++)
    {
		curref = GetAttributeN(arShipList,i);
		st = sti(GetAttributeValue(curref)); // PRS3
        attributeName = "pic" + (i+1);
		makearef(arCurShip, curref); // PRS3
        shipName = GetLocalShipAttrib(arCurShip, ShipsTypes[st],"SName"); // PRS3

        GameInterface.scrollitems.(attributeName).str1 = "#"+GetLocalShipAttrib(arCurShip, ShipsTypes[st],"Class"); // PRS3
        GameInterface.scrollitems.(attributeName).str2 = shipName;
        GameInterface.scrollitems.(attributeName).img1 = "ship back";
        GameInterface.scrollitems.(attributeName).img2 = GetShipPicName(st); // PS
		GameInterface.scrollitems.(attributeName).tex1 = 0;
		GameInterface.scrollitems.(attributeName).tex2 = 1+GetShipTexture(st); // PS

		// TIH --> sy_rpg_style selection visual adjustment Jul27'06
		if( SY_RPG_STYLE )
		{
			GameInterface.scrollitems.(attributeName).spec2 = sti(GetLocalShipAttrib(arCurShip, ShipsTypes[st],"Class"))<allowedClass && LAi_IsCapturedLocation==false;
			GameInterface.scrollitems.(attributeName).skipsell = sti(GetLocalShipAttrib(arCurShip, ShipsTypes[st],"Class"))<allowedClass && LAi_IsCapturedLocation==false;
		}
		// TIH <--

	// PB: Realistic Ship Purchase -->
		GameInterface.scrollitems.(attributeName).navyship = false;
		GameInterface.scrollitems.(attributeName).pirateship = false;
		if(REALISTIC_SHIP_PURCHASE == 1 && LAi_IsCapturedLocation == false) // KK
		{
			if(GetCurrentLocationNation() == PIRATE)
			{	
				if(GetLocalShipAttrib(arCurShip, ShipsTypes[st],"Nation") == PIRATE) GameInterface.scrollitems.(attributeName).pirateship = true;
				if(PChar.nation == PIRATE && GetFame(PChar, PIRATE) > PIRATE_REQFAME) GameInterface.scrollitems.(attributeName).pirateship = false;
			}
			else
			{
				if(GetLocalShipAttrib(arCurShip, ShipsTypes[st],"Type.War") == true && GetLocalShipAttrib(arCurShip, ShipsTypes[st],"Type.Trade") == false && GetCurrentLocationNation() != PIRATE)
				{
					switch(sti(GetLocalShipAttrib(arCurShip, ShipsTypes[st],"Class")))
					{
						case 1:
							if(RANK_FOR_FIRST_RATE == 0 && !HaveLetterOfMarque(GetCurrentLocationNation()))
							{GameInterface.scrollitems.(attributeName).navyship = true;}

							if(RANK_FOR_FIRST_RATE > 0 && GetRank(GetMainCharacterIndex(), GetCurrentLocationNation()) <= RANK_FOR_FIRST_RATE)
							{GameInterface.scrollitems.(attributeName).navyship = true;}
							break;
						case 2:
							if(RANK_FOR_SECOND_RATE == 0 && !HaveLetterOfMarque(GetCurrentLocationNation()))
							{GameInterface.scrollitems.(attributeName).navyship = true;}

							if(RANK_FOR_SECOND_RATE > 0 && GetRank(GetMainCharacterIndex(), GetCurrentLocationNation()) <= RANK_FOR_FIRST_RATE)
							{GameInterface.scrollitems.(attributeName).navyship = true;}
							break;					
						case 3:
							if(RANK_FOR_THIRD_RATE == 0 && !HaveLetterOfMarque(GetCurrentLocationNation()))
							{GameInterface.scrollitems.(attributeName).navyship = true;}

							if(RANK_FOR_THIRD_RATE > 0 && GetRank(GetMainCharacterIndex(), GetCurrentLocationNation()) <= RANK_FOR_FIRST_RATE)
							{GameInterface.scrollitems.(attributeName).navyship = true;}
							break;					
						case 4:
							if(RANK_FOR_FOURTH_RATE == 0 && !HaveLetterOfMarque(GetCurrentLocationNation()))
							{GameInterface.scrollitems.(attributeName).navyship = true;}

							if(RANK_FOR_FOURTH_RATE > 0 && GetRank(GetMainCharacterIndex(), GetCurrentLocationNation()) <= RANK_FOR_FIRST_RATE)
							{GameInterface.scrollitems.(attributeName).navyship = true;}
							break;
						case 5:
							if(RANK_FOR_FIFTH_RATE == 0 && !HaveLetterOfMarque(GetCurrentLocationNation()))
							{GameInterface.scrollitems.(attributeName).navyship = true;}

							if(RANK_FOR_FIFTH_RATE > 0 && GetRank(GetMainCharacterIndex(), GetCurrentLocationNation()) <= RANK_FOR_FIRST_RATE)
							{GameInterface.scrollitems.(attributeName).navyship = true;}
							break;
						case 6:
							if(RANK_FOR_SIXTH_RATE == 0 && !HaveLetterOfMarque(GetCurrentLocationNation()))
							{GameInterface.scrollitems.(attributeName).navyship = true;}

							if(RANK_FOR_SIXTH_RATE > 0 && GetRank(GetMainCharacterIndex(), GetCurrentLocationNation()) <= RANK_FOR_FIRST_RATE)
							{GameInterface.scrollitems.(attributeName).navyship = true;}
							break;
						case 7:
							if(RANK_FOR_SEVENTH_RATE == 0 && !HaveLetterOfMarque(GetCurrentLocationNation()))
							{GameInterface.scrollitems.(attributeName).navyship = true;}

							if(RANK_FOR_SEVENTH_RATE > 0 && GetRank(GetMainCharacterIndex(), GetCurrentLocationNation()) <= RANK_FOR_FIRST_RATE)
							{GameInterface.scrollitems.(attributeName).navyship = true;}
							break;
					}
				}
			}
		}

		if(GameInterface.scrollitems.(attributeName).navyship)
		{
			GameInterface.scrollitems.(attributeName).spec2 = true;
			GameInterface.scrollitems.(attributeName).skipsell = true;
		}

		if(GameInterface.scrollitems.(attributeName).pirateship)
		{
			GameInterface.scrollitems.(attributeName).spec2 = true;
			GameInterface.scrollitems.(attributeName).skipsell = true;
		}
	// PB: Realistic Ship Purchase <--
    }

    GameInterface.scrollitems.ListSize = i+1;// TIH bugfix Jul27'06
	GameInterface.scrollitems.NotUsed = 5;
}

void FillFScroll()
{
	nCurFScrollNum = -1;// TIH bugfix
	DeleteAttribute(&GameInterface,"passengers");
    GameInterface.passengers.current = 0;
	GameInterface.passengers.NotUsed = 5;

	GameInterface.passengers.ImagesGroup.t0 = "EMPTYFACE";
	ref mchref = GetMainCharacter();
	FillFaceList( "passengers.ImagesGroup", mchref, 0 ); // officers
	FillFaceList( "passengers.ImagesGroup", mchref, 1 ); // companions
	FillFaceList( "passengers.ImagesGroup", mchref, 2 ); // passengers

	GameInterface.passengers.BadTex1 = 0;
	GameInterface.passengers.BadPic1 = "emptyface";

	ref charRef;
	string attributeName;
	nAllPassngerQuantity = 0;
	int cn = GetPassengerFromScroll(0);
	while(cn>=0)
	{
		attributeName = "pic" + (nAllPassngerQuantity+1);
		charRef = GetCharacter(cn);
		GameInterface.passengers.(attributeName).img1 = GetFacePicName(charRef);
		GameInterface.passengers.(attributeName).tex1 = FindFaceGroupNum("passengers.ImagesGroup","FACE128_"+charRef.FaceID);
		nAllPassngerQuantity++;
		cn=GetPassengerFromScroll(nAllPassngerQuantity);
	}
	GameInterface.passengers.ListSize = nAllPassngerQuantity;
}

void FillFourImages()
{
	nCurFourNum = -1;
	if(!CheckAttribute(&GameInterface,"FourImage.current"))
		GameInterface.FourImage.current = 0;

	GameInterface.FourImage.BadTwoPicture = "interfaces\blank_ship.tga";
	GameInterface.FourImage.ImagesGroup.t0 = "ICONS";
	GameInterface.FourImage.ImagesGroup.t1 = "SHIPS16";
	GameInterface.FourImage.ImagesGroup.t2 = "SHIPS1";
	GameInterface.FourImage.ImagesGroup.t3 = "EMPTYFACE";
	ref refMainCh = GetMainCharacter();
	FillFaceList( "FourImage.ImagesGroup", refMainCh, 0 ); // officers
	FillFaceList( "FourImage.ImagesGroup", refMainCh, 1 ); // companions
	FillFaceList( "FourImage.ImagesGroup", refMainCh, 2 ); // passengers

	int i,cn,tmpShipType;
	string tmp1,tmp2,tmpStr;

    for(i=0; i<4; i++)
    {
		tmpStr = "pic"+(i+1);

		tmpShipType = SHIP_NOTUSED;
		cn = GetCompanionIndex(refMainCh,i);
		if(cn!=-1)	tmpShipType = GetCharacterShipType(GetCharacter(cn));
		GameInterface.FourImage.(tmpStr).selected = cn!=-1 || nAllPassngerQuantity>0;

		if(tmpShipType==SHIP_NOTUSED)
		{
			if(cn>=0)
			{
				GameInterface.FourImage.(tmpStr).img1 = GetFacePicName(GetCharacter(cn));
				GameInterface.FourImage.(tmpStr).tex1 = FindFaceGroupNum("FourImage.ImagesGroup","FACE128_"+Characters[cn].FaceID);
				continue;
			}
			tmp1="";
			tmp2="";
		}
		else
		{
			ref baseShip = &ShipsTypes[tmpShipType];
			// PRS3 -->
			makearef(arCurShip, Characters[cn].ship);
			tmp1 = GetLocalShipAttrib(arCurShip, baseShip, "Class");
			tmp2 = GetLocalShipAttrib(arCurShip, baseShip, "SName");
			// PRS3 <--
		}

		GameInterface.FourImage.(tmpStr).img1		= "ship back";
		GameInterface.FourImage.(tmpStr).img2		= GetShipPicName(tmpShipType); // PS
		GameInterface.FourImage.(tmpStr).str1		= "#"+tmp1;
		GameInterface.FourImage.(tmpStr).str2		= GetShipString(tmpShipType); //PS tempfix XI_ConvertString(tmp2);
		GameInterface.FourImage.(tmpStr).tex1		= 0;
		GameInterface.FourImage.(tmpStr).tex2		= 1+GetShipTexture(tmpShipType); // PS
    }
}

// KK -->
/*int GetFourShipType(int fourIdx)
{
	// PRS3 -->
	int cn = GetCompanionIndex(GetMainCharacter(),fourIdx);
	if(cn<0)
	{
		makearef(arCurShip,NullCharacter);
		return SHIP_NOTUSED;
	}
	makearef(arCurShip,Characters[cn].ship);
	// PRS3 <--
	return GetCharacterShipType(GetCharacter(cn));
}*/
// <-- KK

int GetScrollShipType(int scrollIdx)
{
	// PRS3 -->
	if(scrollIdx<0 || scrollIdx>=GetAttributesNum(arShipList))
	{
		makearef(arCurShip,NullCharacter);
		return SHIP_NOTUSED;
	}
	arCurShip = GetAttributeN(arShipList,scrollIdx);
	return sti(GetAttributeValue(GetAttributeN(arShipList,scrollIdx)));
}

// PRS3 -->
//should not be needed.
aref GetScrollShipAttr(int scrollIdx)
{
	if(scrollIdx<0 || scrollIdx>=GetAttributesNum(arShipList)) return NullCharacter;
	return GetAttributeN(arShipList,scrollIdx);
}
// PRS3 <--

int GetPassengerFromScroll(int scrollIdx)
{
	ref chref;
	ref mch = GetMainCharacter();
	int q = GetPassengersQuantity(mch);

	int i,idx,cn;
	idx = 0;
	for(i=0; i<q; i++)
	{
		cn = GetPassenger(mch,i);
		if(cn>=0)
		{
			chref = GetCharacter(cn);
			if(GetRemovable(chref))
			{
				if( !CheckAttribute(chref,"prisoned") || chref.prisoned=="0" )
				{
					if( GetCharacterSkill(chref,SKILL_LEADERSHIP)>0 && GetCharacterSkill(chref,SKILL_SAILING)>0 )
					{
						if(idx==scrollIdx) return cn;
						idx++;
					}
				}
			}
		}
	}
	return -1;
}

int GetBuyPrice(int scrollIdx)
{
	if (LAi_IsCapturedLocation) return 0; // KK
	int price = MakeInt(GetScrollShipPriceByType(GetScrollShipType(scrollIdx)) * GetCharPriceMod(GetMainCharacter(), PRICE_TYPE_BUY, true));
	price -= MakeInt((0.1 * GetTownCrewMorale(GetTownIDFromLocID(Locations[FindLoadedLocation()].id)) / (MORALE_MAX - MORALE_MIN)) * makefloat(GetCurrentLocationNation() == PERSONAL_NATION)); // KK
// changed by MAXIMUS [possibility to repair your ship by double price] -->
	if(tradeHigh==true) price *= 2; // NK now use central func 05-04-19
	return price;
// changed by MAXIMUS [possibility to repair your ship by double price] <--
}

// TIH --> combined functions to one with proper calls Jul27'06
int GetSellPrice(int fourIdx, string cargoHandler)
{
	if (LAi_IsCapturedLocation) return 0; // KK
	int cn = GetCompanionIndex(GetMainCharacter(),fourIdx);
	if(cn<0) return 0;
	if (GetCharacterShipType(GetCharacter(cn)) == SHIP_NOTUSED) return 0; // KK
	makearef(arCurShip, Characters[cn].ship); // PRS3
	// KK int st = GetCharacterShipType(GetCharacter(cn));
	int price = GetShipPriceByType(GetCharacter(cn)); // KK
	price = price - GetSailRepairCost(GetCharacter(cn), GetSailDamagePercent(fourIdx)); // KK
	price = price - GetHullRepairCost(GetCharacter(cn), GetHullDamagePercent(fourIdx)); // KK
	
	// TIH --> added stolen ship price cuts (rpg style only) Jul27'06
	float sellMult = SHIPYARD_SHIP_SELL_MULT;
	if ( SY_RPG_STYLE && CheckAttribute(arCurShip,"acquired") ) {
		switch ( arCurShip.acquired ) {
			case "bought":	sellMult = SHIPYARD_BOUGHTSHIP_SELL_MULT;													break;
			case "taken":	sellMult = makefloat(((SHIPYARD_PIRATEDSHIP_SELL_MULT+SHIPYARD_BOUGHTSHIP_SELL_MULT)/2));	break;
			case "pirated":	sellMult = SHIPYARD_PIRATEDSHIP_SELL_MULT;													break;
			/*default:*/	sellMult = SHIPYARD_BOUGHTSHIP_SELL_MULT;
		}
	}
	// TIH <--

	// TIH --> better accuracy to prevent price banging Jul27'06
	// prevents someone from buying a ship for a new captain, and turning around and selling 
	// it for more than they just bought it for in the same interface session
	int baseCannonsType = CANNON_TYPE_NONECANNON;
	if(USE_REAL_CANNONS) 	baseCannonsType = CANNON_TYPE_LONG_LBS4;
	else 					baseCannonsType = CANNON_TYPE_CANNON_LBS12;
	// KK price = price + GetCannonDeltaPrice(GetCharacter(cn), baseCannonsType, GetCannonQuantity(GetCharacter(cn)), GetCannonMaxQuantity(GetCharacter(cn)));
	price += BuyCannons(GetCharacter(cn), baseCannonsType, GetCannonMaxQuantity(GetCharacter(cn)) - GetCannonQuantity(GetCharacter(cn)));
	// TIH <--

	// LDH 26Nov05 moved back here so cargo doesn't take a hit on sales price.  You can sell cargo at the store for full price anyway.
	price = makeint(price * GetCharPriceMod(GetMainCharacter(), PRICE_TYPE_SELL, true) * sellMult); // TIH moved down here where it is SUPPOSED TO BE - NK now use central func 05-04-19. Yes there is an extra *0.25, not just straight tradeprice.  //price /= (2 * 2 * 2); //pricescalar * orig div * extra div
	if ( cargoHandler == "includecargo" ) {// TIH added handler Jul27'06
		if(gprice[fourIdx] == -1)
		{
			gprice[fourIdx] = 0;
			// Viper - Add Cargo Value to Ship Price -->
			int p, tQuantity;	ref refStore;
			ref refCharacter = GetCharacter(cn);
			int curStoreIdx = GetCharacterCurrentStore(GetMainCharacter());
			makeref (refStore, Stores[curStoreIdx]);
			for(int i=0;i<GOODS_QUANTITY;i++)
			{
				if( !GetStoreGoodsUsed(refStore,i) ) { continue; }
				tQuantity = GetCargoGoods(refCharacter,i);
				if( tQuantity==0 ) { continue; }
				p = GetGoodPriceByType(&refStore, GetMainCharacter(), i, tQuantity, PRICE_TYPE_SELL); // NK
				gprice[fourIdx] += p;
			}
		}
	}
	price += gprice[fourIdx];
	return price;
}

/* depreciated Jul27'06
int GetSellPrice2(int fourIdx)
{
	int cn = GetCompanionIndex(GetMainCharacter(),fourIdx);
	if(cn<0) return 0;
	makearef(arCurShip, Characters[cn].ship); // PRS3
	int st = GetCharacterShipType(GetCharacter(cn));
	int price = GetShipPriceByType(st);
	price = price - GetSailRepairCost(st,GetSailDamagePercent(fourIdx));
	price = price - GetHullRepairCost(st,GetHullDamagePercent(fourIdx));
	price = makeint(price * GetCharPriceMod(GetMainCharacter(), PRICE_TYPE_SELL, true)*SHIPYARD_SHIP_SELL_MULT); // NK now use central func 05-04-19. Yes there is an extra *0.25, not just straight tradeprice.  //price /= (2 * 2 * 2); //pricescalar * orig div * extra div
	price = price + GetCannonDeltaPrice(GetCharacter(cn), CANNON_TYPE_NONECANNON);
	return price;
}
*/

// NK -->
// unneeded as this is now in StoreUtilite.c
/*int GetGoodPriceByType2(int iGoodType,int quantity,int price)
{
	int unitSize = sti(Goods[iGoodType].Units);
	int sumPrice = (quantity*price + unitSize-1) / unitSize;
	return sumPrice;
}*/
// NK <--
  // <-- Viper - Add Cargo Value to Ship Price


int GetSailDamagePercent(int fourIdx)
{
	int cn = GetCompanionIndex(GetMainCharacter(),fourIdx);
	if(cn<0) return 0;
	return 100 - MakeInt(GetSailPercent(GetCharacter(cn)));
}

int GetHullDamagePercent(int fourIdx)
{
	int cn = GetCompanionIndex(GetMainCharacter(),fourIdx);
	if(cn<0) return 0;
	return 100 - MakeInt(GetHullPercent(GetCharacter(cn)));
}

// KK -->
int GetScrollShipPriceByType(int st)
{
	if(st==SHIP_NOTUSED) return 0;
	ref shref = GetShipByType(st);
	return sti(shref.price)*2; // PRS3
}
// <-- KK

// NK 05-04-19 unneeded
/*int GetCannonsDiffPrice(ref chref)
{
	int cannonsQ = GetCannonQuantity(chref);
	if(cannonsQ<=0) return 0;
	int st = GetCharacterShipType(chref);
	if(st==SHIP_NOTUSED) return 0;
	//int ct = GetCaracterShipCannonsType(chref);
	int ctbase; if(USE_REAL_CANNONS) ctbase = CANNON_TYPE_LONG_LBS4; //KNB
	else ctbase = CANNON_TYPE_CANNON_LBS12; // NK
	//if(ct==ctbase) return 0;
	//return cannonsQ*(GetCannonPrice(ct)-GetCannonPrice(ctbase))/2; // NK
	return GetCannonDeltaPrice(&chref, ctbase); // NK can qty 05-04-19
}*/

// moved to cannons\cannons.c - NK 05-04-19 - int GetCannonPrice(int nCannonType)

int GetMyMoney()
{
	ref mychref = GetMainCharacter();
	return sti(mychref.Money);
}

//MAXIMUS -->
int GetExpDivider()
{
	aref curref = GetScrollShipAttr(nCurSScrollNum);
	int sc = sti(GetAttributeValue(curref));
	aref arCurShip; makearef(arCurShip, curref);
	int expDiv = sti(GetLocalShipAttrib(arCurShip, ShipsTypes[sc], "Class"));

	return expDiv;
}
//MAXIMUS <--

// TIH --> consolidated functions using proper calls instead Jul27'06
void DoSellShip(string crewHandler, string cargoHandler)
{
	int cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
	if(cn<0) return;
	ref chref = GetCharacter(cn);
	int sellPrice = GetSellPrice(nCurFourNum,cargoHandler);

	AddMoneyToCharacter(GetMainCharacter(),sellPrice);
	//MAXIMUS -->
	if(AUTO_SKILL_SYSTEM)
	{
		AddPartyExpChar(GetMainCharacter(), "Commerce", makeint(sellPrice/sti(1000/GetExpDivider())));
		AddCharacterExpNSChar(shipwright, "Commerce", makeint(sellPrice/sti(1000/GetExpDivider())));
	}
	//MAXIMUS <--
	// NK -->
	if ( crewHandler == "firecrew" ) { // TIH added handler Jul27'06
		SetTownCrewQuantity(sTownName, GetTownCrewQuantity(sTownName) + GetCrewQuantity(chref)); // NK 04-09-08 put fired crew in town
	}
	nStoreMoney -= sellPrice;
	GameInterface.strings.Money = MakeMoneyShow(sti(Characters[GetMainCharacterIndex()].money),MONEY_SIGN,MONEY_DELIVER);
	GameInterface.strings.SMoney = MakeMoneyShow(nStoreMoney,MONEY_SIGN,MONEY_DELIVER);
	// NK <--

	// TIH --> sy_rpg_style ship add to shipyard Jul27'06
	if ( SY_RPG_STYLE && CheckAttribute(chref,"ship.stats") ) {
		// since player sold a ship, add it to the shipyard listing
		string lastSlot = GetAttributeName( GetAttributeN( arShipList, (GetAttributesNum(arShipList)-1) ) );
		string shipYardSlot = "ship" + ( sti( strcut(lastSlot, 4, strlen(lastSlot)-1) ) + 1);

		arShipList.(shipYardSlot) = chref.ship.idx;
		arShipList.(shipYardSlot).stats = "";

		aref sto;
		aref sfrom;
		trace("SY sell ship to shipyard, from idx: "+ chref.ship.idx +" to slot: "+shipYardSlot);
		makearef(sto, 	arShipList.(shipYardSlot).stats);
		makearef(sfrom, chref.ship.stats);
		CopyAttributes(sto, sfrom); //copy stats tree over
		//int PRIORnCurSScrollNum = nCurSScrollNum;// TIH save this to put it back after a sell (due to reset, baaaaaaad)
		//UpdateShipScroll();// refresh the listing
		//nCurSScrollNum = PRIORnCurSScrollNum;// TIH reset
	}
	// TIH <--

	DeleteAttribute(chref,"ship.sails");
	DeleteAttribute(chref,"ship.blots");
	chref.ship.type = SHIP_NOTUSED_TYPE_NAME; // PS
	chref.ship.idx = SHIP_NOTUSED; // PS for lookup
	DeleteAttribute(chref,"ship.stats"); // PRS3
//KB - Tuning ships - deleting tune attribute
	aref temparef;
	makearef(temparef,chref.ship);
	if (CheckAttribute(temparef,"tune")) { DeleteAttribute(chref,"ship.tune"); }
// KB <---
	if ( CheckAttribute(chref,"ship.acquired") ) DeleteAttribute(chref,"ship.acquired");// TIH to remove this tag from the ship Jul27'06
	if ( cargoHandler == "includecargo" ) { // TIH added handler Jul27'06
		// Viper - Add Cargo Value to Ship Price --> 
		int p, tQuantity;	ref refStore;
		ref refCharacter = GetCharacter(cn);
		int curStoreIdx = GetCharacterCurrentStore(GetMainCharacter());
		makeref (refStore, Stores[curStoreIdx]);
		//p = 0; // NK
		for(int i=0;i<GOODS_QUANTITY;i++)
		{
			if( !GetStoreGoodsUsed(refStore,i) ) { continue; }
			tQuantity = GetCargoGoods(refCharacter,i);
			if( tQuantity==0 ) { continue; }
			RemoveCharacterGoods(refCharacter,i,tQuantity);
			// NK -->
			//p += GetGoodPriceByType(&refStore, GetMainCharacter(), i, tQuantity, PRICE_TYPE_SELL);
			SetStoreGoods(refStore,i,GetStoreGoodsQuantity(refStore,i)+tQuantity);
		}
		
	}
	gprice[nCurFourNum] = -1;
}

/* depreciated Jul27'06
void DoSellShip2()
{
	int cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
	if(cn<0) return;
	ref chref = GetCharacter(cn);
	int sellPrice = GetSellPrice2(nCurFourNum);

	AddMoneyToCharacter(GetMainCharacter(),sellPrice);
	// NK -->
	nStoreMoney -= sellPrice;
	GameInterface.strings.Money = MakeMoneyShow(sti(Characters[GetMainCharacterIndex()].money),MONEY_SIGN,MONEY_DELIVER);
	GameInterface.strings.SMoney = MakeMoneyShow(nStoreMoney,MONEY_SIGN,MONEY_DELIVER);
	gprice[nCurFourNum] = -1;
	// NK <--
	DeleteAttribute(chref,"ship.sails");
	DeleteAttribute(chref,"ship.blots");
	chref.ship.type = SHIP_NOTUSED_TYPE_NAME; // PS
	chref.ship.idx = SHIP_NOTUSED; // PS for lookup
	DeleteAttribute(chref,"ship.stats"); // PRS3
//KB - Tuning ships - deleting tune attribute
	aref temparef;
	makearef(temparef,chref.ship);
	if (CheckAttribute(temparef,"tune")) { DeleteAttribute(chref,"ship.tune"); }
// KB <---
}
*/

void DoBuyShip()
{
	int cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
	if(cn<0) return;

	//int money = sti(Characters[GetMainCharacterIndex()].money);	// TIH not needed when checks below are done properly Jul27'06
	//int sellPrice = GetSellPrice(nCurFourNum,"skipcargo");		// TIH not needed when checks below are done properly Jul27'06
	int st = GetScrollShipType(nCurSScrollNum); // PRS3 moved this line here

	/* TIH --> fixed price bug Jul27'06
	// changed by MAXIMUS [possibility to repair your ship by double price] -->
	int buyPrice;
	if(tradeHigh==true) buyPrice = GetShipPriceByType(st)*2;
	else 				buyPrice = GetShipPriceByType(st);
	// changed by MAXIMUS [possibility to repair your ship by double price] <--
	*/ // CORRECT:
	int buyPrice = GetBuyPrice(nCurSScrollNum);
	// TIH <--

	/* TIH --> fixed checks bug Jul27'06
	if(money+sellPrice < buyPrice) return;
	if(nStoreMoney + buyPrice < sellPrice) return; // NK
	*/ // CORRECT:
	if ( !IsMoneyForBuyEnable() ) return;
	// TIH <--

	DoSellShip("keepcrew","keepcargo");// TIH keep any stuff around as we only swap ships (or add ship to companion) Jul27'06

	AddMoneyToCharacter(GetMainCharacter(),-buyPrice);
	//MAXIMUS -->
	if(AUTO_SKILL_SYSTEM)
	{
		AddPartyExpChar(GetMainCharacter(), "Commerce", makeint(buyPrice/sti(1000/GetExpDivider())));
		AddCharacterExpNSChar(shipwright, "Commerce", makeint(buyPrice/sti(1000/GetExpDivider())));
	}
	//MAXIMUS <--
  	// NK -->
  	nStoreMoney += buyPrice;
	GameInterface.strings.Money = MakeMoneyShow(sti(Characters[GetMainCharacterIndex()].money),MONEY_SIGN,MONEY_DELIVER);
	GameInterface.strings.SMoney = MakeMoneyShow(nStoreMoney,MONEY_SIGN,MONEY_DELIVER);
	// NK <--

	ref chref = GetCharacter(cn);
	if(st==SHIP_NOTUSED) return;

	ref brefShip = GetShipByType(st);

	chref.ship.type = GetShipID(st); // PS
	chref.ship.idx = st; // PS for lookup
	// PRS3 -->
	makearef(arCurShip, chref.ship);
	arCurShip.stats = "";
	//yes I know this is bloated. I just want to be sure it works.
	aref sto; makearef(sto, arCurShip.stats);
	aref stmp = GetScrollShipAttr(nCurSScrollNum);
	aref sfrom; makearef(sfrom, stmp.stats);
	CopyAttributes(sto, sfrom); //copy stats tree over
	// PRS3 <--
//KB - Tuning ships - copy tune tree over
	if (CheckAttribute(stmp,"tune") ) { 
		arCurShip.tune = "";
		makearef(sto, arCurShip.tune);
		makearef(sfrom, stmp.tune);
		CopyAttributes(sto, sfrom);	
	}
// KB <---

	DeleteAttribute(chref,"ship.sails");
	DeleteAttribute(chref,"ship.blots");
	DeleteAttribute(chref,"ship.masts"); // NK
	chref.ship.sp = GetLocalShipAttrib(arCurShip, brefShip,"SP"); // PRS3
	chref.ship.hp = GetLocalShipAttrib(arCurShip, brefShip,"HP"); // PRS3
	chref.ship.acquired = "bought"; // TIH tag on how they acquired this ship (rpgstyle shipyard) Jul27'06
	DeleteAttribute(chref, "ship.cannons"); // delete cannons property to clear destroyable cannon state. 05-08-01
	if(USE_REAL_CANNONS) 	chref.ship.Cannons.Type = CANNON_TYPE_LONG_LBS4; // KNB
	else 					chref.ship.Cannons.Type = CANNON_TYPE_CANNON_LBS12; // NK

	// TIH --> sy_rpg_style ship removal Jul27'06
	if ( SY_RPG_STYLE ) {
		// since player bought the ship, remove it from shipyard listing
		string boughtSlot = GetAttributeName( GetAttributeN( arShipList, nCurSScrollNum ) );
		trace("SY buy ship, idx: "+ stmp +" slot: "+ boughtSlot);
		DeleteAttribute( arShipList, (boughtSlot) );
	}
	// TIH <--

}

void UpdateFourImages()
{
/*	DeleteAttribute(&GameInterface,"FourImage");
	GameInterface.FourImage.current = nCurFourNum;
    FillFourImages();
	SendMessage(&GameInterface,"lsl", MSG_INTERFACE_FOURIMAGE_CHANGE, "SHIPSLIST", -1);
*/
	ref refMainCh = GetMainCharacter();

	int i,cn,tmpShipType;
	string tmp1,tmp2,tmpStr;

    for(i=0; i<4; i++)
    {
		tmpStr = "pic"+(i+1);
		DeleteAttribute(&GameInterface,"FourImage."+tmpStr);

		tmpShipType = SHIP_NOTUSED;
		cn = GetCompanionIndex(refMainCh,i);
		if(cn!=-1)	tmpShipType = GetCharacterShipType(GetCharacter(cn));
		GameInterface.FourImage.(tmpStr).selected = cn!=-1 || nAllPassngerQuantity>0;

		if(tmpShipType==SHIP_NOTUSED)
		{
			if(cn>=0)
			{
				GameInterface.FourImage.(tmpStr).img1 = GetFacePicName(GetCharacter(cn));
				GameInterface.FourImage.(tmpStr).tex1 = FindFaceGroupNum("FourImage.ImagesGroup","FACE128_"+Characters[cn].FaceID);
				continue;
			}
			tmp1="";
			tmp2="";
		}
		else
		{
			ref baseShip = &ShipsTypes[tmpShipType];
			//tmp1 = baseShip.Class;
			//tmp2 = baseShip.SName; // PS
			// PRS3 -->
			makearef(arCurShip, Characters[cn].ship);
			tmp1 = GetLocalShipAttrib(arCurShip, baseShip, "Class");
			tmp2 = GetLocalShipAttrib(arCurShip, baseShip, "SName");
			// PRS3 <--
		}

		GameInterface.FourImage.(tmpStr).img1		= "ship back";
		GameInterface.FourImage.(tmpStr).img2		= GetShipPicName(tmpShipType); // PS
		GameInterface.FourImage.(tmpStr).str1		= "#"+tmp1;
		GameInterface.FourImage.(tmpStr).str2		= GetShipString(tmpShipType); //PS tempfix XI_ConvertString(tmp2);;
		GameInterface.FourImage.(tmpStr).tex1		= 0;
		GameInterface.FourImage.(tmpStr).tex2		= 1+GetShipTexture(tmpShipType); // PS
    }

	SendMessage(&GameInterface,"lsl", MSG_INTERFACE_FOURIMAGE_CHANGE, "SHIPSLIST", -1);
}

void UpdateShipScroll()
{
	DeleteAttribute(&GameInterface,"scrollitems");
	GameInterface.scrollitems.current = nCurSScrollNum;
    FillSScroll();
    SendMessage(&GameInterface,"lsl",MSG_INTERFACE_SCROLL_CHANGE,"SCROLLITEMS",-1);
}

void UpdateFaceScroll()
{
	nCurFScrollNum = -1;// TIH bugfix
	GameInterface.passengers.current = 0;// TIH bugfix
	// Delete old attributes
	int charQuantity = sti(GameInterface.passengers.ListSize);
	for(int i=0; i<charQuantity; i++)
	{
		attributeName = "passengers.pic" + (i+1);
		DeleteAttribute(&GameInterface, attributeName);
	}

	ref charRef;
	string attributeName;
	nAllPassngerQuantity = 0;
	int cn = GetPassengerFromScroll(0);
	while(cn>=0)
	{
		attributeName = "pic" + (nAllPassngerQuantity+1);
		charRef = GetCharacter(cn);
		GameInterface.passengers.(attributeName).img1 = GetFacePicName(charRef);
		GameInterface.passengers.(attributeName).tex1 = FindFaceGroupNum("passengers.ImagesGroup","FACE128_"+charRef.FaceID);
		nAllPassngerQuantity++;
		cn=GetPassengerFromScroll(nAllPassngerQuantity);
	}
	GameInterface.passengers.ListSize = nAllPassngerQuantity;
	//if( nCurSScrollNum >= nAllPassngerQuantity ) nCurSScrollNum = nAllPassngerQuantity;// TIH bugfix
	SendMessage(&GameInterface,"lsl",MSG_INTERFACE_SCROLL_CHANGE,"PASSENGERS",-1);
}

void UpdateCompanionCharacter()
{
	int cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
	int nn = GetPassengerFromScroll(nCurFScrollNum);
	if(nn==cn) return;
	if(nn>=0 && GetRemovable(GetCharacter(nn))==false) return;

	if(nn<0)	{DoSellShip("firecrew","includecargo");}// TIH added handlers Jul27'06

	if( nn>=0 && cn>=0 )	ExchangeCharacterShip(GetCharacter(nn),GetCharacter(cn));

	if(nn>=0) RemovePassenger(GetMainCharacter(),GetCharacter(nn));
	SetCompanionIndex(GetMainCharacter(),nCurFourNum,nn);
	makearef(arCurShip, Characters[nn].ship); // PRS3
	// NK get back officers 05-04-18 -->
	if(cn>=0)
	{
		AddPassenger(GetMainCharacter(),GetCharacter(cn),false);
		int on;
		for(int i = 1; i < 4; i++)
		{
			on = SetOfficersIndex(GetCharacter(cn),i,-1);	// TIH remove the officer from the old captain, otherwise doubles get made
			if(on != -1) AddPassenger(GetMainCharacter(), GetCharacter(on), false);
		}
	}
	// NK <--

	UpdateFaceScroll();
	UpdateFourImages();
	UpdateShipScroll();// TIH update
}

void FireCaptain()
{
	int cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
	if(cn<0) return;
	// NK get back officers 05-04-18 -->
	int on;
	for(int i = 1; i < 4; i++)
	{
		on = SetOfficersIndex(GetCharacter(cn),i,-1);	// TIH remove the officer from the old captain, otherwise doubles get made
		if(on != -1) AddPassenger(GetMainCharacter(), GetCharacter(on), false);
	}
	// NK <--
	DoSellShip("firecrew","includecargo");// TIH added handlers Jul27'06

	SetCompanionIndex(GetMainCharacter(),nCurFourNum,-1);
	AddPassenger(GetMainCharacter(),GetCharacter(cn),false);

	UpdateFaceScroll();
	UpdateFourImages();
	UpdateShipScroll();// TIH update
}

void DoShipParametersClamp()
{
	ref mchref = GetMainCharacter();
	ref chref;
	int i,cn,st,pq;

	for(i=0; i<4; i++)
	{
		cn = GetCompanionIndex(mchref,i);
		if(cn>=0)
		{
			chref = GetCharacter(cn);
			st = GetCharacterShipType(chref);
			if(st==SHIP_NOTUSED)
			{
				ClampShipToEmpty(chref);
				if(i>0)
				{
					//JA22Nov06 remove companions officers -->
					int on;
					for(int j = 1; j < 4; j++)
						{
							on = SetOfficersIndex(chref,j,-1);
							if(on != -1) AddPassenger(mchref, GetCharacter(on), false);
						}
						// <-- JA
					SetCompanionIndex(mchref,i,-1);
					AddPassenger(mchref,chref,false);
				}
			}
			else {
				ClampShipToType(chref);
			}
		}
	}

	pq = GetPassengersQuantity(mchref);
	for(i=0; i<pq; i++)
	{
		cn = GetPassenger(mchref,i);
		if(cn>=0) {
			ClampShipToEmpty(GetCharacter(cn));
		}
	}
}

void ClampShipToEmpty(ref chref)
{
	string sname = "";
	if(CheckAttribute(chref,"ship.name")) {
		sname = chref.ship.name;
	}
	if( sti(chref.index)==GetMainCharacterIndex() )
	{
		if( CheckAttribute(chref,"location.from_sea") ) {
			if( !CheckAttribute(chref,"location.old_from_sea") ) {
				chref.location.old_from_sea = chref.location.from_sea;
			}
			chref.location.from_sea = "";
			SetFleetInTown(GetTownIDFromLocID(chref.location.from_sea), "pchar"); // NK 05-04-02 WM/IT set fleet.
		}
	}
	DeleteAttribute(chref,"ship");
	chref.ship.type = SHIP_NOTUSED_TYPE_NAME; // PS
	chref.ship.idx = SHIP_NOTUSED; // PS
	if(sname=="") {
		SetRandomNameToShip(chref);
	}
	else {
		chref.ship.name = sname;
	}
}

void ClampShipToType(ref chref)
{
	int tmpLangFileID = LanguageOpenFile("interface_strings.txt");
	int i;
	int st = GetCharacterShipType(chref);
	ref base_ship = GetShipByType(st);
	aref arship; makearef(arship, chref.ship); // PRS3
	int mcrew = sti(GetLocalShipAttrib(arship, base_ship,"MaxCrew")); // PRS3

	if(GetCrewQuantity(chref)>mcrew)
	{		
		SetTownCrewQuantity(sTownName, GetTownCrewQuantity(sTownName) + (GetCrewQuantity(chref) - mcrew)); // NK 04-09-08 put crew in town
		chref.Ship.Crew.Quantity = mcrew;
	}

	if(!CheckAttribute(chref,"Ship.Name"))
	{
		SetRandomNameToShip(chref);
	}

	int gq[MAX_GOODS]; // NK
	string goods_id;

	chref.Ship.Pos.x = 0;
	chref.Ship.Pos.z = 0;
	chref.Ship.Ang = "";
	chref.Ship.Cannons.Borts = "";
	for(int ca = 0; ca < 4; ca++) { SetCannonArcQty(&chref, ca, GetCannonArcQty(&chref, ca)); } // NK cannon qty 05-04-18
	if(sti(chref.index) == GetMainCharacterIndex()) { chref.Ship.Cannons.Charge.Type = DEFAULT_CHARGE; }
	else { chref.Ship.Cannons.Charge.Type = GOOD_BALLS; } // NK 04-09-16 so player can choose default loadout
	if (!CheckAttribute(chref,"Ship.Cannons.Type")) { chref.Ship.Cannons.Type = MakeInt(base_ship.Cannon); }
	// NK 04-09-08 check town crew quantity -->
	if (!CheckAttribute(chref,"Ship.Crew.Morale"))	{ chref.Ship.Crew.Morale = GetTownCrewMorale(sTownName);	} 
	int tmpcrew = 1; if(AUTOHIRECREW_ONCHANGESHIP) tmpcrew = mcrew;
	// NK add cost 05-04-18 -->
	int hcrew = 0; 
	if(GetCrewQuantity(chref) < tmpcrew)
	{
		if(GetTownCrewQuantity(sTownName) >= mcrew - GetCrewQuantity(chref))
		{
			//SetTownCrewQuantity(sTownName, GetTownCrewQuantity(sTownName) - (mcrew - GetCrewQuantity(chref)));
			hcrew = mcrew - GetCrewQuantity(chref);
			
		}
		else
		{
			/*chref.Ship.Crew.Quantity += GetTownCrewQuantity(sTownName); // 04-10-25 OmegaRED
			SetTownCrewQuantity(sTownName, 0);*/
			hcrew = GetTownCrewQuantity(sTownName);
		}
		int ccost = GetCrewHireCost(GetMainCharacter());
		int pmoney = GetCharacterMoney(GetMainCharacter());
		if(hcrew * ccost > pmoney)
		{
			hcrew = pmoney / ccost;
		}
		AddMoneyToCharacter(GetMainCharacter(), -hcrew*ccost);		// this happens if you just LOOK at selling a ship LDH 26Nov06
		SetTownCrewQuantity(sTownName, GetTownCrewQuantity(sTownName) - hcrew);
		chref.Ship.Crew.Quantity = GetCrewQuantity(chref) + hcrew;
		// NK <--
	}
	// NK <--

	// loop through goods to see what existed in old ship
	for(i=0; i<GOODS_QUANTITY; i++)
	{
		if(!CheckAttribute(Goods[i],"name")) continue; // NK
		goods_id = Goods[i].name;
		if( CheckAttribute(chref,"Ship.Cargo.Goods."+goods_id) )
		{
			gq[i] = sti(chref.Ship.Cargo.Goods.(goods_id));
		}
		else
		{
			gq[i] = 0;
		}
		chref.Ship.Cargo.Goods.(goods_id) = 0;
	}
	chref.Ship.Cargo.Load = 0;

	// loop through all the goods of the old ship, to see if they fit in the new ship - sell what doesnt fit
	int minnumdaysrations = 10;
	for(i=0; i<GOODS_QUANTITY; i++)
	{
		int oldq, pricediff;
		int mcmoney = GetCharacterMoney(GetMainCharacter());
		ref cstore = &Stores[GetCharacterCurrentStore(GetMainCharacter())];
        if(FOOD_ON == 1 && i == GOOD_WHEAT && gq[i] < makeint(sti(chref.ship.crew.quantity) * FOOD_PER_CREW * minnumdaysrations))
		{
			oldq = gq[i];
			gq[i] = makeint(sti(chref.ship.crew.quantity) * FOOD_PER_CREW * minnumdaysrations); // 10 days worth of food in case of need.
			pricediff = GetGoodPriceByType(&cstore, GetMainCharacter(), i, gq[i] - oldq, PRICE_TYPE_BUY);
			// TIH --> fixed this so it doesn't plumment the player into debt ! Jul27'06
			if(mcmoney > pricediff)
			{
				AddStoreGoods(&cstore, i, -1 * (gq[i] - oldq));
				nStoreMoney += pricediff;
				AddMoneyToCharacter(GetMainCharacter(), -pricediff);
				//MAXIMUS -->
				if(AUTO_SKILL_SYSTEM)
				{
					AddPartyExpChar(GetMainCharacter(), "Commerce", makeint(pricediff/sti(1000/GetExpDivider())));
				}
				//MAXIMUS <--
				Log_SetStringToLog(LanguageConvertString(tmpLangFileID,"Not enough food! Your purser makes an emergency purchase of") + " " + (gq[i]-oldq) + " " + LanguageConvertString(tmpLangFileID,"days' rations for the crew of the") + " " + chref.ship.name + " " + LanguageConvertString(tmpLangFileID,"for a cost of") + " " + pricediff + " " + LanguageConvertString(tmpLangFileID,"Gold") + ".");
			}
			else
			{
				gq[i] = oldq;
				Log_SetStringToLog(LanguageConvertString(tmpLangFileID,"You are low on food! Purser could not buy more because you are low on money!"));
			}
			// TIH <--
		}
		Fantom_SetCharacterGoods(chref, i, gq[i]); // changed from SetCharacterGoods() to this by NK 05-08-01
		// Do check
		oldq = GetCargoGoods(&chref, i);
    	// --> Swindler 05-10-16: only make emergency pursue when FOOD_ON
    	// TIH --> why on earth FOR??? changed this so it sells ANY over quantity good!!! grrrr Jul27'06
        //if(FOOD_ON == 1 && oldq < gq[i]) {
        if(oldq < gq[i]) {
			// sold some
			pricediff = GetGoodPriceByType(&cstore, GetMainCharacter(), i, gq[i] - oldq, PRICE_TYPE_SELL);
			AddStoreGoods(&cstore, i, gq[i] - oldq);
			nStoreMoney -= pricediff;
			AddMoneyToCharacter(GetMainCharacter(), pricediff);
			//MAXIMUS -->
			if(AUTO_SKILL_SYSTEM)
			{
				AddPartyExpChar(GetMainCharacter(), "Commerce", makeint(pricediff/sti(1000/GetExpDivider())));
			}
			//MAXIMUS <--
			Log_SetStringToLog(LanguageConvertString(tmpLangFileID,"Too little room! Your purser makes an emergency sale of") + " " + (gq[i]-oldq) + " " + LanguageConvertString(tmpLangFileID,"units of") + " " + XI_ConvertString(Goods[i].Name) + " " + LanguageConvertString(tmpLangFileID,"from the") + " " + chref.ship.name + " " + LanguageConvertString(tmpLangFileID,"for a total of") + " " + pricediff + " " + LanguageConvertString(tmpLangFileID,"Gold") + ".");
		}
	}

	if( sti(chref.index)==GetMainCharacterIndex() )
	{
		if( CheckAttribute(chref,"location.old_from_sea") ) {
			chref.location.from_sea = chref.location.old_from_sea;
			SetFleetInTown(GetTownIDFromLocID(chref.location.from_sea), "pchar"); // NK 05-04-02 WM/IT set fleet.
			DeleteAttribute(chref,"location.old_from_sea");
		}
	}
	LanguageCloseFile(tmpLangFileID);
}

void DoSailRepairToPercent(ref chref,int toPerc)
{
	ref mchref = GetMainCharacter();

	int cursp = MakeInt(GetSailPercent(chref));
	if(cursp>=toPerc) return;

	makearef(arCurShip, chref.ship); // PRS3

	// TIH --> proper way to handle this Jul27'06
	int sailRepairCost = GetSailRepairCost(chref, toPerc-cursp); // KK
	/* prior broken method
	// changed by MAXIMUS [possibility to repair your ship by double price] -->
	int sailRepairCost;
	if(tradeHigh==true) sailRepairCost = GetSailRepairCost(GetCharacterShipType(chref),toPerc-cursp)*2;
	else 				sailRepairCost = GetSailRepairCost(GetCharacterShipType(chref),toPerc-cursp);
	// changed by MAXIMUS [possibility to repair your ship by double price] <--
	*/
	// TIH <--

	int nMyMoney = GetMyMoney();
	while(nMyMoney<sailRepairCost)
	{
		toPerc--;
		if(cursp>=toPerc) return;
		sailRepairCost = GetSailRepairCost(chref, toPerc-cursp); // KK
	}

	AddMoneyToCharacter(mchref,-sailRepairCost);

	// ccc feb05 shipyard waiting
	if(REALREPAIR==1)
	{
		daystowait += 1+makeint(sqrt(sailRepairCost/1000)); // NK - WaitDate("", 0,0, 1+makeint(sqrt(sailRepairCost/1000)),0,0);
		/*PlaySound("ambient\shipyard\axe.wav");	//just earcandy :)
		PlaySound("ambient\shipyard\vehicle.wav"); 
		Log_SetStringToLog("You get your ship back several days later.");*/
	}
	// ccc end

	// NK -->
	nStoreMoney += sailRepairCost;
	GameInterface.strings.Money = MakeMoneyShow(GetMyMoney(),MONEY_SIGN,MONEY_DELIVER);
	GameInterface.strings.SMoney = MakeMoneyShow(nStoreMoney,MONEY_SIGN,MONEY_DELIVER);
	// NK <--

	if(toPerc>=100)
	{
		chref.ship.sp = GetCharacterShipSP(chref);
		DeleteAttribute(chref,"ship.sails");
		DeleteAttribute(chref,"ship.masts");
		return;
	}

	float fsail = MakeFloat(toPerc) - GetSailPercent(chref);
	ProcessSailRepair(chref,fsail);
	chref.ship.sp = CalculateShipSP(chref);
	if(AUTO_SKILL_SYSTEM) { if(!CheckAttribute(GetMainCharacter(),"gained_repair_sail")) { AddPartyExpChar(GetMainCharacter(), "Repair", makeint(sailRepairCost/100)); characters[GetMainCharacterIndex()].gained_repair_sail = sailRepairCost; } }
}

void DoHullRepairToPercent(ref chref,int toPerc)
{
	ref mchref = GetMainCharacter();

	int curhp = MakeInt(GetHullPercent(chref));
	if(curhp>=toPerc) return;
	makearef(arCurShip, chref.ship); // PRS3

	// TIH --> proper way to handle this Jul27'06
	int hullRepairCost = GetHullRepairCost(chref, toPerc-curhp); // KK
	/* prior broken method
	// changed by MAXIMUS [possibility to repair your ship by double price] -->
	int hullRepairCost;
	if(tradeHigh==true) hullRepairCost = GetHullRepairCost(GetCharacterShipType(chref),toPerc-curhp)*2;
	else 				hullRepairCost = GetHullRepairCost(GetCharacterShipType(chref),toPerc-curhp);
	// changed by MAXIMUS [possibility to repair your ship by double price] <--
	*/
	// TIH <--

	int nMyMoney = GetMyMoney();
	while(nMyMoney<hullRepairCost)
	{
		toPerc--;
		if(curhp>=toPerc) return;
		hullRepairCost = GetHullRepairCost(chref, toPerc-curhp); // KK
	}

	AddMoneyToCharacter(mchref,-hullRepairCost);

	// ccc feb05 shipyard waiting
	if(REALREPAIR==1)
	{
		daystowait += 1+makeint(sqrt(hullRepairCost/1000)); // NK - WaitDate("", 0,0, 1+makeint(sqrt(hullRepairCost/1000)),0,0);
		/*PlaySound("ambient\shipyard\axe.wav");	//just earcandy :)
		PlaySound("ambient\shipyard\vehicle.wav"); 
		Log_SetStringToLog("You get your ship back several days later.");*/
	}
	// ccc end

	// NK -->
	nStoreMoney += hullRepairCost;
	GameInterface.strings.Money = MakeMoneyShow(GetMyMoney(),MONEY_SIGN,MONEY_DELIVER);
	GameInterface.strings.SMoney = MakeMoneyShow(nStoreMoney,MONEY_SIGN,MONEY_DELIVER);
	// NK <--

	if(toPerc==100)
	{
		chref.ship.hp = GetCharacterShipHP(chref);
		DeleteAttribute(chref,"ship.blots");
		return;
	}

	float fhull = MakeFloat(toPerc) - GetHullPercent(chref);
	ProcessHullRepair(chref,fhull);
	chref.ship.hp = GetCharacterShipHP(chref)*toPerc/100.0+0.01;
	if(AUTO_SKILL_SYSTEM)
	{
		if(!CheckAttribute(GetMainCharacter(),"gained_repair_hull"))
		{
			AddPartyExpChar(GetMainCharacter(), "Repair", makeint(hullRepairCost/100));
			AddPartyExpChar(GetMainCharacter(), "Defence", makeint(hullRepairCost/100));
			characters[GetMainCharacterIndex()].gained_repair_hull = hullRepairCost;
		}
	}
}

// LDH --> 27Sep06
void DoCannonRepair(ref chref)
{
	int cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
	int gunRepairCost = 0;
	if (cn>=0) gunRepairCost = (GetCannonMaxQuantity(chref) - GetCannonQuantity(chref)) * GetCannonPrice(sti(chref.ship.cannons.type));
	if (gunRepairCost == 0) return;
	if (tradeHigh) gunRepairCost *= 2;
	if (LAi_IsCapturedLocation) gunRepairCost = 0; // KK
	if (GetMyMoney() >= gunRepairCost) // KK
	{
		RepairAllCannons(chref);	
		ResetCannons(chref);
		AddMoneyToCharacter(GetMainCharacter(),-gunRepairCost);
		nStoreMoney += gunRepairCost;
		GameInterface.strings.Money = MakeMoneyShow(GetMyMoney(),MONEY_SIGN,MONEY_DELIVER);
		GameInterface.strings.SMoney = MakeMoneyShow(nStoreMoney,MONEY_SIGN,MONEY_DELIVER);
		if(AUTO_SKILL_SYSTEM) { if(!CheckAttribute(GetMainCharacter(),"gained_repair_cannon")) { AddPartyExpChar(GetMainCharacter(), "Repair", makeint(gunRepairCost/100)); characters[GetMainCharacterIndex()].gained_repair_cannon = gunRepairCost; } }
	}
}
// LDH <--

void ChangeHullRepair(int delta)
{
	int cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
	if(cn<0) return;
	makearef(arCurShip, Characters[cn].ship); // PRS3

	int newHP = nhpRepair + delta;
	if(newHP>100)
	{
		newHP = 100;
	}

	int curHP = MakeInt(GetHullPercent(GetCharacter(cn)));
	if(newHP<curHP)
	{
		newHP = curHP;
	}

	// TIH --> proper way to handle this Jul27'06
	int price = GetHullRepairCost(GetCharacter(cn), newHP-curHP); // KK
	/* prior broken method
	// changed by MAXIMUS [possibility to repair your ship by double price] -->
	int price;
	if(tradeHigh==true) price = GetHullRepairCost(GetCharacter(cn),newHP-curHP)*2;
	else 				price = GetHullRepairCost(GetCharacter(cn),newHP-curHP);
	// changed by MAXIMUS [possibility to repair your ship by double price] <--
	*/
	// TIH <--

	while(GetMyMoney()<price)
	{
		newHP--;
		price = GetHullRepairCost(GetCharacter(cn), newHP-curHP); // KK
	}

	if(newHP==nhpRepair) return;
	nhpRepair = newHP;

    GameInterface.strings.HullPercent = nhpRepair + "%";
    GameInterface.strings.RepairHullCost = MakeMoneyShow(price,MONEY_SIGN,MONEY_DELIVER); // NK
}

void ChangeSailRepair(int delta)
{
	int cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
	if(cn<0) return;
	makearef(arCurShip, Characters[cn].ship); // PRS3

	int newSP = nspRepair + delta;
	if(newSP>100)
	{
		newSP = 100;
	}

	int curSP = MakeInt(GetSailPercent(GetCharacter(cn)));
	if(newSP<curSP)
	{
		newSP = curSP;
	}

	// TIH --> proper way to handle this Jul27'06
	int price = GetSailRepairCost(GetCharacter(cn), newSP-curSP); // KK
	/* prior broken method
	// changed by MAXIMUS [possibility to repair your ship by double price] -->
	int price;
	if(tradeHigh==true) price = GetSailRepairCost(GetCharacter(cn),newSP-curSP)*2;
	else 				price = GetSailRepairCost(GetCharacter(cn),newSP-curSP);
	// changed by MAXIMUS [possibility to repair your ship by double price] <--
	*/
	// TIH <--

	while(GetMyMoney()<price)
	{
		newSP--;
		price = GetSailRepairCost(GetCharacter(cn), newSP-curSP); // KK
	}

	if(newSP==nspRepair) return;
	nspRepair = newSP;

    GameInterface.strings.SailsPercent = nspRepair + "%";
    GameInterface.strings.RepairSailsCost = MakeMoneyShow(price,MONEY_SIGN,MONEY_DELIVER); // NK
}

void EnableChooseButtons()
{
	SetNodeUsing( "BUY_BUTTON", IsEnableBuyShip() ); // KK
	SetSelectable( "BUY_BUTTON", IsEnableBuyShip() );
	SetSelectable( "REPAIR_BUTTON", IsEnableRepairShip() );
	SetSelectable( "SELLSHIP_BUTTON", IsEnableSellShip() );
	SetSelectable( "CHANGE_CAPTAIN", IsEnableChangeCaptain() );
}

string GetNextChoose(string curChoose, bool bUpDirection)
{
	switch(curChoose)
	{
	case "BUY_BUTTON":
		if(bUpDirection)	{return "";}
		else	{return "REPAIR_BUTTON";}
	break;
	case "REPAIR_BUTTON":
		if(bUpDirection)	{return "BUY_BUTTON";}
		else	{return "SELLSHIP_BUTTON";}
	break;
	case "SELLSHIP_BUTTON":
		if(bUpDirection)	{return "REPAIR_BUTTON";}
		else	{return "CHANGE_CAPTAIN";}
	break;
	case "CHANGE_CAPTAIN":
		if(bUpDirection)	{return "SELLSHIP_BUTTON";}
		else	{return "";}
	break;
	}
}

void ChooseButtonTopSelect()
{
	string nextNode = "BUY_BUTTON";
	while(nextNode!="")
	{
		if( GetSelectable(nextNode) )
		{
			SetCurrentNode(nextNode);
			return;
		}
		nextNode = GetNextChoose(nextNode, false);
	}
}

void ChooseButtonNextSelect(string chooseBtnName, bool bUpDirection)
{
	string nextNode = GetNextChoose(chooseBtnName, bUpDirection);
	while(nextNode!="")
	{
		if( GetSelectable(nextNode) )
		{
			SetCurrentNode(nextNode);
			return;
		}
		nextNode = GetNextChoose(nextNode, bUpDirection);
	}
}

bool IsEnableBuyShip()
{
	int cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
	if(cn<0) return false;
	ref chref = GetCharacter(cn);
	if( !GetRemovable(chref) ) return false;

	// TIH --> sy_rpg_style cannot buy outclassed ships Jul27'06
	if ( SY_RPG_STYLE ) {
		//int mcL = GetLevel(GetMainCharacter());
		//int allowedClass = iclamp(1,7 , makeint( 7 - roundup(mcL / SHIPYARD_RPG_LPC) ));
		// for every SHIPYARD_RPG_LPC levels, they gain access to next class (7 is always available)
		//if ( sti(GetLocalShipAttrib(arCurShip, ShipsTypes[st],"Class")) < allowedClass ) {
		//	return false;
		//}
		string attributeName = "pic" + (nCurSScrollNum+1);
		if ( CheckAttribute(GameInterface,"scrollitems."+(attributeName)+".skipsell") ) {
			if ( GameInterface.scrollitems.(attributeName).skipsell==true ) return false;
		}
	}
	// TIH <--
	return GetShipRemovable(chref);
}

bool IsEnableSellShip()
{
	int cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
	if(cn<0) return false;
	ref chref = GetCharacter(cn);
	if( GetCharacterShipType(chref)==SHIP_NOTUSED ) return false;
	if( !GetRemovable(chref) ) return false;

	return GetShipRemovable(chref);
}

bool IsEnableRepairShip()
{
	int cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
	if(cn<0) return false;
	ref chref = GetCharacter(cn);
	if( GetCharacterShipType(chref)==SHIP_NOTUSED ) return false;
	// LDH --> 27Sep06
	int gcost = 0;
	if (cn>=0) gcost = (GetCannonMaxQuantity(chref) - GetCannonQuantity(chref)) * GetCannonPrice(sti(chref.ship.cannons.type));
	if (tradeHigh) gcost *= 2;
	// LDH <--

	if( GetCharacterShipType(chref)==SHIP_NOTUSED ) return false;
	if( GetSailPercent(chref)>=100.0 && GetHullPercent(chref)>=100.0 && gcost==0 ) return false; // LDH 27Sep06
	return true;
}

bool IsEnableChangeCaptain()
{
	if(nCurFourNum<1) return false;
	int cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
	if(cn>=0)
	{
		ref chref = GetCharacter(cn);
		if( !GetRemovable(chref) ) return false;
	}
	return true;
}

bool IsMoneyForBuyEnable()
{
	int money 		= sti(Characters[GetMainCharacterIndex()].money);
	int sellPrice 	= GetSellPrice(nCurFourNum,"skipcargo"); // TIH added handler Jul27'06 // Viper - dont add Cargo Value to Ship Price
	//int st 		= GetScrollShipType(nCurSScrollNum); // PRS3 moved line here// TIH not needed anymore because we use proper check now Jul27'06
	int buyPrice 	= GetBuyPrice(nCurSScrollNum);//GetShipPriceByType(st);// TIH this wasn't using the proper check Jul27'06
	if(money + sellPrice < buyPrice) return false;
	if(nStoreMoney + buyPrice < sellPrice) return false;
	return true;
}

// NK -->
bool IsMoneyForSellEnable()
{
	//int st = GetScrollShipType(nCurSScrollNum);// TIH not needed Jul27'06
	int sellPrice = GetSellPrice(nCurFourNum,"includecargo"); // TIH added handler Jul27'06 // Viper - Add Cargo Value to Ship Price
	if(sellPrice > nStoreMoney) return false;
	return true;
}
// NK <--

void SetCaptainButtonsEnable()
{
	bool bRemoveEnable = true;
	bool bSetEnable = true;

	int cn = GetCompanionIndex(GetMainCharacter(),nCurFourNum);
	if(cn<0 || !GetRemovable(GetCharacter(cn)) )	bRemoveEnable = false;

	int nn = GetPassengerFromScroll(nCurFScrollNum);
	if(nn==cn)	bSetEnable = false;
	if( nn>=0 && !GetRemovable(GetCharacter(nn)) )	bSetEnable = false;
	if( nn<0 )	bSetEnable = false;

	SetSelectable("SKILLINFO_BUTTON", nChrIdxForInfo>=0);
	SetSelectable("REMOVEC_BUTTON", bRemoveEnable);
	SetSelectable("SETC_BUTTON", bSetEnable);
}

void SelectCaptainButton()
{
	if( GetSelectable("SKILLINFO_BUTTON") ) {SetCurrentNode("SKILLINFO_BUTTON");}
	else
	{
		if( GetSelectable("REMOVEC_BUTTON") ) {SetCurrentNode("REMOVEC_BUTTON");}
		else
		{
			if( GetSelectable("SETC_BUTTON") ) {SetCurrentNode("SETC_BUTTON");}
			else {SetCurrentNode("PASSENGERS");}
		}
	}
}

string GetNextCaptainButton(string curNode, bool bUpDirection)
{
	switch(curNode)
	{
	case "PASSENGERS":
		if(bUpDirection) {return "";}
		else {return "SKILLINFO_BUTTON";}
	break;

	case "SKILLINFO_BUTTON":
		if(bUpDirection) {return "PASSENGERS";}
		else {return "REMOVEC_BUTTON";}
	break;

	case "REMOVEC_BUTTON":
		if(bUpDirection) {return "SKILLINFO_BUTTON";}
		else {return "SETC_BUTTON";}
	break;

	case "SETC_BUTTON":
		if(bUpDirection) {return "REMOVEC_BUTTON";}
		else {return "";}
	break;
	}
	return "";
}

void SetNextCaptainButton(string curNode, bool bUpDirection)
{
	string nextNode = GetNextCaptainButton(curNode, bUpDirection);
	while(nextNode!="")
	{
		if( GetSelectable(nextNode) )
		{
			SetCurrentNode(nextNode);
			return;
		}
		nextNode = GetNextCaptainButton(nextNode, bUpDirection);
	}
	SetCurrentNode(curNode);
}

void SetSkillData()
{
	if(nChrIdxForInfo<0)
	{
		GameInterface.strings.CharacterName = "";
		GameInterface.strings.skillLeadership = "0";
		GameInterface.strings.skillFencing = "0";
		GameInterface.strings.skillSailing = "0";
		GameInterface.strings.skillAccuracy = "0";
		GameInterface.strings.skillCannons = "0";
		GameInterface.strings.skillGrappling = "0";
		GameInterface.strings.skillRepair = "0";
		GameInterface.strings.skillDefence = "0";
		GameInterface.strings.skillCommerce = "0";
		GameInterface.strings.skillSneak = "0";
		return;
	}
	ref chref = GetCharacter(nChrIdxForInfo);
	GameInterface.strings.CharacterName = GetCharacterFullName(chref.id) +" - " + XI_ConvertString("S"+chref.quest.officertype);
	GameInterface.strings.skillLeadership = GetCharacterSkill(chref,SKILL_LEADERSHIP);
	GameInterface.strings.skillFencing = GetCharacterSkill(chref,SKILL_FENCING);
	GameInterface.strings.skillSailing = GetCharacterSkill(chref,SKILL_SAILING);
	GameInterface.strings.skillAccuracy = GetCharacterSkill(chref,SKILL_ACCURACY);
	GameInterface.strings.skillCannons = GetCharacterSkill(chref,SKILL_CANNONS);
	GameInterface.strings.skillGrappling = GetCharacterSkill(chref,SKILL_GRAPPLING);
	GameInterface.strings.skillRepair = GetCharacterSkill(chref,SKILL_REPAIR);
	GameInterface.strings.skillDefence = GetCharacterSkill(chref,SKILL_DEFENCE);
	GameInterface.strings.skillCommerce = GetCharacterSkill(chref,SKILL_COMMERCE);
	GameInterface.strings.skillSneak = GetCharacterSkill(chref,SKILL_SNEAK);
}

void SetCharacterToInfoCharacter(int nInfoChrIdx)
{
	nChrIdxForInfo = nInfoChrIdx;
	if(nInfoChrIdx<0)
	{
		GameInterface.strings.CharacterName = "";
		return;
	}

	if(CheckAttribute(Characters[nInfoChrIdx],"quest.officertype")) GameInterface.strings.CharacterName = GetCharacterFullName(Characters[nInfoChrIdx].id) +" - " + XI_ConvertString("S"+Characters[nInfoChrIdx].quest.officertype);
	else GameInterface.strings.CharacterName = GetCharacterFullName(Characters[nInfoChrIdx].id) +" - " + XI_ConvertString("SComrade-In-Arms");
}
