/*
 * This file is part of OpenTTD.
 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
 */

/** @file vehicle_cmd.cpp Commands for vehicles. */

#include "stdafx.h"
#include "roadveh.h"
#include "news_func.h"
#include "airport.h"
#include "command_func.h"
#include "company_func.h"
#include "train.h"
#include "aircraft.h"
#include "newgrf_text.h"
#include "vehicle_func.h"
#include "string_func.h"
#include "depot_map.h"
#include "vehiclelist.h"
#include "engine_func.h"
#include "articulated_vehicles.h"
#include "autoreplace_gui.h"
#include "group.h"
#include "order_backup.h"
#include "ship.h"
#include "newgrf.h"
#include "company_base.h"
#include "core/random_func.hpp"
#include "vehicle_cmd.h"
#include "aircraft_cmd.h"
#include "autoreplace_cmd.h"
#include "group_cmd.h"
#include "order_cmd.h"
#include "roadveh_cmd.h"
#include "train_cmd.h"
#include "ship_cmd.h"
#include <charconv>

#include "table/strings.h"

#include "safeguards.h"

/**
 * @name Tables used to find the right error message for a certain vehicle type.
 * @see vehicle_func.h
 * @{
 */
/** When can't buy such vehicle. */
VehicleTypeIndexArray<const StringID> _veh_build_msg_table = {
	STR_ERROR_CAN_T_BUY_TRAIN,
	STR_ERROR_CAN_T_BUY_ROAD_VEHICLE,
	STR_ERROR_CAN_T_BUY_SHIP,
	STR_ERROR_CAN_T_BUY_AIRCRAFT,
};

/** When can't sell such vehicle. */
VehicleTypeIndexArray<const StringID> _veh_sell_msg_table = {
	STR_ERROR_CAN_T_SELL_TRAIN,
	STR_ERROR_CAN_T_SELL_ROAD_VEHICLE,
	STR_ERROR_CAN_T_SELL_SHIP,
	STR_ERROR_CAN_T_SELL_AIRCRAFT,
};

/** When can't sell all vehicles in depot. */
VehicleTypeIndexArray<const StringID> _veh_sell_all_msg_table = {
	STR_ERROR_CAN_T_SELL_ALL_TRAIN,
	STR_ERROR_CAN_T_SELL_ALL_ROAD_VEHICLE,
	STR_ERROR_CAN_T_SELL_ALL_SHIP,
	STR_ERROR_CAN_T_SELL_ALL_AIRCRAFT,
};

/** When can't autoreplace such vehicle. */
VehicleTypeIndexArray<const StringID> _veh_autoreplace_msg_table = {
	STR_ERROR_CAN_T_AUTOREPLACE_TRAIN,
	STR_ERROR_CAN_T_AUTOREPLACE_ROAD_VEHICLE,
	STR_ERROR_CAN_T_AUTOREPLACE_SHIP,
	STR_ERROR_CAN_T_AUTOREPLACE_AIRCRAFT,
};

/** When can't refit such vehicle. */
VehicleTypeIndexArray<const StringID> _veh_refit_msg_table = {
	STR_ERROR_CAN_T_REFIT_TRAIN,
	STR_ERROR_CAN_T_REFIT_ROAD_VEHICLE,
	STR_ERROR_CAN_T_REFIT_SHIP,
	STR_ERROR_CAN_T_REFIT_AIRCRAFT,
};

/** When can't send to depot such vehicle. */
VehicleTypeIndexArray<const StringID> _send_to_depot_msg_table = {
	STR_ERROR_CAN_T_SEND_TRAIN_TO_DEPOT,
	STR_ERROR_CAN_T_SEND_ROAD_VEHICLE_TO_DEPOT,
	STR_ERROR_CAN_T_SEND_SHIP_TO_DEPOT,
	STR_ERROR_CAN_T_SEND_AIRCRAFT_TO_HANGAR,
};
/** @} */


/**
 * Build a vehicle.
 * @param flags for command
 * @param tile tile of depot where the vehicle is built
 * @param eid vehicle type being built.
 * @param use_free_vehicles use free vehicles when building the vehicle.
 * @param cargo refit cargo type.
 * @param client_id User
 * @return the cost of this operation + the new vehicle ID + the refitted capacity + the refitted mail capacity (aircraft) or an error
 */
