function ConnectAllDepots() {
	local depots = AIDepotList(AITile.TRANSPORT_RAIL);
	local depot = depots.Begin();
	while (depots.HasNext()) {
		ConnectDepot(depot)
		depot = depots.Next()
	}
}

function ConnectDepots(depots) {
	foreach (depot in depots) {
		ConnectDepot(depot)
	}
}

function ConnectDepot(depot) {
	//LogTile("Connecting depot", depot)
	local front = AIRail.GetRailDepotFrontTile(depot)
	local c = 0;
	foreach (delta in [dXY(1,-1), dXY(1,1), dXY(-1,-1), dXY(-1,1), dXY(0,2), dXY(0,-2), dXY(2,0), dXY(-2,0)]) {
		if (AIRail.IsRailTile(depot + delta))
			c += (AIRail.BuildRail(depot,front, depot + delta)  || AIError.GetLastError() == AIError.ERR_ALREADY_BUILT)?1:0
	}
	return c
}

function DisconnectDepot(depot) {
	//LogTile("Disconnecting depot", depot)
	local front = AIRail.GetRailDepotFrontTile(depot)
	local c = 0;
	foreach (delta in [dXY(1,-1), dXY(1,1), dXY(-1,-1), dXY(-1,1), dXY(0,2), dXY(0,-2), dXY(2,0), dXY(-2,0)]) {
		AIRail.RemoveRail(depot,front, depot + delta) 
	}
}

function RemoveDepot(depot) {
	DisconnectDepot(depot)
	AITile.DemolishTile(depot);
}