function GetBankBalance() {
	local me = AICompany.ResolveCompanyID(AICompany.COMPANY_SELF);
	return AICompany.GetBankBalance(me);
}

function MayBuyTrain() {
	return (GetMaximumAmountCash() > 50000);
}
function MayExtendRailway() {
	return (GetMaximumAmountCash() > 30000);
}
function MayCreateNewRailway() {
	return (GetMaximumAmountCash() > 180000);
}
function MayCreateNewBusline() {
	return (GetMaximumAmountCash() > 30000);
}

function GetMaximumAmountCash() {
	return GetBankBalance() + AICompany.GetMaxLoanAmount() - AICompany.GetLoanAmount()
}

function RailwAI::DetermineLoan() {
	local bankBalance = GetBankBalance()
	local maxLoan = AICompany.GetMaxLoanAmount()
	if (bankBalance > maxLoan*2) {
		//Pay back loans
		AICompany.SetMinimumLoanAmount(0)
	} else {
		AICompany.SetLoanAmount(maxLoan)
	}
}

function RailwAI::MonthlyPayBack() {
	local bankBalance = GetBankBalance()
	if (bankBalance < 0) {
		AICompany.SetLoanAmount(AICompany.GetLoanAmount() + AICompany.GetLoanInterval())
	} else {
		AICompany.SetLoanAmount(AICompany.GetLoanAmount() - AICompany.GetLoanInterval())
	}
}

function GetFinancialBuffer() {
	//10.000 + 2 years of interest + 1000 per vehicle
	local buffer = 10000 + AICompany.GetLoanAmount()/25 + 1000 * AIVehicleList().Count()
	return buffer
}
function RailwAI::EnlargeFinancialBuffer() {
	//nothing
}

//maximize loan
function RailwAI::SetMaxLoan() {
	AICompany.SetLoanAmount(AICompany.GetMaxLoanAmount())
}

function IncreaseLoan() {
	AICompany.SetLoanAmount(AICompany.GetLoanAmount() + 4*AICompany.GetLoanInterval())
}

function RailwAI::SetMaxAllowedLoan() {
	AICompany.SetLoanAmount(AICompany.GetMaxLoanAmount() - (GetFinancialBuffer() / AICompany.GetLoanInterval()) * AICompany.GetLoanInterval())
}

function RailwAI::SetMinLoan() {
	while (GetBankBalance() > AICompany.GetLoanInterval() && AICompany.GetLoanAmount() > 0) {
		AICompany.SetLoanAmount(AICompany.GetLoanAmount() - AICompany.GetLoanInterval())
	}
	if (GetBankBalance() < 0) {
		AICompany.SetLoanAmount(AICompany.GetLoanAmount() + AICompany.GetLoanInterval())
	}
}