std::tuple<CommandCost, VehicleID, uint, uint16_t, CargoArray> CmdBuildVehicle(DoCommandFlags flags, TileIndex tile, EngineID eid, bool use_free_vehicles, CargoType cargo, ClientID client_id)
{
	/* Elementary check for valid location. */
	if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return { CMD_ERROR, VehicleID::Invalid(), 0, 0, {} };

	VehicleType type = GetDepotVehicleType(tile);

	/* Validate the engine type. */
	if (!IsEngineBuildable(eid, type, _current_company)) return { CommandCost(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + to_underlying(type)), VehicleID::Invalid(), 0, 0, {} };

	/* Validate the cargo type. */
	if (cargo >= NUM_CARGO && IsValidCargoType(cargo)) return { CMD_ERROR, VehicleID::Invalid(), 0, 0, {} };

	const Engine *e = Engine::Get(eid);
	CommandCost value(ExpensesType::NewVehicles, e->GetCost());

	/* Engines without valid cargo should not be available */
	CargoType default_cargo = e->GetDefaultCargoType();
	if (!IsValidCargoType(default_cargo)) return { CMD_ERROR, VehicleID::Invalid(), 0, 0, {} };

	bool refitting = IsValidCargoType(cargo) && cargo != default_cargo;

	/* Check whether the number of vehicles we need to build can be built according to pool space. */
	uint num_vehicles;
	switch (type) {
		case VehicleType::Train:    num_vehicles = (e->VehInfo<RailVehicleInfo>().railveh_type == RailVehicleType::Multihead ? 2 : 1) + CountArticulatedParts(eid); break;
		case VehicleType::Road:     num_vehicles = 1 + CountArticulatedParts(eid); break;
		case VehicleType::Ship:     num_vehicles = 1; break;
		case VehicleType::Aircraft: num_vehicles = e->VehInfo<AircraftVehicleInfo>().subtype & AIR_CTOL ? 2 : 3; break;
		default: NOT_REACHED(); // Safe due to IsDepotTile()
	}
	if (!Vehicle::CanAllocateItem(num_vehicles)) return { CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME), VehicleID::Invalid(), 0, 0, {} };

	/* Check whether we can allocate a unit number. Autoreplace does not allocate
	 * an unit number as it will (always) reuse the one of the replaced vehicle
	 * and (train) wagons don't have an unit number in any scenario. */
	UnitID unit_num = (flags.Test(DoCommandFlag::QueryCost) || flags.Test(DoCommandFlag::AutoReplace) || (type == VehicleType::Train && e->VehInfo<RailVehicleInfo>().railveh_type == RailVehicleType::Wagon)) ? 0 : GetFreeUnitNumber(type);
	if (unit_num == UINT16_MAX) return { CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME), VehicleID::Invalid(), 0, 0, {} };

	/* If we are refitting we need to temporarily purchase the vehicle to be able to
	 * test it. */
	DoCommandFlags subflags = flags;
	if (refitting && !flags.Test(DoCommandFlag::Execute)) subflags.Set({DoCommandFlag::Execute, DoCommandFlag::AutoReplace});

	/* Vehicle construction needs random bits, so we have to save the random
	 * seeds to prevent desyncs. */
	SavedRandomSeeds saved_seeds;
	SaveRandomSeeds(&saved_seeds);

	Vehicle *v = nullptr;
	switch (type) {
		case VehicleType::Train:    value.AddCost(CmdBuildRailVehicle(subflags, tile, e, &v)); break;
		case VehicleType::Road:     value.AddCost(CmdBuildRoadVehicle(subflags, tile, e, &v)); break;
		case VehicleType::Ship:     value.AddCost(CmdBuildShip       (subflags, tile, e, &v)); break;
		case VehicleType::Aircraft: value.AddCost(CmdBuildAircraft   (subflags, tile, e, &v)); break;
		default: NOT_REACHED(); // Safe due to IsDepotTile()
	}

	VehicleID veh_id = VehicleID::Invalid();
	uint refitted_capacity = 0;
	uint16_t refitted_mail_capacity = 0;
	CargoArray cargo_capacities{};
	if (value.Succeeded()) {
		if (subflags.Test(DoCommandFlag::Execute)) {
			v->unitnumber = unit_num;
			v->value      = value.GetCost();
			veh_id        = v->index;
		}

		if (refitting) {
			/* Refit only one vehicle. If we purchased an engine, it may have gained free wagons. */
			CommandCost cc;
			std::tie(cc, refitted_capacity, refitted_mail_capacity, cargo_capacities) = CmdRefitVehicle(flags, v->index, cargo, 0, false, false, 1);
			value.AddCost(std::move(cc));
		} else {
			/* Fill in non-refitted capacities */
			if (e->type == VehicleType::Train || e->type == VehicleType::Road) {
				cargo_capacities = GetCapacityOfArticulatedParts(eid);
				refitted_capacity = cargo_capacities[default_cargo];
				refitted_mail_capacity = 0;
			} else {
				refitted_capacity = e->GetDisplayDefaultCapacity(&refitted_mail_capacity);
				cargo_capacities[default_cargo] = refitted_capacity;
				CargoType mail = GetCargoTypeByLabel(CT_MAIL);
				if (IsValidCargoType(mail)) cargo_capacities[mail] = refitted_mail_capacity;
			}
		}

		if (flags.Test(DoCommandFlag::Execute)) {
			if (type == VehicleType::Train && use_free_vehicles && !flags.Test(DoCommandFlag::AutoReplace) && Train::From(v)->IsEngine()) {
				/* Move any free wagons to the new vehicle. */
				NormalizeTrainVehInDepot(Train::From(v));
			}

			InvalidateWindowData(WindowClass::VehicleDepot, v->tile);
			InvalidateWindowClassesData(GetWindowClassForVehicleType(type), 0);
			SetWindowDirty(WindowClass::Company, _current_company);
			if (IsLocalCompany()) {
				InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the auto replace window (must be called before incrementing num_engines)
			}
		}

		if (subflags.Test(DoCommandFlag::Execute)) {
			GroupStatistics::CountEngine(v, 1);
			GroupStatistics::UpdateAutoreplace(_current_company);

			if (v->IsPrimaryVehicle()) {
				GroupStatistics::CountVehicle(v, 1);
				if (!subflags.Test(DoCommandFlag::AutoReplace)) OrderBackup::Restore(v, client_id);
			}

			Company::Get(v->owner)->freeunits[v->type].UseID(v->unitnumber);
		}


		/* If we are not in DoCommandFlag::Execute undo everything */
		if (flags != subflags) {
			Command<Commands::SellVehicle>::Do(DoCommandFlag::Execute, v->index, false, false, INVALID_CLIENT_ID);
		}
	}

	/* Only restore if we actually did some refitting */
	if (flags != subflags) RestoreRandomSeeds(saved_seeds);

	return { value, veh_id, refitted_capacity, refitted_mail_capacity, cargo_capacities };
}

/**
 * Sell a vehicle.
 * @param flags for command.
 * @param v_id vehicle ID being sold.
 * @param sell_chain sell the vehicle and all vehicles following it in the chain.
 * @param backup_order make a backup of the vehicle's order (if an engine).
 * @param client_id User.
 * @return the cost of this operation or an error.
 */
CommandCost CmdSellVehicle(DoCommandFlags flags, VehicleID v_id, bool sell_chain, bool backup_order, ClientID client_id)
{
	Vehicle *v = Vehicle::GetIfValid(v_id);
	if (v == nullptr || !IsCompanyBuildableVehicleType(v)) return CMD_ERROR;

	Vehicle *front = v->First();

	CommandCost ret = CheckOwnership(front->owner);
	if (ret.Failed()) return ret;

	if (front->vehstatus.Test(VehState::Crashed)) return CommandCost(STR_ERROR_VEHICLE_IS_DESTROYED);

	if (!front->IsStoppedInDepot()) return CommandCost(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + to_underlying(front->type));

	if (v->type == VehicleType::Train) {
		ret = CmdSellRailWagon(flags, v, sell_chain, backup_order, client_id);
	} else {
		ret = CommandCost(ExpensesType::NewVehicles, -front->value);

		if (flags.Test(DoCommandFlag::Execute)) {
			if (front->IsPrimaryVehicle() && backup_order) OrderBackup::Backup(front, client_id);
			delete front;
		}
	}

	return ret;
}

/**
 * Helper to run the refit cost callback.
 * @param v The vehicle we are refitting, can be nullptr.
 * @param engine_type Which engine to refit
 * @param new_cargo_type Cargo type we are refitting to.
 * @param new_subtype New cargo subtype.
 * @param[out] auto_refit_allowed The refit is allowed as an auto-refit.
 * @return Price for refitting
 */
static int GetRefitCostFactor(const Vehicle *v, EngineID engine_type, CargoType new_cargo_type, uint8_t new_subtype, bool *auto_refit_allowed)
{
	/* Prepare callback param with info about the new cargo type. */
	const Engine *e = Engine::Get(engine_type);

	/* Is this vehicle a NewGRF vehicle? */
	if (e->GetGRF() != nullptr) {
		const CargoSpec *cs = CargoSpec::Get(new_cargo_type);
		uint32_t param1 = (cs->classes.base() << 16) | (new_subtype << 8) | e->GetGRF()->cargo_map[new_cargo_type];

		uint16_t cb_res = GetVehicleCallback(CBID_VEHICLE_REFIT_COST, param1, 0, engine_type, v);
		if (cb_res != CALLBACK_FAILED) {
			*auto_refit_allowed = HasBit(cb_res, 14);
			int factor = GB(cb_res, 0, 14);
			if (factor >= 0x2000) factor -= 0x4000; // Treat as signed integer.
			return factor;
		}
	}

	*auto_refit_allowed = e->info.refit_cost == 0;
	return (v == nullptr || v->cargo_type != new_cargo_type) ? e->info.refit_cost : 0;
}

/**
 * Learn the price of refitting a certain engine
 * @param v The vehicle we are refitting, can be nullptr.
 * @param engine_type Which engine to refit
 * @param new_cargo_type Cargo type we are refitting to.
 * @param new_subtype New cargo subtype.
 * @param[out] auto_refit_allowed The refit is allowed as an auto-refit.
 * @return Price for refitting
 */
static CommandCost GetRefitCost(const Vehicle *v, EngineID engine_type, CargoType new_cargo_type, uint8_t new_subtype, bool *auto_refit_allowed)
{
	ExpensesType expense_type;
	const Engine *e = Engine::Get(engine_type);
	Price base_price;
	int cost_factor = GetRefitCostFactor(v, engine_type, new_cargo_type, new_subtype, auto_refit_allowed);
	switch (e->type) {
		case VehicleType::Ship:
			base_price = Price::BuildVehicleShip;
			expense_type = ExpensesType::ShipRun;
			break;

		case VehicleType::Road:
			base_price = Price::BuildVehicleRoad;
			expense_type = ExpensesType::RoadVehRun;
			break;

		case VehicleType::Aircraft:
			base_price = Price::BuildVehicleAircraft;
			expense_type = ExpensesType::AircraftRun;
			break;

		case VehicleType::Train:
			base_price = (e->VehInfo<RailVehicleInfo>().railveh_type == RailVehicleType::Wagon) ? Price::BuildVehicleWagon : Price::BuildVehicleTrain;
			cost_factor <<= 1;
			expense_type = ExpensesType::TrainRun;
			break;

		default: NOT_REACHED();
	}
	if (cost_factor < 0) {
		return CommandCost(expense_type, -GetPrice(base_price, -cost_factor, e->GetGRF(), -10));
	} else {
		return CommandCost(expense_type, GetPrice(base_price, cost_factor, e->GetGRF(), -10));
	}
}

/** Helper structure for RefitVehicle() */
struct RefitResult {
	Vehicle *v;         ///< Vehicle to refit
	uint capacity;      ///< New capacity of vehicle
	uint mail_capacity; ///< New mail capacity of aircraft
	uint8_t subtype;       ///< cargo subtype to refit to
};

/**
 * Refits a vehicle (chain).
 * This is the vehicle-type independent part of the CmdRefitXXX functions.
 * @param v            The vehicle to refit.
 * @param only_this    Whether to only refit this vehicle, or to check the rest of them.
 * @param num_vehicles Number of vehicles to refit (not counting articulated parts). Zero means the whole chain.
 * @param new_cargo_type      Cargotype to refit to
 * @param new_subtype  Cargo subtype to refit to. 0xFF means to try keeping the same subtype according to GetBestFittingSubType().
 * @param flags        Command flags
 * @param auto_refit   Refitting is done as automatic refitting outside a depot.
 * @return Refit cost + refitted capacity + mail capacity (aircraft).
 */
static std::tuple<CommandCost, uint, uint16_t, CargoArray> RefitVehicle(Vehicle *v, bool only_this, uint8_t num_vehicles, CargoType new_cargo_type, uint8_t new_subtype, DoCommandFlags flags, bool auto_refit)
{
	CommandCost cost(v->GetExpenseType(false));
	uint total_capacity = 0;
	uint total_mail_capacity = 0;
	num_vehicles = num_vehicles == 0 ? UINT8_MAX : num_vehicles;
	CargoArray cargo_capacities{};

	VehicleSet vehicles_to_refit;
	if (!only_this) {
		GetVehicleSet(vehicles_to_refit, v, num_vehicles);
		/* In this case, we need to check the whole chain. */
		v = v->First();
	}

	std::vector<RefitResult> refit_result;

	v->InvalidateNewGRFCacheOfChain();
	uint8_t actual_subtype = new_subtype;
	for (; v != nullptr; v = (only_this ? nullptr : v->Next())) {
		/* Reset actual_subtype for every new vehicle */
		if (!v->IsArticulatedPart()) actual_subtype = new_subtype;

		if (v->type == VehicleType::Train && std::ranges::find(vehicles_to_refit, v->index) == vehicles_to_refit.end() && !only_this) continue;

		const Engine *e = v->GetEngine();
		if (!e->CanCarryCargo()) continue;

		/* If the vehicle is not refittable, or does not allow automatic refitting,
		 * count its capacity nevertheless if the cargo matches */
		bool refittable = e->info.refit_mask.Test(new_cargo_type) && (!auto_refit || e->info.misc_flags.Test(EngineMiscFlag::AutoRefit));
		if (!refittable && v->cargo_type != new_cargo_type) {
			uint amount = e->DetermineCapacity(v, nullptr);
			if (amount > 0) cargo_capacities[v->cargo_type] += amount;
			continue;
		}

		/* Determine best fitting subtype if requested */
		if (actual_subtype == 0xFF) {
			actual_subtype = GetBestFittingSubType(v, v, new_cargo_type);
		}

		/* Back up the vehicle's cargo type */
		CargoType temp_cargo_type = v->cargo_type;
		uint8_t temp_subtype = v->cargo_subtype;
		if (refittable) {
			v->cargo_type = new_cargo_type;
			v->cargo_subtype = actual_subtype;
		}

		uint16_t mail_capacity = 0;
		uint amount = e->DetermineCapacity(v, &mail_capacity);
		total_capacity += amount;
		/* mail_capacity will always be zero if the vehicle is not an aircraft. */
		total_mail_capacity += mail_capacity;

		cargo_capacities[new_cargo_type] += amount;
		CargoType mail = GetCargoTypeByLabel(CT_MAIL);
		if (IsValidCargoType(mail)) cargo_capacities[mail] += mail_capacity;

		if (!refittable) continue;

		/* Restore the original cargo type */
		v->cargo_type = temp_cargo_type;
		v->cargo_subtype = temp_subtype;

		bool auto_refit_allowed;
		CommandCost refit_cost = GetRefitCost(v, v->engine_type, new_cargo_type, actual_subtype, &auto_refit_allowed);
		if (auto_refit && !flags.Test(DoCommandFlag::QueryCost) && !auto_refit_allowed) {
			/* Sorry, auto-refitting not allowed, subtract the cargo amount again from the total.
			 * When querying cost/capacity (for example in order refit GUI), we always assume 'allowed'.
			 * It is not predictable. */
			total_capacity -= amount;
			total_mail_capacity -= mail_capacity;

			if (v->cargo_type == new_cargo_type) {
				/* Add the old capacity nevertheless, if the cargo matches */
				total_capacity += v->cargo_cap;
				if (v->type == VehicleType::Aircraft) total_mail_capacity += v->Next()->cargo_cap;
			}
			continue;
		}
		cost.AddCost(std::move(refit_cost));

		/* Record the refitting.
		 * Do not execute the refitting immediately, so DetermineCapacity and GetRefitCost do the same in test and exec run.
		 * (weird NewGRFs)
		 * Note:
		 *  - If the capacity of vehicles depends on other vehicles in the chain, the actual capacity is
		 *    set after RefitVehicle() via ConsistChanged() and friends. The estimation via _returned_refit_capacity will be wrong.
		 *  - We have to call the refit cost callback with the pre-refit configuration of the chain because we want refit and
		 *    autorefit to behave the same, and we need its result for auto_refit_allowed.
		 */
		refit_result.emplace_back(v, amount, mail_capacity, actual_subtype);
	}

	if (flags.Test(DoCommandFlag::Execute)) {
		/* Store the result */
		for (RefitResult &result : refit_result) {
			Vehicle *u = result.v;
			u->refit_cap = (u->cargo_type == new_cargo_type) ? std::min<uint16_t>(result.capacity, u->refit_cap) : 0;
			if (u->cargo.TotalCount() > u->refit_cap) u->cargo.Truncate(u->cargo.TotalCount() - u->refit_cap);
			u->cargo_type = new_cargo_type;
			u->cargo_cap = result.capacity;
			u->cargo_subtype = result.subtype;
			if (u->type == VehicleType::Aircraft) {
				Vehicle *w = u->Next();
				assert(w != nullptr);
				w->refit_cap = std::min<uint16_t>(w->refit_cap, result.mail_capacity);
				w->cargo_cap = result.mail_capacity;
				if (w->cargo.TotalCount() > w->refit_cap) w->cargo.Truncate(w->cargo.TotalCount() - w->refit_cap);
			}
		}
	}

	refit_result.clear();
	return { cost, total_capacity, total_mail_capacity, cargo_capacities };
}

/**
 * Refits a vehicle to the specified cargo type.
 * @param flags type of operation
 * @param veh_id vehicle ID to refit
 * @param new_cargo_type New cargo type to refit to.
 * @param new_subtype New cargo subtype to refit to. 0xFF means to try keeping the same subtype according to GetBestFittingSubType().
 * @param auto_refit Automatic refitting.
 * @param only_this Refit only this vehicle. Used only for cloning vehicles.
 * @param num_vehicles Number of vehicles to refit (not counting articulated parts). Zero means all vehicles.
 *                     Only used if "refit only this vehicle" is false.
 * @return the cost of this operation or an error
 */
std::tuple<CommandCost, uint, uint16_t, CargoArray> CmdRefitVehicle(DoCommandFlags flags, VehicleID veh_id, CargoType new_cargo_type, uint8_t new_subtype, bool auto_refit, bool only_this, uint8_t num_vehicles)
{
	Vehicle *v = Vehicle::GetIfValid(veh_id);
	if (v == nullptr || !IsCompanyBuildableVehicleType(v)) return { CMD_ERROR, 0, 0, {} };

	Vehicle *front = v->First();

	CommandCost ret = CheckOwnership(front->owner);
	if (ret.Failed()) return { ret, 0, 0, {} };

	bool free_wagon = v->type == VehicleType::Train && Train::From(front)->IsFreeWagon(); // used by autoreplace/renew

	/* Don't allow shadows and such to be refitted. */
	if (v != front && (v->type == VehicleType::Ship || v->type == VehicleType::Aircraft)) return { CMD_ERROR, 0, 0, {} };

	/* Allow auto-refitting only during loading and normal refitting only in a depot. */
	if (!flags.Test(DoCommandFlag::QueryCost) && // used by the refit GUI, including the order refit GUI.
			!free_wagon && // used by autoreplace/renew
			(!auto_refit || !front->current_order.IsType(OT_LOADING)) && // refit inside stations
			!front->IsStoppedInDepot()) { // refit inside depots
		return { CommandCost(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + to_underlying(front->type)), 0, 0, {} };
	}

	if (front->vehstatus.Test(VehState::Crashed)) return { CommandCost(STR_ERROR_VEHICLE_IS_DESTROYED), 0, 0, {} };

	/* Check cargo */
	if (new_cargo_type >= NUM_CARGO) return { CMD_ERROR, 0, 0, {} };

	/* For ships and aircraft there is always only one. */
	only_this |= front->type == VehicleType::Ship || front->type == VehicleType::Aircraft;

	auto [cost, refit_capacity, mail_capacity, cargo_capacities] = RefitVehicle(v, only_this, num_vehicles, new_cargo_type, new_subtype, flags, auto_refit);

	if (flags.Test(DoCommandFlag::Execute)) {
		/* Update the cached variables */
		switch (v->type) {
			case VehicleType::Train:
				Train::From(front)->ConsistChanged(auto_refit ? CCF_AUTOREFIT : CCF_REFIT);
				break;
			case VehicleType::Road:
				RoadVehUpdateCache(RoadVehicle::From(front), auto_refit);
				if (_settings_game.vehicle.roadveh_acceleration_model != AccelerationModel::Original) RoadVehicle::From(front)->CargoChanged();
				break;

			case VehicleType::Ship:
				v->InvalidateNewGRFCacheOfChain();
				Ship::From(v)->UpdateCache();
				break;

			case VehicleType::Aircraft:
				v->InvalidateNewGRFCacheOfChain();
				UpdateAircraftCache(Aircraft::From(v), true);
				break;

			default: NOT_REACHED();
		}
		front->MarkDirty();

		if (!free_wagon) {
			InvalidateWindowData(WindowClass::VehicleDetails, front->index);
			InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0);
		}
		SetWindowDirty(WindowClass::VehicleDepot, front->tile);
	} else {
		/* Always invalidate the cache; querycost might have filled it. */
		v->InvalidateNewGRFCacheOfChain();
	}

	return { cost, refit_capacity, mail_capacity, cargo_capacities };
}

/**
 * Start/Stop a vehicle
 * @param flags type of operation
 * @param veh_id vehicle to start/stop, don't forget to change CcStartStopVehicle if you modify this!
 * @param evaluate_startstop_cb Shall the start/stop newgrf callback be evaluated (only valid with DoCommandFlag::AutoReplace for network safety)
 * @return the cost of this operation or an error
 */
CommandCost CmdStartStopVehicle(DoCommandFlags flags, VehicleID veh_id, bool evaluate_startstop_cb)
{
	/* Disable the effect of evaluate_startstop_cb, when DoCommandFlag::AutoReplace is not set */
	if (!flags.Test(DoCommandFlag::AutoReplace)) evaluate_startstop_cb = true;

	Vehicle *v = Vehicle::GetIfValid(veh_id);
	if (v == nullptr || !IsCompanyBuildableVehicleType(v) || !v->IsPrimaryVehicle()) return CMD_ERROR;

	CommandCost ret = CheckOwnership(v->owner);
	if (ret.Failed()) return ret;

	if (v->vehstatus.Test(VehState::Crashed)) return CommandCost(STR_ERROR_VEHICLE_IS_DESTROYED);

	switch (v->type) {
		case VehicleType::Train:
			if (v->vehstatus.Test(VehState::Stopped) && Train::From(v)->gcache.cached_power == 0) return CommandCost(STR_ERROR_TRAIN_START_NO_POWER);
			break;

		case VehicleType::Ship:
		case VehicleType::Road:
			break;

		case VehicleType::Aircraft: {
			Aircraft *a = Aircraft::From(v);
			/* cannot stop airplane when in flight, or when taking off / landing */
			if (a->state >= STARTTAKEOFF && a->state < TERM7) return CommandCost(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
			if (a->flags.Test(VehicleAirFlag::HelicopterDirectDescent)) return CommandCost(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
			break;
		}

		default: return CMD_ERROR;
	}

	if (evaluate_startstop_cb) {
		/* Check if this vehicle can be started/stopped. Failure means 'allow'. */
		std::array<int32_t, 1> regs100;
		uint16_t callback = GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK, 0, 0, v->engine_type, v, regs100);
		StringID error = STR_NULL;
		if (callback != CALLBACK_FAILED) {
			if (v->GetGRF()->grf_version < 8) {
				/* 8 bit result 0xFF means 'allow' */
				if (callback < 0x400 && GB(callback, 0, 8) != 0xFF) error = GetGRFStringID(v->GetGRFID(), GRFSTR_MISC_GRF_TEXT + callback);
			} else {
				if (callback < 0x400) {
					error = GetGRFStringID(v->GetGRFID(), GRFSTR_MISC_GRF_TEXT + callback);
				} else {
					switch (callback) {
						case 0x400: // allow
							break;

						case 0x40F:
							error = GetGRFStringID(v->GetGRFID(), static_cast<GRFStringID>(regs100[0]));
							break;

						default: // unknown reason -> disallow
							error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
							break;
					}
				}
			}
		}
		if (error != STR_NULL) return CommandCost(error);
	}

	if (flags.Test(DoCommandFlag::Execute)) {
		if (v->IsStoppedInDepot() && !flags.Test(DoCommandFlag::AutoReplace)) DeleteVehicleNews(veh_id, AdviceType::VehicleWaiting);

		v->vehstatus.Flip(VehState::Stopped);
		if (v->type != VehicleType::Train) v->cur_speed = 0; // trains can stop 'slowly'

		/* Unbunching data is no longer valid. */
		v->ResetDepotUnbunching();

		v->MarkDirty();
		SetWindowWidgetDirty(WindowClass::VehicleView, v->index, WID_VV_START_STOP);
		SetWindowDirty(WindowClass::VehicleDepot, v->GetMovingFront()->tile);
		SetWindowClassesDirty(GetWindowClassForVehicleType(v->type));
		InvalidateWindowData(WindowClass::VehicleView, v->index);
	}
	return CommandCost();
}

/**
 * Starts or stops a lot of vehicles
 * @param flags type of operation
 * @param tile Tile of the depot where the vehicles are started/stopped (only used for depots)
 * @param do_start set = start vehicles, unset = stop vehicles
 * @param vehicle_list_window if set, then it's a vehicle list window, not a depot and Tile is ignored in this case
 * @param vli VehicleListIdentifier
 * @return the cost of this operation or an error
 */
CommandCost CmdMassStartStopVehicle(DoCommandFlags flags, TileIndex tile, bool do_start, bool vehicle_list_window, const VehicleListIdentifier &vli)
{
	VehicleList list;

	if (!vli.Valid()) return CMD_ERROR;
	if (!IsCompanyBuildableVehicleType(vli.vtype)) return CMD_ERROR;

	if (vehicle_list_window) {
		if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
	} else {
		if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;
		/* Get the list of vehicles in the depot */
		BuildDepotVehicleList(vli.vtype, tile, &list, nullptr);
	}

	for (const Vehicle *v : list) {
		if (v->vehstatus.Test(VehState::Stopped) != do_start) continue;

		if (!vehicle_list_window && !v->IsChainInDepot()) continue;

		/* Just try and don't care if some vehicle's can't be stopped. */
		Command<Commands::StartStopVehicle>::Do(flags, v->index, false);
	}

	return CommandCost();
}

/**
 * Sells all vehicles in a depot
 * @param flags type of operation
 * @param tile Tile of the depot where the depot is
 * @param vehicle_type Vehicle type
 * @return the cost of this operation or an error
 */
CommandCost CmdDepotSellAllVehicles(DoCommandFlags flags, TileIndex tile, VehicleType vehicle_type)
{
	VehicleList list;

	CommandCost cost(ExpensesType::NewVehicles);

	if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
	if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;

	/* Get the list of vehicles in the depot */
	BuildDepotVehicleList(vehicle_type, tile, &list, &list);

	CommandCost last_error = CMD_ERROR;
	bool had_success = false;
	for (const Vehicle *v : list) {
		CommandCost ret = Command<Commands::SellVehicle>::Do(flags, v->index, true, false, INVALID_CLIENT_ID);
		if (ret.Succeeded()) {
			cost.AddCost(ret.GetCost());
			had_success = true;
		} else {
			last_error = std::move(ret);
		}
	}

	return had_success ? cost : last_error;
}

/**
 * Autoreplace all vehicles in the depot
 * @param flags type of operation
 * @param tile Tile of the depot where the vehicles are
 * @param vehicle_type Type of vehicle
 * @return the cost of this operation or an error
 */
CommandCost CmdDepotMassAutoReplace(DoCommandFlags flags, TileIndex tile, VehicleType vehicle_type)
{
	VehicleList list;
	CommandCost cost = CommandCost(ExpensesType::NewVehicles);

	if (!IsCompanyBuildableVehicleType(vehicle_type)) return CMD_ERROR;
	if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR;

	/* Get the list of vehicles in the depot */
	BuildDepotVehicleList(vehicle_type, tile, &list, &list, true);

	for (const Vehicle *v : list) {
		/* Ensure that the vehicle completely in the depot */
		if (!v->IsChainInDepot()) continue;

		CommandCost ret = Command<Commands::AutoreplaceVehicle>::Do(flags, v->index);

		if (ret.Succeeded()) cost.AddCost(ret.GetCost());
	}
	return cost;
}

/**
 * Test if a name is unique among vehicle names.
 * @param name Name to test.
 * @return True ifffffff the name is unique.
 */
bool IsUniqueVehicleName(const std::string &name)
{
	for (const Vehicle *v : Vehicle::Iterate()) {
		if (!v->name.empty() && v->name == name) return false;
	}

	return true;
}

/**
 * Clone the custom name of a vehicle, adding or incrementing a number.
 * @param src Source vehicle, with a custom name.
 * @param dst Destination vehicle.
 */
static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
{
	std::string buf;

	/* Find the position of the first digit in the last group of digits. */
	size_t number_position;
	for (number_position = src->name.length(); number_position > 0; number_position--) {
		/* The design of UTF-8 lets this work simply without having to check
		 * for UTF-8 sequences. */
		if (src->name[number_position - 1] < '0' || src->name[number_position - 1] > '9') break;
	}

	/* Format buffer and determine starting number. */
	long num;
	uint8_t padding = 0;
	if (number_position == src->name.length()) {
		/* No digit at the end, so start at number 2. */
		buf = src->name;
		buf += " ";
		number_position = buf.length();
		num = 2;
	} else {
		/* Found digits, parse them and start at the next number. */
		buf = src->name.substr(0, number_position);

		auto num_str = std::string_view(src->name).substr(number_position);
		padding = (uint8_t)num_str.length();

		[[maybe_unused]] auto err = std::from_chars(num_str.data(), num_str.data() + num_str.size(), num, 10).ec;
		assert(err == std::errc());
		num++;
	}

	/* Check if this name is already taken. */
	for (int max_iterations = 1000; max_iterations > 0; max_iterations--, num++) {
		std::string new_name = fmt::format("{}{:0{}}", buf, num, padding);

		/* Check the name is unique. */
		if (IsUniqueVehicleName(new_name)) {
			dst->name = std::move(new_name);
			break;
		}
	}

	/* All done. If we didn't find a name, it'll just use its default. */
}

/**
 * Clone a vehicle. If it is a train, it will clone all the cars too
 * @param flags type of operation
 * @param tile tile of the depot where the cloned vehicle is build
 * @param veh_id the original vehicle's index
 * @param share_orders shared orders, else copied orders
 * @return the cost of this operation + the new vehicle ID or an error
 */
std::tuple<CommandCost, VehicleID> CmdCloneVehicle(DoCommandFlags flags, TileIndex tile, VehicleID veh_id, bool share_orders)
{
	CommandCost total_cost(ExpensesType::NewVehicles);

	Vehicle *v = Vehicle::GetIfValid(veh_id);
	if (v == nullptr || !IsCompanyBuildableVehicleType(v) || !v->IsPrimaryVehicle()) return { CMD_ERROR, VehicleID::Invalid() };
	Vehicle *v_front = v;
	Vehicle *w = nullptr;
	Vehicle *w_front = nullptr;
	Vehicle *w_rear = nullptr;

	/*
	 * v_front is the front engine in the original vehicle
	 * v is the car/vehicle of the original vehicle that is currently being copied
	 * w_front is the front engine of the cloned vehicle
	 * w is the car/vehicle currently being cloned
	 * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
	 */

	CommandCost ret = CheckOwnership(v->owner);
	if (ret.Failed()) return { ret, VehicleID::Invalid() };

	/* Crashed trains can only be cloned before cleanup begins. */
	if (v->type == VehicleType::Train && (!v->IsFrontEngine() || Train::From(v)->crash_anim_pos >= 4400)) return { CommandCost(STR_ERROR_VEHICLE_IS_DESTROYED), VehicleID::Invalid() };

	/* check that we can allocate enough vehicles */
	if (!flags.Test(DoCommandFlag::Execute)) {
		int veh_counter = 0;
		do {
			veh_counter++;
		} while ((v = v->Next()) != nullptr);

		if (!Vehicle::CanAllocateItem(veh_counter)) {
			return { CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME), VehicleID::Invalid() };
		}
	}

	v = v_front;

	VehicleID new_veh_id = VehicleID::Invalid();
	do {
		if (v->type == VehicleType::Train && Train::From(v)->IsRearDualheaded()) {
			/* we build the rear ends of multiheaded trains with the front ones */
			continue;
		}

		/* In case we're building a multi headed vehicle and the maximum number of
		 * vehicles is almost reached (e.g. max trains - 1) not all vehicles would
		 * be cloned. When the non-primary engines were build they were seen as
		 * 'new' vehicles whereas they would immediately be joined with a primary
		 * engine. This caused the vehicle to be not build as 'the limit' had been
		 * reached, resulting in partially build vehicles and such. */
		DoCommandFlags build_flags = flags;
		if (flags.Test(DoCommandFlag::Execute) && !v->IsPrimaryVehicle()) build_flags.Set(DoCommandFlag::AutoReplace);

		CommandCost cost;
		std::tie(cost, new_veh_id, std::ignore, std::ignore, std::ignore) = Command<Commands::BuildVehicle>::Do(build_flags, tile, v->engine_type, false, INVALID_CARGO, INVALID_CLIENT_ID);

		if (cost.Failed()) {
			/* Can't build a part, then sell the stuff we already made; clear up the mess */
			if (w_front != nullptr) Command<Commands::SellVehicle>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
			return { cost, VehicleID::Invalid() };
		}

		total_cost.AddCost(cost.GetCost());

		if (flags.Test(DoCommandFlag::Execute)) {
			w = Vehicle::Get(new_veh_id);

			if (v->type == VehicleType::Train && Train::From(v)->flags.Test(VehicleRailFlag::Flipped)) {
				/* Only copy the reverse state if neither old or new vehicle implements reverse-on-build probability callback. */
				if (!TestVehicleBuildProbability(v, BuildProbabilityType::Reversed).has_value() &&
					!TestVehicleBuildProbability(w, BuildProbabilityType::Reversed).has_value()) {
					Train::From(w)->flags.Set(VehicleRailFlag::Flipped);
				}
			}

			if (v->type == VehicleType::Train && !v->IsFrontEngine()) {
				/* this s a train car
				 * add this unit to the end of the train */
				CommandCost result = Command<Commands::MoveRailVehicle>::Do(flags, w->index, w_rear->index, true);
				if (result.Failed()) {
					/* The train can't be joined to make the same consist as the original.
					 * Sell what we already made (clean up) and return an error.           */
					Command<Commands::SellVehicle>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
					Command<Commands::SellVehicle>::Do(flags, w->index,       true, false, INVALID_CLIENT_ID);
					return { result, VehicleID::Invalid() }; // return error and the message returned from Commands::MoveRailVehicle
				}
			} else {
				/* this is a front engine or not a train. */
				w_front = w;
				w->service_interval = v->service_interval;
				w->SetServiceIntervalIsCustom(v->ServiceIntervalIsCustom());
				w->SetServiceIntervalIsPercent(v->ServiceIntervalIsPercent());
			}
			w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop
		}
	} while (v->type == VehicleType::Train && (v = v->GetNextVehicle()) != nullptr);

	if (flags.Test(DoCommandFlag::Execute) && v_front->type == VehicleType::Train) {
		/* for trains this needs to be the front engine due to the callback function */
		new_veh_id = w_front->index;
	}

	if (flags.Test(DoCommandFlag::Execute)) {
		/* Cloned vehicles belong to the same group */
		Command<Commands::AddVehicleToGroup>::Do(flags, v_front->group_id, w_front->index, false, VehicleListIdentifier{});
	}


	/* Take care of refitting. */
	w = w_front;
	v = v_front;

	/* Both building and refitting are influenced by newgrf callbacks, which
	 * makes it impossible to accurately estimate the cloning costs. In
	 * particular, it is possible for engines of the same type to be built with
	 * different numbers of articulated parts, so when refitting we have to
	 * loop over real vehicles first, and then the articulated parts of those
	 * vehicles in a different loop. */
	do {
		do {
			if (flags.Test(DoCommandFlag::Execute)) {
				assert(w != nullptr);

				/* Find out what's the best sub type */
				uint8_t subtype = GetBestFittingSubType(v, w, v->cargo_type);
				if (w->cargo_type != v->cargo_type || w->cargo_subtype != subtype) {
					CommandCost cost = ExtractCommandCost(Command<Commands::RefitVehicle>::Do(flags, w->index, v->cargo_type, subtype, false, true, 0));
					if (cost.Succeeded()) total_cost.AddCost(cost.GetCost());
				}

				if (w->IsGroundVehicle() && w->HasArticulatedPart()) {
					w = w->GetNextArticulatedPart();
				} else {
					break;
				}
			} else {
				const Engine *e = v->GetEngine();
				CargoType initial_cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : INVALID_CARGO);

				if (v->cargo_type != initial_cargo && IsValidCargoType(initial_cargo)) {
					bool dummy;
					total_cost.AddCost(GetRefitCost(nullptr, v->engine_type, v->cargo_type, v->cargo_subtype, &dummy));
				}
			}

			if (v->IsGroundVehicle() && v->HasArticulatedPart()) {
				v = v->GetNextArticulatedPart();
			} else {
				break;
			}
		} while (v != nullptr);

		if (flags.Test(DoCommandFlag::Execute) && v->type == VehicleType::Train) w = w->GetNextVehicle();
	} while (v->type == VehicleType::Train && (v = v->GetNextVehicle()) != nullptr);

	if (flags.Test(DoCommandFlag::Execute)) {
		/*
		 * Set the orders of the vehicle. Cannot do it earlier as we need
		 * the vehicle refitted before doing this, otherwise the moved
		 * cargo types might not match (passenger vs non-passenger)
		 */
		CommandCost result = Command<Commands::CloneOrder>::Do(flags, (share_orders ? CO_SHARE : CO_COPY), w_front->index, v_front->index);
		if (result.Failed()) {
			/* The vehicle has already been bought, so now it must be sold again. */
			Command<Commands::SellVehicle>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
			return { result, VehicleID::Invalid() };
		}

		/* Now clone the vehicle's name, if it has one. */
		if (!v_front->name.empty()) CloneVehicleName(v_front, w_front);

		/* Since we can't estimate the cost of cloning a vehicle accurately we must
		 * check whether the company has enough money manually. */
		if (!CheckCompanyHasMoney(total_cost)) {
			/* The vehicle has already been bought, so now it must be sold again. */
			Command<Commands::SellVehicle>::Do(flags, w_front->index, true, false, INVALID_CLIENT_ID);
			return { total_cost, VehicleID::Invalid() };
		}
	}

	return { total_cost, new_veh_id };
}

/**
 * Send all vehicles of type to depots
 * @param flags   the flags used for DoCommand()
 * @param service should the vehicles only get service in the depots
 * @param vli     identifier of the vehicle list
 * @return 0 for success and CMD_ERROR if no vehicle is able to go to depot
 */
static CommandCost SendAllVehiclesToDepot(DoCommandFlags flags, bool service, const VehicleListIdentifier &vli)
{
	VehicleList list;

	if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;

	/* Send all the vehicles to a depot */
	bool had_success = false;
	for (uint i = 0; i < list.size(); i++) {
		const Vehicle *v = list[i];
		CommandCost ret = Command<Commands::SendVehicleToDepot>::Do(flags, v->index, (service ? DepotCommandFlag::Service : DepotCommandFlags{}) | DepotCommandFlag::DontCancel, {});

		if (ret.Succeeded()) {
			had_success = true;

			/* Return 0 if DoCommandFlag::Execute is not set this is a valid goto depot command)
			 * In this case we know that at least one vehicle can be sent to a depot
			 * and we will issue the command. We can now safely quit the loop, knowing
			 * it will succeed at least once. With DoCommandFlag::Execute we really need to send them to the depot */
			if (!flags.Test(DoCommandFlag::Execute)) break;
		}
	}

	return had_success ? CommandCost() : CMD_ERROR;
}

/**
 * Send a vehicle to the depot.
 * @param flags for command type
 * @param veh_id vehicle ID to send to the depot
 * @param depot_cmd DEPOT_ flags (see vehicle_type.h)
 * @param vli VehicleListIdentifier.
 * @return the cost of this operation or an error
 */
CommandCost CmdSendVehicleToDepot(DoCommandFlags flags, VehicleID veh_id, DepotCommandFlags depot_cmd, const VehicleListIdentifier &vli)
{
	if (depot_cmd.Test(DepotCommandFlag::MassSend)) {
		/* Mass goto depot requested */
		if (!vli.Valid()) return CMD_ERROR;
		return SendAllVehiclesToDepot(flags, depot_cmd.Test(DepotCommandFlag::Service), vli);
	}

	Vehicle *v = Vehicle::GetIfValid(veh_id);
	if (v == nullptr || !IsCompanyBuildableVehicleType(v)) return CMD_ERROR;
	if (!v->IsPrimaryVehicle()) return CMD_ERROR;

	return v->SendToDepot(flags, depot_cmd);
}

/**
 * Give a custom name to your vehicle
 * @param flags type of operation
 * @param veh_id vehicle ID to name
 * @param text the new name or an empty string when resetting to the default
 * @return the cost of this operation or an error
 */
CommandCost CmdRenameVehicle(DoCommandFlags flags, VehicleID veh_id, const std::string &text)
{
	Vehicle *v = Vehicle::GetIfValid(veh_id);
	if (v == nullptr || !IsCompanyBuildableVehicleType(v) || !v->IsPrimaryVehicle()) return CMD_ERROR;

	CommandCost ret = CheckOwnership(v->owner);
	if (ret.Failed()) return ret;

	bool reset = text.empty();

	if (!reset) {
		if (Utf8StringLength(text) >= MAX_LENGTH_VEHICLE_NAME_CHARS) return CMD_ERROR;
		if (!flags.Test(DoCommandFlag::AutoReplace) && !IsUniqueVehicleName(text)) return CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE);
	}

	if (flags.Test(DoCommandFlag::Execute)) {
		if (reset) {
			v->name.clear();
		} else {
			v->name = text;
		}
		InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 1);
		MarkWholeScreenDirty();
	}

	return CommandCost();
}


/**
 * Change the service interval of a vehicle
 * @param flags type of operation
 * @param veh_id vehicle ID that is being service-interval-changed
 * @param serv_int new service interval
 * @param is_custom service interval is custom flag
 * @param is_percent service interval is percentage flag
 * @return the cost of this operation or an error
 */
CommandCost CmdChangeServiceInt(DoCommandFlags flags, VehicleID veh_id, uint16_t serv_int, bool is_custom, bool is_percent)
{
	Vehicle *v = Vehicle::GetIfValid(veh_id);
	if (v == nullptr || !IsCompanyBuildableVehicleType(v) || !v->IsPrimaryVehicle()) return CMD_ERROR;

	CommandCost ret = CheckOwnership(v->owner);
	if (ret.Failed()) return ret;

	const Company *company = Company::Get(v->owner);
	is_percent = is_custom ? is_percent : company->settings.vehicle.servint_ispercent;

	if (is_custom) {
		if (serv_int != GetServiceIntervalClamped(serv_int, is_percent)) return CMD_ERROR;
	} else {
		serv_int = CompanyServiceInterval(company, v->type);
	}

	if (flags.Test(DoCommandFlag::Execute)) {
		v->SetServiceInterval(serv_int);
		v->SetServiceIntervalIsCustom(is_custom);
		v->SetServiceIntervalIsPercent(is_percent);
		SetWindowDirty(WindowClass::VehicleDetails, v->index);
	}

	return CommandCost();
}
