/* $Id$ */

/*
 * 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 <http://www.gnu.org/licenses/>.
 */

/** @file smallmap_gui.cpp GUI that shows a small map of the world with metadata like owner or height. */

#include "stdafx.h"
#include "clear_map.h"
#include "industry.h"
#include "station_map.h"
#include "landscape.h"
#include "window_gui.h"
#include "tree_map.h"
#include "viewport_func.h"
#include "town.h"
#include "blitter/factory.hpp"
#include "tunnelbridge_map.h"
#include "strings_func.h"
#include "core/endian_func.hpp"
#include "vehicle_base.h"
#include "sound_func.h"
#include "window_func.h"
#include "company_base.h"
//#include "cargotype.h"
//#include "openttd.h"
#include "company_func.h"
#include "station_base.h"

#include "table/strings.h"

//#include <cmath>
#include <vector>

/** Widget numbers of the small map window. */
enum SmallMapWindowWidgets {
	SM_WIDGET_CAPTION,           ///< Caption widget.
	SM_WIDGET_MAP_BORDER,        ///< Border around the smallmap.
	SM_WIDGET_MAP,               ///< Panel containing the smallmap.
	SM_WIDGET_LEGEND,            ///< Bottom panel to display smallmap legends.
	SM_WIDGET_BLANK,             ///< Empty button as placeholder.
	SM_WIDGET_ZOOM_IN,           ///< Button to zoom in one step.
	SM_WIDGET_ZOOM_OUT,          ///< Button to zoom out one step.
	SM_WIDGET_CONTOUR,           ///< Button to select the contour view (height map).
	SM_WIDGET_VEHICLES,          ///< Button to select the vehicles view.
	SM_WIDGET_INDUSTRIES,        ///< Button to select the industries view.
	SM_WIDGET_LINKSTATS,         ///< Button to select the link stats view.
	SM_WIDGET_ROUTES,            ///< Button to select the routes view.
	SM_WIDGET_VEGETATION,        ///< Button to select the vegetation view.
	SM_WIDGET_OWNERS,            ///< Button to select the owners view.
	SM_WIDGET_CENTERMAP,         ///< Button to move smallmap center to main window center.
	SM_WIDGET_TOGGLETOWNNAME,    ///< Toggle button to display town names.
	SM_WIDGET_SELECT_BUTTONS,    ///< Selection widget for the buttons present in some smallmap modes.
	SM_WIDGET_ENABLE_ALL,        ///< Button to enable display of all toggable legend entries.
	SM_WIDGET_DISABLE_ALL,       ///< Button to disable display of all toggable legend entries.
	SM_WIDGET_SHOW_HEIGHT,       ///< Show heightmap toggle button.
};

static int _smallmap_industry_count;         ///< Number of used industries
static int _smallmap_company_count;          ///< Number of entries in the owner legend.
static const int NUM_NO_COMPANY_ENTRIES = 4; ///< Number of entries in the owner legend that are not companies.
static int _smallmap_cargo_count;            ///< number of cargos in the link stats legend

static const uint8 PC_ROUGH_LAND      = 0x52; ///< Dark green palette colour for rough land.
static const uint8 PC_GRASS_LAND      = 0x54; ///< Dark green palette colour for grass land.
static const uint8 PC_BARE_LAND       = 0x37; ///< Brown palette colour for bare land.
static const uint8 PC_FIELDS          = 0x25; ///< Light brown palette colour for fields.
static const uint8 PC_TREES           = 0x57; ///< Green palette colour for trees.
static const uint8 PC_WATER           = 0xCA; ///< Dark blue palette colour for water.

enum SmallMapStats {
	STAT_CAPACITY,
	STAT_BEGIN = STAT_CAPACITY,
	STAT_USAGE,
	STAT_PLANNED,
	STAT_SENT,
	STAT_TEXT,
	STAT_GRAPH,
	STAT_END,
	NUM_STATS = STAT_END,
};

/** Macro for ordinary entry of LegendAndColour */
#define MK(a, b) {a, b, INVALID_INDUSTRYTYPE, 0, INVALID_COMPANY, true, false, false}

/** Macro for a height legend entry with configurable colour. */
#define MC(height)  {0, STR_TINY_BLACK_HEIGHT, INVALID_INDUSTRYTYPE, height, INVALID_COMPANY, true, false, false}

/**
 * Macro for break marker in arrays of LegendAndColour.
 * It will have valid data, though
 */
#define MS(a, b) {a, b, INVALID_INDUSTRYTYPE, 0, INVALID_COMPANY, true, false, true}

/** Macro for a height legend break marker entry with configurable colour. */
#define MCS(height)  {0, STR_TINY_BLACK_HEIGHT, INVALID_INDUSTRYTYPE, height, INVALID_COMPANY, true, false, true}

/** Macro for non-company owned property entry of LegendAndColour */
#define MO(a, b) {a, b, INVALID_INDUSTRYTYPE, 0, INVALID_COMPANY, true, false, false}

/** Macro used for forcing a rebuild of the owner legend the first time it is used. */
#define MOEND() {0, 0, INVALID_INDUSTRYTYPE, 0, OWNER_NONE, true, true, false}

/** Macro for end of list marker in arrays of LegendAndColour */
#define MKEND() {0, STR_NULL, INVALID_INDUSTRYTYPE, 0, INVALID_COMPANY, true, true, false}

/** Structure for holding relevant data for legends in small map */
struct LegendAndColour {
	uint8 colour;              ///< Colour of the item on the map.
	StringID legend;           ///< String corresponding to the coloured item.
	IndustryType type;         ///< Type of industry. Only valid for industry entries.
	uint8 height;              ///< Height in tiles. Only valid for height legend entries.
	CompanyID company;         ///< Company to display. Only valid for company entries of the owner legend.
	bool show_on_map;          ///< For filtering industries, if \c true, industry is shown on the map in colour.
	bool end;                  ///< This is the end of the list.
	bool col_break;            ///< Perform a column break and go further at the next column.
};

/** Legend text giving the colours to look for on the minimap (original) */
static LegendAndColour _legend_land_contours_old[] = {
	/* The colours for the following values are set at BuildLandLegend() based on each colour scheme when the more height levels patch is off. */
	MC(1),
	MC(5),
	MC(9),
	MC(13),
	MC(15),

	MS(PC_BLACK,           STR_SMALLMAP_LEGENDA_ROADS),
	MK(PC_GREY,            STR_SMALLMAP_LEGENDA_RAILROADS),
	MK(PC_LIGHT_BLUE,      STR_SMALLMAP_LEGENDA_STATIONS_AIRPORTS_DOCKS),
	MK(PC_DARK_RED,        STR_SMALLMAP_LEGENDA_BUILDINGS_INDUSTRIES),
	MK(PC_WHITE,           STR_SMALLMAP_LEGENDA_VEHICLES),
	MKEND()
};

/** Legend text giving the colours to look for on the minimap (in case of AllowMoreHeightlevels()) */
static LegendAndColour _legend_land_contours_extended[] = {
	/* The colours for the following values are set at BuildLandLegend() based on each colour scheme when the more height levels patch is on. */
	MC(1),
	MC(16),
	MC(32),
	MC(48),
	MC(64),
	MC(80),

	MCS(96),
	MC(112),
	MC(128),
	MC(144),
	MC(160),
	MC(176),

	MCS(192),
	MC(208),
	MC(224),
	MC(240),
	MC(255),

	MS(PC_BLACK,      STR_SMALLMAP_LEGENDA_ROADS),
	MK(PC_GREY,       STR_SMALLMAP_LEGENDA_RAILROADS),
	MK(PC_LIGHT_BLUE, STR_SMALLMAP_LEGENDA_STATIONS_AIRPORTS_DOCKS),
	MK(PC_DARK_RED,   STR_SMALLMAP_LEGENDA_BUILDINGS_INDUSTRIES),
	MK(PC_WHITE,      STR_SMALLMAP_LEGENDA_VEHICLES),
	MKEND()
};

static const LegendAndColour _legend_vehicles[] = {
	MK(PC_RED,             STR_SMALLMAP_LEGENDA_TRAINS),
	MK(PC_YELLOW,          STR_SMALLMAP_LEGENDA_ROAD_VEHICLES),
	MK(PC_LIGHT_BLUE,      STR_SMALLMAP_LEGENDA_SHIPS),
	MK(PC_WHITE,           STR_SMALLMAP_LEGENDA_AIRCRAFT),

	MS(PC_BLACK,           STR_SMALLMAP_LEGENDA_TRANSPORT_ROUTES),
	MK(PC_DARK_RED,        STR_SMALLMAP_LEGENDA_BUILDINGS_INDUSTRIES),
	MKEND()
};

static const LegendAndColour _legend_routes[] = {
	MK(PC_BLACK,           STR_SMALLMAP_LEGENDA_ROADS),
	MK(PC_GREY,            STR_SMALLMAP_LEGENDA_RAILROADS),
	MK(PC_DARK_RED,        STR_SMALLMAP_LEGENDA_BUILDINGS_INDUSTRIES),

	MS(PC_VERY_DARK_BROWN, STR_SMALLMAP_LEGENDA_RAILROAD_STATION),
	MK(PC_ORANGE,          STR_SMALLMAP_LEGENDA_TRUCK_LOADING_BAY),
	MK(PC_YELLOW,          STR_SMALLMAP_LEGENDA_BUS_STATION),
	MK(PC_RED,             STR_SMALLMAP_LEGENDA_AIRPORT_HELIPORT),
	MK(PC_LIGHT_BLUE,      STR_SMALLMAP_LEGENDA_DOCK),
	MKEND()
};

static const LegendAndColour _legend_vegetation[] = {
	MK(PC_ROUGH_LAND,      STR_SMALLMAP_LEGENDA_ROUGH_LAND),
	MK(PC_GRASS_LAND,      STR_SMALLMAP_LEGENDA_GRASS_LAND),
	MK(PC_BARE_LAND,       STR_SMALLMAP_LEGENDA_BARE_LAND),
	MK(PC_FIELDS,          STR_SMALLMAP_LEGENDA_FIELDS),
	MK(PC_TREES,           STR_SMALLMAP_LEGENDA_TREES),
	MK(PC_GREEN,           STR_SMALLMAP_LEGENDA_FOREST),

	MS(PC_GREY,            STR_SMALLMAP_LEGENDA_ROCKS),
	MK(PC_ORANGE,          STR_SMALLMAP_LEGENDA_DESERT),
	MK(PC_LIGHT_BLUE,      STR_SMALLMAP_LEGENDA_SNOW),
	MK(PC_BLACK,           STR_SMALLMAP_LEGENDA_TRANSPORT_ROUTES),
	MK(PC_DARK_RED,        STR_SMALLMAP_LEGENDA_BUILDINGS_INDUSTRIES),
	MKEND()
};

static LegendAndColour _legend_land_owners[NUM_NO_COMPANY_ENTRIES + MAX_COMPANIES + 1] = {
	MO(PC_WATER,           STR_SMALLMAP_LEGENDA_WATER),
	MO(0x00,               STR_SMALLMAP_LEGENDA_NO_OWNER), // This colour will vary depending on settings.
	MO(PC_DARK_RED,        STR_SMALLMAP_LEGENDA_TOWNS),
	MO(PC_DARK_GREY,       STR_SMALLMAP_LEGENDA_INDUSTRIES),
	/* The legend will be terminated the first time it is used. */
	MOEND(),
};

#undef MK
#undef MC
#undef MS
#undef MCS
#undef MO
#undef MOEND
#undef MKEND

/**
 * Allow room for all industries, plus a terminator entry
 * This is required in order to have the indutry slots all filled up
 */
static LegendAndColour _legend_from_industries[NUM_INDUSTRYTYPES + 1];
/** For connecting industry type to position in industries list(small map legend) */
static uint _industry_to_list_pos[NUM_INDUSTRYTYPES];
/** Show heightmap in industry and owner mode of smallmap window. */
static bool _smallmap_show_heightmap = false;
/** For connecting company ID to position in owner list (small map legend) */
static uint _company_to_list_pos[MAX_COMPANIES];

/**
 * Fills an array for the industries legends.
 */
void BuildIndustriesLegend()
{
	uint j = 0;

	/* Add each name */
	for (uint8 i = 0; i < NUM_INDUSTRYTYPES; i++) {
		IndustryType ind = _sorted_industry_types[i];
		const IndustrySpec *indsp = GetIndustrySpec(ind);
		if (indsp->enabled) {
			_legend_from_industries[j].legend = indsp->name;
			_legend_from_industries[j].colour = indsp->map_colour;
			_legend_from_industries[j].type = ind;
			_legend_from_industries[j].show_on_map = true;
			_legend_from_industries[j].col_break = false;
			_legend_from_industries[j].end = false;

			/* Store widget number for this industry type. */
			_industry_to_list_pos[ind] = j;
			j++;
		}
	}
	/* Terminate the list */
	_legend_from_industries[j].end = true;

	/* Store number of enabled industries */
	_smallmap_industry_count = j;
}

static LegendAndColour _legend_linkstats[NUM_CARGO + NUM_STATS + 1];

/**
 * Populate legend table for the link stat view.
 */
void BuildLinkStatsLegend()
{
	/* Clear the legend */
	memset(_legend_linkstats, 0, sizeof(_legend_linkstats));

	uint i = 0;
	for (; i < _sorted_cargo_specs_size; ++i) {
		const CargoSpec *cs = _sorted_cargo_specs[i];

		_legend_linkstats[i].legend = cs->name;
		_legend_linkstats[i].colour = cs->legend_colour;
		_legend_linkstats[i].type = cs->Index();
		_legend_linkstats[i].show_on_map = true;
	}

	_legend_linkstats[i].col_break = true;

	_smallmap_cargo_count = i;

	/* the colours cannot be resolved before the gfx system is initialized.
	 * So we have to build the legend when creating the window.
	 */
	for (uint st = 0; st < NUM_STATS; ++st) {
		LegendAndColour & legend_entry = _legend_linkstats[i + st];
		switch(st) {
		case STAT_CAPACITY:
			legend_entry.colour = _colour_gradient[COLOUR_WHITE][7];
			legend_entry.legend = STR_SMALLMAP_LEGENDA_CAPACITY;
			legend_entry.show_on_map = true;
			break;
		case STAT_USAGE:
			legend_entry.colour = _colour_gradient[COLOUR_GREY][1];
			legend_entry.legend = STR_SMALLMAP_LEGENDA_USAGE;
			legend_entry.show_on_map = false;
			break;
		case STAT_PLANNED:
			legend_entry.colour = _colour_gradient[COLOUR_RED][5];
			legend_entry.legend = STR_SMALLMAP_LEGENDA_PLANNED;
			legend_entry.show_on_map = true;
			break;
		case STAT_SENT:
			legend_entry.colour = _colour_gradient[COLOUR_YELLOW][5];
			legend_entry.legend = STR_SMALLMAP_LEGENDA_SENT;
			legend_entry.show_on_map = false;
			break;
		case STAT_TEXT:
			legend_entry.colour = _colour_gradient[COLOUR_GREY][7];
			legend_entry.legend = STR_SMALLMAP_LEGENDA_SHOW_TEXT;
			legend_entry.show_on_map = false;
			break;
		case STAT_GRAPH:
			legend_entry.colour = _colour_gradient[COLOUR_GREY][7];
			legend_entry.legend = STR_SMALLMAP_LEGENDA_SHOW_GRAPH;
			legend_entry.show_on_map = true;
			break;
		}
	}

	_legend_linkstats[i + NUM_STATS].end = true;
}

static const LegendAndColour * const _legend_table_old[] = {
	_legend_land_contours_old,
	_legend_vehicles,
	_legend_from_industries,
	_legend_linkstats,
	_legend_routes,
	_legend_vegetation,
	_legend_land_owners,
};

static const LegendAndColour * const _legend_table_extended[] = {
	_legend_land_contours_extended,
	_legend_vehicles,
	_legend_from_industries,
	_legend_linkstats,
	_legend_routes,
	_legend_vegetation,
	_legend_land_owners,
};

#define MKCOLOUR(x)         TO_LE32X(x)

#define MKCOLOUR_XXXX(x)    (MKCOLOUR(0x01010101) * (uint)(x))
#define MKCOLOUR_X0X0(x)    (MKCOLOUR(0x01000100) * (uint)(x))
#define MKCOLOUR_0X0X(x)    (MKCOLOUR(0x00010001) * (uint)(x))
#define MKCOLOUR_0XX0(x)    (MKCOLOUR(0x00010100) * (uint)(x))
#define MKCOLOUR_X00X(x)    (MKCOLOUR(0x01000001) * (uint)(x))

#define MKCOLOUR_XYXY(x, y) (MKCOLOUR_X0X0(x) | MKCOLOUR_0X0X(y))
#define MKCOLOUR_XYYX(x, y) (MKCOLOUR_X00X(x) | MKCOLOUR_0XX0(y))

#define MKCOLOUR_0000       MKCOLOUR_XXXX(0x00)
#define MKCOLOUR_0FF0       MKCOLOUR_0XX0(0xFF)
#define MKCOLOUR_F00F       MKCOLOUR_X00X(0xFF)
#define MKCOLOUR_FFFF       MKCOLOUR_XXXX(0xFF)

/**
 * Colour array for displaying elevation in the smallmap, ordered by height.
 * This is the original array for use when AllowMoreHeightlevels() is false.
 */
static const uint32 _green_map_heights_old[] = {
	MKCOLOUR(0x04dcdcdc), // Action colour, flashing purple. This is for level zero(Not flooded) !! Flooding danger !! Not yet water. (When level -1 will be possible: Will provide for a nice flooding_danger_area_border_flash in combination witch previous colour, similar to the waves at water borders.)
	MKCOLOUR_XXXX(0x5A),
	MKCOLOUR_XYXY(0x5A, 0x5B),
	MKCOLOUR_XXXX(0x5B),
	MKCOLOUR_XYXY(0x5B, 0x5C),
	MKCOLOUR_XXXX(0x5C),
	MKCOLOUR_XYXY(0x5C, 0x5D),
	MKCOLOUR_XXXX(0x5D),
	MKCOLOUR_XYXY(0x5D, 0x5E),
	MKCOLOUR_XXXX(0x5E),
	MKCOLOUR_XYXY(0x5E, 0x5F),
	MKCOLOUR_XXXX(0x5F),
	MKCOLOUR_XYXY(0x5F, 0x1F),
	MKCOLOUR_XXXX(0x1F),
	MKCOLOUR_XYXY(0x1F, 0x27),
	MKCOLOUR_XXXX(0x27),
	MKCOLOUR_XXXX(0x27),
};
assert_compile(lengthof(_green_map_heights_old) == MAX_TILE_HEIGHT_OLD + 2);

/**
 * Height map colours for the green colour scheme, ordered by height.
 * Used when AllowMoreHeightlevels() is true.
 * For the moment the aray is extended to 256 levels.
 */
static const uint32 _green_map_heights_extended[] = {
	/* First two colours are action colours.(First commented out, first we need level -1 (and underwater tunnels)) */
	//MKCOLOUR(0xdcdcdcdc), // Nice flashy colour, darkblue. (Do not use above level 1. (second colour)) (I keep it here to become level -1 ground tile (not flooded) (For now: To see its full effect, use this as second color.Then imagine at level -1.))
	MKCOLOUR(0x04dcdcdc), // Action colour, flashing purple. This is for level zero(Not flooded) !! Flooding danger !! Not yet water. (When level -1 will be possible: Will provide for a nice flooding_danger_area_border_flash in combination witch previous colour, similar to the waves at water borders.)
	MKCOLOUR(0x59595958), // height 1
	MKCOLOUR(0x59595958), // height 2
	MKCOLOUR(0X59595959), // height 3
	MKCOLOUR(0X59595959), // height 4
	MKCOLOUR(0X5959595A), // height 5
	MKCOLOUR(0X5959595A), // height 6
	MKCOLOUR(0X59595A59), // height 7
	MKCOLOUR(0X59595A59), // height 8
	MKCOLOUR(0X59595A5A), // height 9
	MKCOLOUR(0X59595A5A), // height 10
	MKCOLOUR(0X595A5959), // height 11
	MKCOLOUR(0X595A5959), // height 12
	MKCOLOUR(0X595A595A), // height 13
	MKCOLOUR(0X595A595A), // height 14
	MKCOLOUR(0X595A5A59), // height 15
	MKCOLOUR(0X595A5A59), // height 16
	MKCOLOUR(0X595A5A5A), // height 17
	MKCOLOUR(0X595A5A5A), // height 18
	MKCOLOUR(0X5A595959), // height 19
	MKCOLOUR(0X5A595959), // height 20
	MKCOLOUR(0X5A59595A), // height 21
	MKCOLOUR(0X5A59595A), // height 22
	MKCOLOUR(0X5A595A59), // height 23
	MKCOLOUR(0X5A595A59), // height 24
	MKCOLOUR(0X5A595A5A), // height 25
	MKCOLOUR(0X5A595A5A), // height 26
	MKCOLOUR(0X5A5A5959), // height 27
	MKCOLOUR(0X5A5A5959), // height 28
	MKCOLOUR(0X5A5A595A), // height 29
	MKCOLOUR(0X5A5A595A), // height 30
	MKCOLOUR(0X5A5A5A59), // height 31
	MKCOLOUR(0X5A5A5A59), // height 32
	MKCOLOUR(0x5A5A5A5A), // height 33 // original smallmap color do not modify
	MKCOLOUR(0x5A5A5A5A), // height 34 // original smallmap color do not modify
	MKCOLOUR(0x5A5A5A5B), // height 35
	MKCOLOUR(0x5A5A5A5B), // height 36
	MKCOLOUR(0x5A5A5B5A), // height 37
	MKCOLOUR(0x5A5A5B5A), // height 38
	MKCOLOUR(0x5A5A5B5B), // height 39
	MKCOLOUR(0x5A5A5B5B), // height 40
	MKCOLOUR(0x5A5B5A5A), // height 41
	MKCOLOUR(0x5A5B5A5A), // height 42
	MKCOLOUR(0x5A5B5A5B), // height 43 // original smallmap color do not modify
	MKCOLOUR(0x5A5B5A5B), // height 44 // original smallmap color do not modify
	MKCOLOUR(0x5A5B5B5A), // height 45
	MKCOLOUR(0x5A5B5B5A), // height 46
	MKCOLOUR(0x5A5B5B5B), // height 47
	MKCOLOUR(0x5A5B5B5B), // height 48
	MKCOLOUR(0x5B5A5A5A), // height 49
	MKCOLOUR(0x5B5A5A5A), // height 50
	MKCOLOUR(0x5B5A5A5B), // height 51
	MKCOLOUR(0x5B5A5A5B), // height 52
	MKCOLOUR(0x5B5A5B5A), // height 53
	MKCOLOUR(0x5B5A5B5A), // height 54
	MKCOLOUR(0x5B5A5B5B), // height 55
	MKCOLOUR(0x5B5A5B5B), // height 56
	MKCOLOUR(0x5B5B5A5A), // height 57
	MKCOLOUR(0x5B5B5A5A), // height 58
	MKCOLOUR(0x5B5B5A5B), // height 59
	MKCOLOUR(0x5B5B5A5B), // height 60
	MKCOLOUR(0x5B5B5B5B), // height 61 // original smallmap color do not modify
	MKCOLOUR(0x5B5B5B5B), // height 62 // original smallmap color do not modify
	MKCOLOUR(0x5B5B5B5C), // height 63
	MKCOLOUR(0x5B5B5B5C), // height 64
	MKCOLOUR(0x5B5B5C5B), // height 65
	MKCOLOUR(0x5B5B5C5B), // height 66
	MKCOLOUR(0x5B5B5C5C), // height 67
	MKCOLOUR(0x5B5B5C5C), // height 68
	MKCOLOUR(0x5B5C5B5B), // height 69
	MKCOLOUR(0x5B5C5B5B), // height 70
	MKCOLOUR(0x5B5C5B5C), // height 71 // original smallmap color do not modify
	MKCOLOUR(0x5B5C5B5C), // height 72 // original smallmap color do not modify
	MKCOLOUR(0x5B5C5C5B), // height 73
	MKCOLOUR(0x5B5C5C5B), // height 74
	MKCOLOUR(0x5B5C5C5C), // height 75
	MKCOLOUR(0x5B5C5C5C), // height 76
	MKCOLOUR(0x5C5B5B5B), // height 77
	MKCOLOUR(0x5C5B5B5B), // height 78
	MKCOLOUR(0x5C5B5B5C), // height 79
	MKCOLOUR(0x5C5B5B5C), // height 80
	MKCOLOUR(0x5C5B5C5B), // height 81
	MKCOLOUR(0x5C5B5C5B), // height 82
	MKCOLOUR(0x5C5B5C5C), // height 83
	MKCOLOUR(0x5C5B5C5C), // height 84
	MKCOLOUR(0x5C5C5B5B), // height 85
	MKCOLOUR(0x5C5C5B5B), // height 86
	MKCOLOUR(0x5C5C5B5C), // height 87
	MKCOLOUR(0x5C5C5B5C), // height 88
	MKCOLOUR(0x5C5C5C5C), // height 89 // original smallmap color do not modify
	MKCOLOUR(0x5C5C5C5C), // height 90 // original smallmap color do not modify
	MKCOLOUR(0x5C5C5C5D), // height 91
	MKCOLOUR(0x5C5C5C5D), // height 92
	MKCOLOUR(0x5C5C5D5C), // height 93
	MKCOLOUR(0x5C5C5D5C), // height 94
	MKCOLOUR(0x5C5C5D5D), // height 95
	MKCOLOUR(0x5C5C5D5D), // height 96
	MKCOLOUR(0x5C5D5C5C), // height 97
	MKCOLOUR(0x5C5D5C5C), // height 98
	MKCOLOUR(0x5C5D5C5D), // height 99 // original smallmap color do not modify
	MKCOLOUR(0x5C5D5C5D), // height 100 // original smallmap color do not modify
	MKCOLOUR(0x5C5D5D5C), // height 101
	MKCOLOUR(0x5C5D5D5C), // height 102
	MKCOLOUR(0x5C5D5D5D), // height 103
	MKCOLOUR(0x5C5D5D5D), // height 104
	MKCOLOUR(0x5D5C5C5C), // height 105
	MKCOLOUR(0x5D5C5C5C), // height 106
	MKCOLOUR(0x5D5C5C5D), // height 107
	MKCOLOUR(0x5D5C5C5D), // height 108
	MKCOLOUR(0x5D5C5D5C), // height 109
	MKCOLOUR(0x5D5C5D5C), // height 110
	MKCOLOUR(0x5D5C5D5D), // height 111
	MKCOLOUR(0x5D5C5D5D), // height 112
	MKCOLOUR(0x5D5D5C5C), // height 113
	MKCOLOUR(0x5D5D5C5C), // height 114
	MKCOLOUR(0x5D5D5C5D), // height 115
	MKCOLOUR(0x5D5D5C5D), // height 116
	MKCOLOUR(0x5D5D5D5D), // height 117 // original smallmap color do not modify
	MKCOLOUR(0x5D5D5D5D), // height 118 // original smallmap color do not modify
	MKCOLOUR(0x5D5D5D5E), // height 119
	MKCOLOUR(0x5D5D5D5E), // height 120
	MKCOLOUR(0x5D5D5E5D), // height 121
	MKCOLOUR(0x5D5D5E5D), // height 122
	MKCOLOUR(0x5D5D5E5E), // height 123
	MKCOLOUR(0x5D5D5E5E), // height 124
	MKCOLOUR(0x5D5E5D5D), // height 125
	MKCOLOUR(0x5D5E5D5D), // height 126
	MKCOLOUR(0x5D5E5D5E), // height 127 // original smallmap color do not modify
	MKCOLOUR(0x5D5E5D5E), // height 128 // original smallmap color do not modify
	MKCOLOUR(0x5D5E5E5D), // height 129
	MKCOLOUR(0x5D5E5E5D), // height 130
	MKCOLOUR(0x5D5E5E5E), // height 131
	MKCOLOUR(0x5D5E5E5E), // height 132
	MKCOLOUR(0x5E5D5D5D), // height 133
	MKCOLOUR(0x5E5D5D5D), // height 134
	MKCOLOUR(0x5E5D5D5E), // height 135
	MKCOLOUR(0x5E5D5D5E), // height 136
	MKCOLOUR(0x5E5D5E5D), // height 137
	MKCOLOUR(0x5E5D5E5D), // height 138
	MKCOLOUR(0x5E5D5E5E), // height 139
	MKCOLOUR(0x5E5D5E5E), // height 140
	MKCOLOUR(0x5E5D5D5D), // height 141
	MKCOLOUR(0x5E5D5D5D), // height 142
	MKCOLOUR(0x5E5D5D5E), // height 143
	MKCOLOUR(0x5E5D5D5E), // height 144
	MKCOLOUR(0x5E5E5E5E), // height 145 // original smallmap color do not modify
	MKCOLOUR(0x5E5E5E5E), // height 146 // original smallmap color do not modify
	MKCOLOUR(0x5E5E5E5F), // height 147
	MKCOLOUR(0x5E5E5E5F), // height 148
	MKCOLOUR(0x5E5E5F5E), // height 149
	MKCOLOUR(0x5E5E5F5E), // height 150
	MKCOLOUR(0x5E5E5F5F), // height 151
	MKCOLOUR(0x5E5E5F5F), // height 152
	MKCOLOUR(0x5E5F5E5E), // height 153
	MKCOLOUR(0x5E5F5E5E), // height 154
	MKCOLOUR(0x5E5F5E5F), // height 155 // original smallmap color do not modify
	MKCOLOUR(0x5E5F5E5F), // height 156 // original smallmap color do not modify
	MKCOLOUR(0x5E5F5F5E), // height 157
	MKCOLOUR(0x5E5F5F5E), // height 158
	MKCOLOUR(0x5E5F5F5F), // height 159
	MKCOLOUR(0x5E5F5F5F), // height 160
	MKCOLOUR(0x5F5E5E5E), // height 161
	MKCOLOUR(0x5F5E5E5E), // height 162
	MKCOLOUR(0x5F5E5E5F), // height 163
	MKCOLOUR(0x5F5E5E5F), // height 164
	MKCOLOUR(0x5F5E5F5E), // height 165
	MKCOLOUR(0x5F5E5F5E), // height 166
	MKCOLOUR(0x5F5E5F5F), // height 167
	MKCOLOUR(0x5F5E5F5F), // height 168
	MKCOLOUR(0x5F5F5E5E), // height 169
	MKCOLOUR(0x5F5F5E5E), // height 170
	MKCOLOUR(0x5F5F5E5F), // height 171
	MKCOLOUR(0x5F5F5E5F), // height 172
	MKCOLOUR(0x5F5F5F5F), // height 173 // original smallmap color do not modify
	MKCOLOUR(0x5F5F5F5F), // height 174 // original smallmap color do not modify
	MKCOLOUR(0x5F5F5F1F), // height 175
	MKCOLOUR(0x5F5F5F1F), // height 176
	MKCOLOUR(0x5F5F1F5F), // height 177
	MKCOLOUR(0x5F5F1F5F), // height 178
	MKCOLOUR(0x5F5F1F1F), // height 179
	MKCOLOUR(0x5F5F1F1F), // height 180
	MKCOLOUR(0x5F1F5F1F), // height 181 // original smallmap color do not modify
	MKCOLOUR(0x5F1F5F1F), // height 182 // original smallmap color do not modify
// pale greens need finetuning ?
	MKCOLOUR(0x5F1F1F1F), // height 183
	MKCOLOUR(0x5F1F1F1F), // height 184
	MKCOLOUR(0x1F5F5F5F), // height 185
	MKCOLOUR(0x1F5F5F5F), // height 186
	MKCOLOUR(0x1F5F5F1F), // height 187
	MKCOLOUR(0x1F5F5F1F), // height 188
	MKCOLOUR(0x1F5F1F5F), // height 189
	MKCOLOUR(0x1F5F1F5F), // height 190
	MKCOLOUR(0x1F5F1F1F), // height 191
	MKCOLOUR(0x1F5F1F1F), // height 192
	MKCOLOUR(0x1F1F5F5F), // height 193
	MKCOLOUR(0x1F1F5F5F), // height 194
	MKCOLOUR(0x1F1F5F1F), // height 195
	MKCOLOUR(0x1F1F5F1F), // height 196
	MKCOLOUR(0x1F1F1F5F), // height 197
	MKCOLOUR(0x1F1F1F5F), // height 198
//fine tune pale greens untill here ?
	MKCOLOUR(0x1F1F1F1F), // height 199 // original smallmap color do not modify
	MKCOLOUR(0x1F1F1F1F), // height 200 // original smallmap color do not modify
	MKCOLOUR(0x1F1F1F27), // height 201
	MKCOLOUR(0x1F1F1F27), // height 202
	MKCOLOUR(0x1F1F271F), // height 203
	MKCOLOUR(0x1F1F271F), // height 204
	MKCOLOUR(0x1F1F2727), // height 205
	MKCOLOUR(0x1F1F2727), // height 206
	MKCOLOUR(0x1F271F1F), // height 207
	MKCOLOUR(0x1F271F1F), // height 208
	MKCOLOUR(0x1F271F27), // height 209 // original smallmap color do not modify
	MKCOLOUR(0x1F271F27), // height 210 // original smallmap color do not modify
	MKCOLOUR(0x1F272727), // height 211
	MKCOLOUR(0x1F272727), // height 212
	MKCOLOUR(0x271F1F1F), // height 213
	MKCOLOUR(0x271F1F1F), // height 214
	MKCOLOUR(0x271F1F27), // height 215
	MKCOLOUR(0x271F1F27), // height 216
	MKCOLOUR(0x271F271F), // height 217
	MKCOLOUR(0x271F271F), // height 218
	MKCOLOUR(0x271F2727), // height 219
	MKCOLOUR(0x271F2727), // height 220
	MKCOLOUR(0x27271F1F), // height 221
	MKCOLOUR(0x27271F1F), // height 222
	MKCOLOUR(0x27271F27), // height 223
	MKCOLOUR(0x27271F27), // height 224
	MKCOLOUR(0x2727271F), // height 225
	MKCOLOUR(0x2727271F), // height 226
	MKCOLOUR(0x27272727), // height 227 // original smallmap color do not modify
	MKCOLOUR(0x27272727), // height 228 // original smallmap color do not modify
    /* Above and below the same color. I know. It was like that before I arrived. I prefer extending over modifying, it stays. */
	MKCOLOUR(0x27272727), // height 229 // original smallmap color do not modify
	MKCOLOUR(0x27272727), // height 230 // original smallmap color do not modify
	/* Purple top */
	MKCOLOUR(0x1F27AF27), // height 231
	MKCOLOUR(0x1F27AF27), // height 232
	MKCOLOUR(0x1F274FAF), // height 233
	MKCOLOUR(0x1F274FAF), // height 234
	MKCOLOUR(0x4F274FAF), // height 235
	MKCOLOUR(0x4F274FAF), // height 236
	MKCOLOUR(0x4FAF1FAF), // height 237
	MKCOLOUR(0x4FAF1FAF), // height 238
	MKCOLOUR(0x4F2727AF), // height 239
	MKCOLOUR(0x4F2727AF), // height 240
	MKCOLOUR(0x4F27AF27), // height 241
	MKCOLOUR(0x4F27AF27), // height 242
	MKCOLOUR(0x4F27AFAF), // height 243
	MKCOLOUR(0x4F27AFAF), // height 244
	MKCOLOUR(0x4FAF2727), // height 245
	MKCOLOUR(0x4FAF2727), // height 246
	MKCOLOUR(0x4FAF27AF), // height 247
	MKCOLOUR(0x4FAF27AF), // height 248
	MKCOLOUR(0x4FAFAF27), // height 249
	MKCOLOUR(0x4FAFAF27), // height 250
	MKCOLOUR(0x4FAFAFAF), // height 251
	MKCOLOUR(0x4FAFAFAF), // height 252
	MKCOLOUR(0x4FAFAFCF), // height 253
	MKCOLOUR(0x4FAFAFCF), // height 254
	MKCOLOUR(0x4FAFCFAF), // height 255
	MKCOLOUR(0x4FCFAFAF), /* 1 extra color for people not liking the flood_warning feature. */
	/* Flashing test with current parameters no longer needed. */
	//MKCOLOUR(0x04dcdcdc), /* FLASHING TEST (You can use this when going for 512 colours.) */
};
assert_compile(lengthof(_green_map_heights_extended) == MAX_TILE_HEIGHT_EXTENDED + 2);

/**
 * Height map colours for the dark green colour scheme, ordered by height.
 * This is the original array for use when AllowMoreHeightlevels() is false.
 */
static const uint32 _dark_green_map_heights_old[] = {
	MKCOLOUR(0x04dcdcdc), // Action colour, flashing purple. This is for level zero(Not flooded) !! Flooding danger !! Not yet water. (When level -1 will be possible: Will provide for a nice flooding_danger_area_border_flash in combination witch previous colour, similar to the waves at water borders.)
	MKCOLOUR_XXXX(0x60),
	MKCOLOUR_XYXY(0x60, 0x61),
	MKCOLOUR_XXXX(0x61),
	MKCOLOUR_XYXY(0x61, 0x62),
	MKCOLOUR_XXXX(0x62),
	MKCOLOUR_XYXY(0x62, 0x63),
	MKCOLOUR_XXXX(0x63),
	MKCOLOUR_XYXY(0x63, 0x64),
	MKCOLOUR_XXXX(0x64),
	MKCOLOUR_XYXY(0x64, 0x65),
	MKCOLOUR_XXXX(0x65),
	MKCOLOUR_XYXY(0x65, 0x66),
	MKCOLOUR_XXXX(0x66),
	MKCOLOUR_XYXY(0x66, 0x67),
	MKCOLOUR_XXXX(0x67),
	MKCOLOUR_XXXX(0x67),
};
assert_compile(lengthof(_dark_green_map_heights_old) == MAX_TILE_HEIGHT_OLD + 2);

/**
 * Height map colours for the dark green colour scheme, ordered by height.
 * Used when AllowMoreHeightlevels() is true.
 * For the moment the aray is extended to 256 levels.
 */
static const uint32 _dark_green_map_heights_extended[] = {
	/* First two colours are action colours.(First commented out, first we need level -1 (and underwater tunnels)) */
	//MKCOLOUR(0xdcdcdcdc), // Nice flashy colour, darkblue. (Do not use above level 1. (second colour)) (I keep it here to become level -1 ground tile (not flooded) (For now: To see its full effect, use this as second color.Then imagine at level -1.))
	MKCOLOUR(0x04dcdcdc), // Action colour, flashing purple. This is for level zero(Not flooded) !! Flooding danger !! Not yet water. (When level -1 will be possible: Will provide for a nice flooding_danger_area_border_flash in combination witch previous colour, similar to the waves at water borders.)
	MKCOLOUR(0x60606060), // height 1 // original smallmap color do not modify
	MKCOLOUR(0x60606060),
	MKCOLOUR(0x60606061), // height 3
	MKCOLOUR(0x60606061),
	MKCOLOUR(0x60606160), // height 5
	MKCOLOUR(0x60606160),
	MKCOLOUR(0x60606161), // height 7
	MKCOLOUR(0x60606161),
	MKCOLOUR(0x60616060), // height 9
	MKCOLOUR(0x60616060),
	MKCOLOUR(0x60616061), // height 11 // original smallmap color do not modify
	MKCOLOUR(0x60616061),
	MKCOLOUR(0x60616160), // height 13
	MKCOLOUR(0x60616160),
	MKCOLOUR(0x60616161), // height 15
	MKCOLOUR(0x60616161),
	MKCOLOUR(0x61606060), // height 17
	MKCOLOUR(0x61606060),
	MKCOLOUR(0x61606061), // height 19
	MKCOLOUR(0x61606061),
	MKCOLOUR(0x61606160), // height 21
	MKCOLOUR(0x61606160),
	MKCOLOUR(0x61606161), // height 23
	MKCOLOUR(0x61606161),
	MKCOLOUR(0x61616060), // height 25
	MKCOLOUR(0x61616060),
	MKCOLOUR(0x61616061), // height 27
	MKCOLOUR(0x61616061),
	MKCOLOUR(0x61616160), // height 29
	MKCOLOUR(0x61616160),
	MKCOLOUR(0x61616161), // height 31 // original smallmap color do not modify
	MKCOLOUR(0x61616161),
	MKCOLOUR(0x61616162), // height 33
	MKCOLOUR(0x61616162),
	MKCOLOUR(0x61616261), // height 35
	MKCOLOUR(0x61616261),
	MKCOLOUR(0x61616262), // height 37
	MKCOLOUR(0x61616262),
	MKCOLOUR(0x61626161), // height 39
	MKCOLOUR(0x61626161),
	MKCOLOUR(0x61626162), // height 41 // original smallmap color do not modify
	MKCOLOUR(0x61626162),
	MKCOLOUR(0x61626261), // height 43
	MKCOLOUR(0x61626261),
	MKCOLOUR(0x61626262), // height 45
	MKCOLOUR(0x61626262),
	MKCOLOUR(0x62616161), // height 47
	MKCOLOUR(0x62616161),
	MKCOLOUR(0x62616162), // height 49
	MKCOLOUR(0x62616162),
	MKCOLOUR(0x62616261), // height 51
	MKCOLOUR(0x62616261),
	MKCOLOUR(0x62616262), // height 53
	MKCOLOUR(0x62616262),
	MKCOLOUR(0x62626161), // height 55
	MKCOLOUR(0x62626161),
	MKCOLOUR(0x62626162), // height 57
	MKCOLOUR(0x62626162),
	MKCOLOUR(0x62626261), // height 59
	MKCOLOUR(0x62626261),
	MKCOLOUR(0x62626262), // height 61 // original smallmap color do not modify
	MKCOLOUR(0x62626262),
	MKCOLOUR(0x62626263), // height 63
	MKCOLOUR(0x62626263),
	MKCOLOUR(0x62626362), // height 65
	MKCOLOUR(0x62626362),
	MKCOLOUR(0x62626363), // height 67
	MKCOLOUR(0x62626363),
	MKCOLOUR(0x62636262), // height 69
	MKCOLOUR(0x62636262),
	MKCOLOUR(0x62636263), // height 71 // original smallmap color do not modify
	MKCOLOUR(0x62636263),
	MKCOLOUR(0x62636362), // height 73
	MKCOLOUR(0x62636362),
	MKCOLOUR(0x62636363), // height 75
	MKCOLOUR(0x62636363),
	MKCOLOUR(0x63626262), // height 77
	MKCOLOUR(0x63626262),
	MKCOLOUR(0x63626263), // height 79
	MKCOLOUR(0x63626263),
	MKCOLOUR(0x63626362), // height 81
	MKCOLOUR(0x63626362),
	MKCOLOUR(0x63626363), // height 83
	MKCOLOUR(0x63626363),
	MKCOLOUR(0x63636262), // height 85
	MKCOLOUR(0x63636262),
	MKCOLOUR(0x63636263), // height 87
	MKCOLOUR(0x63636263),
	MKCOLOUR(0x63636362), // height 89
	MKCOLOUR(0x63636362),
	MKCOLOUR(0x63636363), // height 91 // original smallmap color do not modify
	MKCOLOUR(0x63636363),
	MKCOLOUR(0x63636364), // height 93
	MKCOLOUR(0x63636364),
	MKCOLOUR(0x63636463), // height 95
	MKCOLOUR(0x63636463),
	MKCOLOUR(0x63636464), // height 97
	MKCOLOUR(0x63636464),
	MKCOLOUR(0x63646363), // height 99
	MKCOLOUR(0x63646363),
	MKCOLOUR(0x63646364), // height 101 // original smallmap color do not modify
	MKCOLOUR(0x63646364),
	MKCOLOUR(0x63646463), // height 103
	MKCOLOUR(0x63646463),
	MKCOLOUR(0x63646464), // height 105
	MKCOLOUR(0x63646464),
	MKCOLOUR(0x64636363), // height 107
	MKCOLOUR(0x64636363),
	MKCOLOUR(0x64636364), // height 109
	MKCOLOUR(0x64636364),
	MKCOLOUR(0x64636463), // height 111
	MKCOLOUR(0x64636463),
	MKCOLOUR(0x64636464), // height 113
	MKCOLOUR(0x64636464),
	MKCOLOUR(0x64646363), // height 115
	MKCOLOUR(0x64646363),
	MKCOLOUR(0x64646364), // height 117
	MKCOLOUR(0x64646364),
	MKCOLOUR(0x64646463), // height 119
	MKCOLOUR(0x64646463),
	MKCOLOUR(0x64646464), // height 121 // original smallmap color do not modify
	MKCOLOUR(0x64646464),
	MKCOLOUR(0x64646465), // height 123
	MKCOLOUR(0x64646465),
	MKCOLOUR(0x64646564), // height 125
	MKCOLOUR(0x64646564),
	MKCOLOUR(0x64646565), // height 127
	MKCOLOUR(0x64646565),
	MKCOLOUR(0x64656464), // height 129
	MKCOLOUR(0x64656464),
	MKCOLOUR(0x64656465), // height 131 // original smallmap color do not modify
	MKCOLOUR(0x64656465),
	MKCOLOUR(0x64656564), // height 133
	MKCOLOUR(0x64656564),
	MKCOLOUR(0x64656565), // height 135
	MKCOLOUR(0x64656565),
	MKCOLOUR(0x65646464), // height 137
	MKCOLOUR(0x65646464),
	MKCOLOUR(0x65646465), // height 139
	MKCOLOUR(0x65646465),
	MKCOLOUR(0x65646564), // height 141
	MKCOLOUR(0x65646564),
	MKCOLOUR(0x65646565), // height 143
	MKCOLOUR(0x65646565),
	MKCOLOUR(0x65656464), // height 145
	MKCOLOUR(0x65656464),
	MKCOLOUR(0x65656465), // height 147
	MKCOLOUR(0x65656465),
	MKCOLOUR(0x65656564), // height 149
	MKCOLOUR(0x65656564),
	MKCOLOUR(0x65656565), // height 151 // original smallmap color do not modify
	MKCOLOUR(0x65656565),
	MKCOLOUR(0x65656566), // height 153
	MKCOLOUR(0x65656566),
	MKCOLOUR(0x65656665), // height 155
	MKCOLOUR(0x65656665),
	MKCOLOUR(0x65656666), // height 157
	MKCOLOUR(0x65656666),
	MKCOLOUR(0x65666565), // height 159
	MKCOLOUR(0x65666565),
	MKCOLOUR(0x65666566), // height 161 // original smallmap color do not modify
	MKCOLOUR(0x65666566),
	MKCOLOUR(0x65666665), // height 163
	MKCOLOUR(0x65666665),
	MKCOLOUR(0x65666666), // height 165
	MKCOLOUR(0x65666666),
	MKCOLOUR(0x66656565), // height 167
	MKCOLOUR(0x66656565),
	MKCOLOUR(0x66656566), // height 169
	MKCOLOUR(0x66656566),
	MKCOLOUR(0x66656665), // height 171
	MKCOLOUR(0x66656665),
	MKCOLOUR(0x66656666), // height 173
	MKCOLOUR(0x66656666),
	MKCOLOUR(0x66666565), // height 175
	MKCOLOUR(0x66666565),
	MKCOLOUR(0x66666566), // height 177
	MKCOLOUR(0x66666566),
	MKCOLOUR(0x66666665), // height 179
	MKCOLOUR(0x66666665),
	MKCOLOUR(0x66666666), // height 181 // original smallmap color do not modify
	MKCOLOUR(0x66666666),
	MKCOLOUR(0x66666667), // height 183
	MKCOLOUR(0x66666667),
	MKCOLOUR(0x66666766), // height 185
	MKCOLOUR(0x66666766),
	MKCOLOUR(0x66666767), // height 187
	MKCOLOUR(0x66666767),
	MKCOLOUR(0x66676666), // height 189
	MKCOLOUR(0x66676666),
	MKCOLOUR(0x66676667), // height 191 // original smallmap color do not modify
	MKCOLOUR(0x66676667),
	MKCOLOUR(0x66676766), // height 193
	MKCOLOUR(0x66676766),
	MKCOLOUR(0x66676767), // height 195
	MKCOLOUR(0x66676767),
	MKCOLOUR(0x67676767), // height 197 // original smallmap color do not modify
	MKCOLOUR(0x67676767),

// TODO: Extend. read: replace dummy (copied) colurs below

//	MKCOLOUR(0x67676768), // browns or something do not use untill ...
//	MKCOLOUR(0x67676868),
//	MKCOLOUR(0x67686868),
//	MKCOLOUR(0x68686868),
//	MKCOLOUR(0x68686869),
//	MKCOLOUR(0x69686869),
//	MKCOLOUR(0x68686969),
//	MKCOLOUR(0x68696969),
//	MKCOLOUR(0x69696969),
//	MKCOLOUR(0x6969696A),
//	MKCOLOUR(0x69A96A6A),
//	MKCOLOUR(0x6A6A6A6A),
//	MKCOLOUR(0x6A6A6A6B),
//	MKCOLOUR(0x6A6A6B6B),
//	MKCOLOUR(0x6A6B6B6B),
//	MKCOLOUR(0x6B6B6B6B), // ... here and probably a little further.

	MKCOLOUR(0x67676767), // height 199
	MKCOLOUR(0x67676767),
	MKCOLOUR(0x67676767), // height 201
	MKCOLOUR(0x67676767),
	MKCOLOUR(0x67676767), // height 203
	MKCOLOUR(0x67676767),
	MKCOLOUR(0x67676767), // height 205
	MKCOLOUR(0x67676767),
	MKCOLOUR(0x67676767), // height 207
	MKCOLOUR(0x67676767),
	MKCOLOUR(0x67676767), // height 209
	MKCOLOUR(0x67676767),
	MKCOLOUR(0x67676767), // height 211
	MKCOLOUR(0x67676767),
	MKCOLOUR(0x67676767), // height 213
	MKCOLOUR(0x67676767),
	MKCOLOUR(0x67676767), // height 215
	MKCOLOUR(0x67676767),
	MKCOLOUR(0x67676767), // height 217
	MKCOLOUR(0x67676767),
	MKCOLOUR(0x67676767), // height 219
	MKCOLOUR(0x67676767),
	MKCOLOUR(0x67676767), // height 221
	MKCOLOUR(0x67676767),
	MKCOLOUR(0x67676767), // height 223
	MKCOLOUR(0x67676767),
	MKCOLOUR(0x67676767), // height 225
	MKCOLOUR(0x67676767),
	MKCOLOUR(0x67676767), // height 227
	MKCOLOUR(0x67676767),
	MKCOLOUR(0x67676767), // height 229
	MKCOLOUR(0x67676767),

// TODO: extend untill here

	/* purple top */
	MKCOLOUR(0x1F27AF27), // height 231
	MKCOLOUR(0x1F27AF27), // height 232
	MKCOLOUR(0x1F274FAF), // height 233
	MKCOLOUR(0x1F274FAF), // height 234
	MKCOLOUR(0x4F274FAF), // height 235
	MKCOLOUR(0x4F274FAF), // height 236
	MKCOLOUR(0x4FAF1FAF), // height 237
	MKCOLOUR(0x4FAF1FAF), // height 238
	MKCOLOUR(0x4F2727AF), // height 239
	MKCOLOUR(0x4F2727AF), // height 240
	MKCOLOUR(0x4F27AF27), // height 241
	MKCOLOUR(0x4F27AF27), // height 242
	MKCOLOUR(0x4F27AFAF), // height 243
	MKCOLOUR(0x4F27AFAF), // height 244
	MKCOLOUR(0x4FAF2727), // height 245
	MKCOLOUR(0x4FAF2727), // height 246
	MKCOLOUR(0x4FAF27AF), // height 247
	MKCOLOUR(0x4FAF27AF), // height 248
	MKCOLOUR(0x4FAFAF27), // height 249
	MKCOLOUR(0x4FAFAF27), // height 250
	MKCOLOUR(0x4FAFAFAF), // height 251
	MKCOLOUR(0x4FAFAFAF), // height 252
	MKCOLOUR(0x4FAFAFCF), // height 253
	MKCOLOUR(0x4FAFAFCF), // height 254
	MKCOLOUR(0x4FAFCFAF), // height 255
	MKCOLOUR(0x4FCFAFAF), /* 1 extra color for people not liking the flood_warning feature. */
	/* Flashing test with current parameters no longer needed. */
	//MKCOLOUR(0x04dcdcdc), /* FLASHING TEST (You can use this when going for 512 colours.) */
};
assert_compile(lengthof(_dark_green_map_heights_extended) == MAX_TILE_HEIGHT_EXTENDED + 2);

/**
 * Height map colours for the violet colour scheme, ordered by height.
 * This is the original array for use when AllowMoreHeightlevels() is false.
 */
static const uint32 _violet_map_heights_old[] = {
	MKCOLOUR(0x04dcdcdc), // Action colour, flashing purple. This is for level zero(Not flooded) !! Flooding danger !! Not yet water. (When level -1 will be possible: Will provide for a nice flooding_danger_area_border_flash in combination witch previous colour, similar to the waves at water borders.)
	MKCOLOUR_XXXX(0x80),
	MKCOLOUR_XYXY(0x80, 0x81),
	MKCOLOUR_XXXX(0x81),
	MKCOLOUR_XYXY(0x81, 0x82),
	MKCOLOUR_XXXX(0x82),
	MKCOLOUR_XYXY(0x82, 0x83),
	MKCOLOUR_XXXX(0x83),
	MKCOLOUR_XYXY(0x83, 0x84),
	MKCOLOUR_XXXX(0x84),
	MKCOLOUR_XYXY(0x84, 0x85),
	MKCOLOUR_XXXX(0x85),
	MKCOLOUR_XYXY(0x85, 0x86),
	MKCOLOUR_XXXX(0x86),
	MKCOLOUR_XYXY(0x86, 0x87),
	MKCOLOUR_XXXX(0x87),
	MKCOLOUR_XXXX(0x87),
};
assert_compile(lengthof(_violet_map_heights_old) == MAX_TILE_HEIGHT_OLD + 2);

/**
 * Height map colours for the violet colour scheme, ordered by height.
 * Used when AllowMoreHeightlevels() is true.
 * For the moment the aray is extended to 256 levels.
 */
static const uint32 _violet_map_heights_extended[] = {
	/* First two colours are action colours.(First commented out, first we need level -1 (and underwater tunnels)) */
	//MKCOLOUR(0xdcdcdcdc), // Nice flashy colour, darkblue. (Do not use above level 1. (second colour)) (I keep it here to become level -1 ground tile (not flooded) (For now: To see its full effect, use this as second color.Then imagine at level -1.))
	MKCOLOUR(0x04dcdcdc), // Action colour, flashing purple. This is for level zero(Not flooded) !! Flooding danger !! Not yet water. (When level -1 will be possible: Will provide for a nice flooding_danger_area_border_flash in combination witch previous colour, similar to the waves at water borders.)
	MKCOLOUR(0x80808080), // height 1 // original smallmap color do not modify
	MKCOLOUR(0x80808080),
	MKCOLOUR(0x80808081), // height 3
	MKCOLOUR(0x80808081),
	MKCOLOUR(0x80808180), // height 5
	MKCOLOUR(0x80808180),
	MKCOLOUR(0x80808181), // height 7
	MKCOLOUR(0x80808181),
	MKCOLOUR(0x80818080), // height 9
	MKCOLOUR(0x80818080),
	MKCOLOUR(0x80818081), // height 11 // original smallmap color do not modify
	MKCOLOUR(0x80818081),
	MKCOLOUR(0x80818180), // height 13
	MKCOLOUR(0x80818180),
	MKCOLOUR(0x80818181), // height 15
	MKCOLOUR(0x80818181),
	MKCOLOUR(0x81808080), // height 17
	MKCOLOUR(0x81808080),
	MKCOLOUR(0x81808081), // height 19
	MKCOLOUR(0x81808081),
	MKCOLOUR(0x81808180), // height 21
	MKCOLOUR(0x81808180),
	MKCOLOUR(0x81808181), // height 23
	MKCOLOUR(0x81808181),
	MKCOLOUR(0x81818080), // height 25
	MKCOLOUR(0x81818080),
	MKCOLOUR(0x81818081), // height 27
	MKCOLOUR(0x81818081),
	MKCOLOUR(0x81818180), // height 29
	MKCOLOUR(0x81818180),
	MKCOLOUR(0x81818181), // height 31 // original smallmap color do not modify
	MKCOLOUR(0x81818181),
	MKCOLOUR(0x81818182), // height 33
	MKCOLOUR(0x81818182),
	MKCOLOUR(0x81818281), // height 35
	MKCOLOUR(0x81818281),
	MKCOLOUR(0x81818282), // height 37
	MKCOLOUR(0x81818282),
	MKCOLOUR(0x81828181), // height 39
	MKCOLOUR(0x81828181),
	MKCOLOUR(0x81828182), // height 41 // original smallmap color do not modify
	MKCOLOUR(0x81828182),
	MKCOLOUR(0x81828281), // height 43
	MKCOLOUR(0x81828281),
	MKCOLOUR(0x81828282), // height 45
	MKCOLOUR(0x81828282),
	MKCOLOUR(0x82818181), // height 47
	MKCOLOUR(0x82818181),
	MKCOLOUR(0x82818182), // height 49
	MKCOLOUR(0x82818182),
	MKCOLOUR(0x82818281), // height 51
	MKCOLOUR(0x82818281),
	MKCOLOUR(0x82818282), // height 53
	MKCOLOUR(0x82818282),
	MKCOLOUR(0x82828181), // height 55
	MKCOLOUR(0x82828181),
	MKCOLOUR(0x82828182), // height 57
	MKCOLOUR(0x82828182),
	MKCOLOUR(0x82828281), // height 59
	MKCOLOUR(0x82828281),
	MKCOLOUR(0x82828282), // height 61 // original smallmap color do not modify
	MKCOLOUR(0x82828282),
	MKCOLOUR(0x82828283), // height 63
	MKCOLOUR(0x82828283),
	MKCOLOUR(0x82828382), // height 65
	MKCOLOUR(0x82828382),
	MKCOLOUR(0x82828383), // height 67
	MKCOLOUR(0x82828383),
	MKCOLOUR(0x82838282), // height 69
	MKCOLOUR(0x82838282),
	MKCOLOUR(0x82838283), // height 71 // original smallmap color do not modify
	MKCOLOUR(0x82838283),
	MKCOLOUR(0x82838382), // height 73
	MKCOLOUR(0x82838382),
	MKCOLOUR(0x82838383), // height 75
	MKCOLOUR(0x82838383),
	MKCOLOUR(0x83828282), // height 77
	MKCOLOUR(0x83828282),
	MKCOLOUR(0x83828283), // height 79
	MKCOLOUR(0x83828283),
	MKCOLOUR(0x83828382), // height 81
	MKCOLOUR(0x83828382),
	MKCOLOUR(0x83828383), // height 83
	MKCOLOUR(0x83828383),
	MKCOLOUR(0x83838282), // height 85
	MKCOLOUR(0x83838282),
	MKCOLOUR(0x83838283), // height 87
	MKCOLOUR(0x83838283),
	MKCOLOUR(0x83838382), // height 89
	MKCOLOUR(0x83838382),
	MKCOLOUR(0x83838383), // height 91 // original smallmap color do not modify
	MKCOLOUR(0x83838383),
	MKCOLOUR(0x83838384), // height 93
	MKCOLOUR(0x83838384),
	MKCOLOUR(0x83838483), // height 95
	MKCOLOUR(0x83838483),
	MKCOLOUR(0x83838484), // height 97
	MKCOLOUR(0x83838484),
	MKCOLOUR(0x83848383), // height 99
	MKCOLOUR(0x83848383),
	MKCOLOUR(0x83848384), // height 101 // original smallmap color do not modify
	MKCOLOUR(0x83848384),
	MKCOLOUR(0x83848483), // height 103
	MKCOLOUR(0x83848483),
	MKCOLOUR(0x83848484), // height 105
	MKCOLOUR(0x83848484),
	MKCOLOUR(0x84838383), // height 107
	MKCOLOUR(0x84838383),
	MKCOLOUR(0x84838384), // height 109
	MKCOLOUR(0x84838384),
	MKCOLOUR(0x84838483), // height 111
	MKCOLOUR(0x84838483),
	MKCOLOUR(0x84838484), // height 113
	MKCOLOUR(0x84838484),
	MKCOLOUR(0x84848383), // height 115
	MKCOLOUR(0x84848383),
	MKCOLOUR(0x84848384), // height 117
	MKCOLOUR(0x84848384),
	MKCOLOUR(0x84848483), // height 119
	MKCOLOUR(0x84848483),
	MKCOLOUR(0x84848484), // height 121 // original smallmap color do not modify
	MKCOLOUR(0x84848484),
	MKCOLOUR(0x84848485), // height 123
	MKCOLOUR(0x84848485),
	MKCOLOUR(0x84848584), // height 125
	MKCOLOUR(0x84848584),
	MKCOLOUR(0x84848585), // height 127
	MKCOLOUR(0x84848585),
	MKCOLOUR(0x84858484), // height 129
	MKCOLOUR(0x84858484),
	MKCOLOUR(0x84858485), // height 131 // original smallmap color do not modify
	MKCOLOUR(0x84858485),
	MKCOLOUR(0x84858584), // height 133
	MKCOLOUR(0x84858584),
	MKCOLOUR(0x84858585), // height 135
	MKCOLOUR(0x84858585),
	MKCOLOUR(0x85848484), // height 137
	MKCOLOUR(0x85848484),
	MKCOLOUR(0x85848485), // height 139
	MKCOLOUR(0x85848485),
	MKCOLOUR(0x85848584), // height 141
	MKCOLOUR(0x85848584),
	MKCOLOUR(0x85848585), // height 143
	MKCOLOUR(0x85848585),
	MKCOLOUR(0x85858484), // height 145
	MKCOLOUR(0x85858484),
	MKCOLOUR(0x85858485), // height 147
	MKCOLOUR(0x85858485),
	MKCOLOUR(0x85858584), // height 149
	MKCOLOUR(0x85858584),
	MKCOLOUR(0x85858585), // height 151 // original smallmap color do not modify
	MKCOLOUR(0x85858585),
	MKCOLOUR(0x85858586), // height 153
	MKCOLOUR(0x85858586),
	MKCOLOUR(0x85858685), // height 155
	MKCOLOUR(0x85858685),
	MKCOLOUR(0x85858686), // height 157
	MKCOLOUR(0x85858686),
	MKCOLOUR(0x85868585), // height 159
	MKCOLOUR(0x85868585),
	MKCOLOUR(0x85868586), // height 161 // original smallmap color do not modify
	MKCOLOUR(0x85868586),
	MKCOLOUR(0x85868685), // height 163
	MKCOLOUR(0x85868685),
	MKCOLOUR(0x85868686), // height 165
	MKCOLOUR(0x85868686),
	MKCOLOUR(0x85868585), // height 167
	MKCOLOUR(0x85868585),
	MKCOLOUR(0x85868586), // height 169
	MKCOLOUR(0x85868586),
	MKCOLOUR(0x85868685), // height 171
	MKCOLOUR(0x85868685),
	MKCOLOUR(0x85868686), // height 173
	MKCOLOUR(0x85868686),
	MKCOLOUR(0x86868585), // height 175
	MKCOLOUR(0x86868585),
	MKCOLOUR(0x86868586), // height 177
	MKCOLOUR(0x86868586),
	MKCOLOUR(0x86868685), // height 179
	MKCOLOUR(0x86868685),
	MKCOLOUR(0x86868686), // height 181 // original smallmap color do not modify
	MKCOLOUR(0x86868686),
	MKCOLOUR(0x86868687), // height 183
	MKCOLOUR(0x86868687),
	MKCOLOUR(0x86868786), // height 185
	MKCOLOUR(0x86868786),
	MKCOLOUR(0x86868787), // height 187
	MKCOLOUR(0x86868787),
	MKCOLOUR(0x86878686), // height 189
	MKCOLOUR(0x86878686),
	MKCOLOUR(0x86878687), // height 191 // original smallmap color do not modify
	MKCOLOUR(0x86878687),
	MKCOLOUR(0x86878786), // height 193
	MKCOLOUR(0x86878786),
	MKCOLOUR(0x86878787), // height 195
	MKCOLOUR(0x86878787),
	MKCOLOUR(0x87868686), // height 197
	MKCOLOUR(0x87868686),
	MKCOLOUR(0x87868687), // height 199
	MKCOLOUR(0x87868687),
	MKCOLOUR(0x87868786), // height 201
	MKCOLOUR(0x87868786),
	MKCOLOUR(0x87868787), // height 203
	MKCOLOUR(0x87868787),
	MKCOLOUR(0x87878686), // height 205
	MKCOLOUR(0x87878686),
	MKCOLOUR(0x87878687), // height 207
	MKCOLOUR(0x87878687),
	MKCOLOUR(0x87878786), // height 209
	MKCOLOUR(0x87878786),
	MKCOLOUR(0x87878787), // height 211 // original smallmap color do not modify
	MKCOLOUR(0x87878787),
	MKCOLOUR(0x87878787), // height 213 // original smallmap color do not modify
	MKCOLOUR(0x87878787),

// TODO: Extend. read: replace dummy (copied) colurs below

//	MKCOLOUR(0x87878788), // don't use greys/blacks
//	MKCOLOUR(0x87878788),
//	MKCOLOUR(0x87878887),
//	MKCOLOUR(0x87878887),
//	MKCOLOUR(0x87878888),
//	MKCOLOUR(0x87878888),
//	MKCOLOUR(0x87888787),
//	MKCOLOUR(0x87888787),
//	MKCOLOUR(0x87888788),
//	MKCOLOUR(0x87888788),
//	MKCOLOUR(0x87888887),
//	MKCOLOUR(0x87888887),
//	MKCOLOUR(0x87888888),
//	MKCOLOUR(0x87888888),
//	MKCOLOUR(0x88878787),
//	MKCOLOUR(0x88878788),
//	MKCOLOUR(0x88878887),
//	MKCOLOUR(0x88878888),
//	MKCOLOUR(0x88888787),
//	MKCOLOUR(0x88888788),
//	MKCOLOUR(0x88888887),
//	MKCOLOUR(0x88888888), // dont't use untill here probaby a little further too

	MKCOLOUR(0x87878787), // height 215
	MKCOLOUR(0x87878787),
	MKCOLOUR(0x87878787), // height 217
	MKCOLOUR(0x87878787),
	MKCOLOUR(0x87878787), // height 219
	MKCOLOUR(0x87878787),
	MKCOLOUR(0x87878787), // height 221
	MKCOLOUR(0x87878787),
	MKCOLOUR(0x87878787), // height 223
	MKCOLOUR(0x87878787),
	MKCOLOUR(0x87878787), // height 225
	MKCOLOUR(0x87878787),
	MKCOLOUR(0x87878787), // height 227
	MKCOLOUR(0x87878787),
	MKCOLOUR(0x87878787), // height 229
	MKCOLOUR(0x87878787),

// TODO: extend untill here

	/* purple top */
	MKCOLOUR(0x1F27AF27), // height 231
	MKCOLOUR(0x1F27AF27), // height 232
	MKCOLOUR(0x1F274FAF), // height 233
	MKCOLOUR(0x1F274FAF), // height 234
	MKCOLOUR(0x4F274FAF), // height 235
	MKCOLOUR(0x4F274FAF), // height 236
	MKCOLOUR(0x4FAF1FAF), // height 237
	MKCOLOUR(0x4FAF1FAF), // height 238
	MKCOLOUR(0x4F2727AF), // height 239
	MKCOLOUR(0x4F2727AF), // height 240
	MKCOLOUR(0x4F27AF27), // height 241
	MKCOLOUR(0x4F27AF27), // height 242
	MKCOLOUR(0x4F27AFAF), // height 243
	MKCOLOUR(0x4F27AFAF), // height 244
	MKCOLOUR(0x4FAF2727), // height 245
	MKCOLOUR(0x4FAF2727), // height 246
	MKCOLOUR(0x4FAF27AF), // height 247
	MKCOLOUR(0x4FAF27AF), // height 248
	MKCOLOUR(0x4FAFAF27), // height 249
	MKCOLOUR(0x4FAFAF27), // height 250
	MKCOLOUR(0x4FAFAFAF), // height 251
	MKCOLOUR(0x4FAFAFAF), // height 252
	MKCOLOUR(0x4FAFAFCF), // height 253
	MKCOLOUR(0x4FAFAFCF), // height 254
	MKCOLOUR(0x4FAFCFAF), // height 255
	MKCOLOUR(0x4FCFAFAF), /* 1 extra color for people not liking the flood_warning feature. */
	/* Flashing test with current parameters no longer needed. */
	//MKCOLOUR(0x04dcdcdc), /* FLASHING TEST (You can use this when going for 512 colours.) */
};
assert_compile(lengthof(_violet_map_heights_extended) == MAX_TILE_HEIGHT_EXTENDED + 2);

/**
 * Colour Coding for Stuck Counter
 */
static const uint32 _stuck_counter_colours[] = {
	MKCOLOUR(0xD0D0D0D0),
	MKCOLOUR(0xCECECECE),
	MKCOLOUR(0xBFBFBFBF),
	MKCOLOUR(0xBDBDBDBD),
	MKCOLOUR(0xBABABABA),
	MKCOLOUR(0xB8B8B8B8),
	MKCOLOUR(0xB6B6B6B6),
	MKCOLOUR(0xB4B4B4B4),
};
assert_compile(lengthof(_stuck_counter_colours) == 8);

/** Colour scheme of the smallmap. */
struct SmallMapColourScheme {
	const uint32 *height_colours; ///< Colour of each level in a heightmap.
	uint32 default_colour;        ///< Default colour of the land.
};

/** Available colour schemes for height maps. (original) */
static const SmallMapColourScheme _heightmap_schemes_old[] = {
	{_green_map_heights_old,      MKCOLOUR_XXXX(0x54)}, ///< Green colour scheme.
	{_dark_green_map_heights_old, MKCOLOUR_XXXX(0x62)}, ///< Dark green colour scheme.
	{_violet_map_heights_old,     MKCOLOUR_XXXX(0x82)}, ///< Violet colour scheme.
};

/** Available colour schemes for height maps. (in case of AllowMoreHeightlevels() ) */
static const SmallMapColourScheme _heightmap_schemes_extended[] = {
	{_green_map_heights_extended,      MKCOLOUR(0x54545454)}, ///< Green colour scheme.
	{_dark_green_map_heights_extended, MKCOLOUR(0x62626262)}, ///< Dark green colour scheme.
	{_violet_map_heights_extended,     MKCOLOUR(0x82828282)}, ///< Violet colour scheme.
};

/**
 * (Re)build the colour tables for the legends.
 */
void BuildLandLegend()
{
	if (AllowMoreHeightlevels()) {
		for (LegendAndColour *lc = _legend_land_contours_extended; lc->legend == STR_TINY_BLACK_HEIGHT; lc++) {
			lc->colour = _heightmap_schemes_extended[_settings_client.gui.smallmap_land_colour].height_colours[lc->height];
		}
	} else {
		for (LegendAndColour *lc = _legend_land_contours_old; lc->legend == STR_TINY_BLACK_HEIGHT; lc++) {
			lc->colour = _heightmap_schemes_old[_settings_client.gui.smallmap_land_colour].height_colours[lc->height];
		}
	}
}

/**
 * Completes the array for the owned property legend.
 */
void BuildOwnerLegend()
{
	if (AllowMoreHeightlevels()) {
		_legend_land_owners[1].colour = _heightmap_schemes_extended[_settings_client.gui.smallmap_land_colour].default_colour;
	} else {
		_legend_land_owners[1].colour = _heightmap_schemes_old[_settings_client.gui.smallmap_land_colour].default_colour;
	}

	int i = NUM_NO_COMPANY_ENTRIES;
	const Company *c;
	FOR_ALL_COMPANIES(c) {
		_legend_land_owners[i].colour = _colour_gradient[c->colour][5];
		_legend_land_owners[i].company = c->index;
		_legend_land_owners[i].show_on_map = true;
		_legend_land_owners[i].col_break = false;
		_legend_land_owners[i].end = false;
		_company_to_list_pos[c->index] = i;
		i++;
	}

	/* Terminate the list */
	_legend_land_owners[i].end = true;

	/* Store maximum amount of owner legend entries. */
	_smallmap_company_count = i;
}

struct AndOr {
	uint32 mor;
	uint32 mand;
};

static inline uint32 ApplyMask(uint32 colour, const AndOr *mask)
{
	return (colour & mask->mand) | mask->mor;
}

/** Colour masks for "Contour" and "Routes" modes. */
static const AndOr _smallmap_contours_andor[] = {
	{MKCOLOUR_0000               , MKCOLOUR_FFFF}, // MP_CLEAR
	{MKCOLOUR_0XX0(PC_GREY      ), MKCOLOUR_F00F}, // MP_RAILWAY
	{MKCOLOUR_0XX0(PC_BLACK     ), MKCOLOUR_F00F}, // MP_ROAD
	{MKCOLOUR_0XX0(PC_DARK_RED  ), MKCOLOUR_F00F}, // MP_HOUSE
	{MKCOLOUR_0000               , MKCOLOUR_FFFF}, // MP_TREES
	{MKCOLOUR_XXXX(PC_LIGHT_BLUE), MKCOLOUR_0000}, // MP_STATION
	{MKCOLOUR_XXXX(PC_WATER     ), MKCOLOUR_0000}, // MP_WATER
	{MKCOLOUR_0000               , MKCOLOUR_FFFF}, // MP_VOID
	{MKCOLOUR_XXXX(PC_DARK_RED  ), MKCOLOUR_0000}, // MP_INDUSTRY
	{MKCOLOUR_0000               , MKCOLOUR_FFFF}, // MP_TUNNELBRIDGE
	{MKCOLOUR_0XX0(PC_DARK_RED  ), MKCOLOUR_F00F}, // MP_OBJECT
	{MKCOLOUR_0XX0(PC_GREY      ), MKCOLOUR_F00F},
};

/** Colour masks for "Vehicles", "Industry", and "Vegetation" modes. */
static const AndOr _smallmap_vehicles_andor[] = {
	{MKCOLOUR_0000               , MKCOLOUR_FFFF}, // MP_CLEAR
	{MKCOLOUR_0XX0(PC_BLACK     ), MKCOLOUR_F00F}, // MP_RAILWAY
	{MKCOLOUR_0XX0(PC_BLACK     ), MKCOLOUR_F00F}, // MP_ROAD
	{MKCOLOUR_0XX0(PC_DARK_RED  ), MKCOLOUR_F00F}, // MP_HOUSE
	{MKCOLOUR_0000               , MKCOLOUR_FFFF}, // MP_TREES
	{MKCOLOUR_0XX0(PC_BLACK     ), MKCOLOUR_F00F}, // MP_STATION
	{MKCOLOUR_XXXX(PC_WATER     ), MKCOLOUR_0000}, // MP_WATER
	{MKCOLOUR_0000               , MKCOLOUR_FFFF}, // MP_VOID
	{MKCOLOUR_XXXX(PC_DARK_RED  ), MKCOLOUR_0000}, // MP_INDUSTRY
	{MKCOLOUR_0000               , MKCOLOUR_FFFF}, // MP_TUNNELBRIDGE
	{MKCOLOUR_0XX0(PC_DARK_RED  ), MKCOLOUR_F00F}, // MP_OBJECT
	{MKCOLOUR_0XX0(PC_BLACK     ), MKCOLOUR_F00F},
};

/** Mapping of tile type to importance of the tile (higher number means more interesting to show). */
static const byte _tiletype_importance[] = {
	2, // MP_CLEAR
	8, // MP_RAILWAY
	7, // MP_ROAD
	5, // MP_HOUSE
	2, // MP_TREES
	9, // MP_STATION
	2, // MP_WATER
	1, // MP_VOID
	6, // MP_INDUSTRY
	8, // MP_TUNNELBRIDGE
	2, // MP_OBJECT
	0,
};


static inline TileType GetEffectiveTileType(TileIndex tile)
{
	TileType t = GetTileType(tile);

	if (t == MP_TUNNELBRIDGE) {
		TransportType tt = GetTunnelBridgeTransportType(tile);

		switch (tt) {
			case TRANSPORT_RAIL: t = MP_RAILWAY; break;
			case TRANSPORT_ROAD: t = MP_ROAD;    break;
			default:             t = MP_WATER;   break;
		}
	}
	return t;
}

/**
 * Return the colour a tile would be displayed with in the small map in mode "Contour".
 * @param tile The tile of which we would like to get the colour.
 * @param t    Effective tile type of the tile (see #GetEffectiveTileType).
 * @return The colour of tile in the small map in mode "Contour"
 */
static inline uint32 GetSmallMapContoursPixels(TileIndex tile, TileType t)
{
	uint tile_height = TileHeight(tile);

	if (_settings_client.gui.smallmap_land_colour == 0) {
		if (AllowMoreHeightlevels()) {
			if(_settings_client.gui.smallmap_flood_warning) {
				return ApplyMask(_green_map_heights_extended[tile_height], &_smallmap_contours_andor[t]);
			} else {
				return ApplyMask(_green_map_heights_extended[tile_height + 1], &_smallmap_contours_andor[t]);
			}
		} else {
			if(_settings_client.gui.smallmap_flood_warning) {
				return ApplyMask(_green_map_heights_old[tile_height], &_smallmap_contours_andor[t]);
			} else {
				return ApplyMask(_green_map_heights_old[tile_height + 1], &_smallmap_contours_andor[t]);
			}
		}
	} else if (_settings_client.gui.smallmap_land_colour == 1) {
		if (AllowMoreHeightlevels()) {
			if(_settings_client.gui.smallmap_flood_warning) {
				return ApplyMask(_dark_green_map_heights_extended[tile_height], &_smallmap_contours_andor[t]);
			} else {
				return ApplyMask(_dark_green_map_heights_extended[tile_height + 1], &_smallmap_contours_andor[t]);
			}
		} else {
			if(_settings_client.gui.smallmap_flood_warning) {
				return ApplyMask(_dark_green_map_heights_old[tile_height], &_smallmap_contours_andor[t]);
			} else {
				return ApplyMask(_dark_green_map_heights_old[tile_height + 1], &_smallmap_contours_andor[t]);
			}
		}
	} else {
		if (AllowMoreHeightlevels()) {
			if(_settings_client.gui.smallmap_flood_warning) {
				return ApplyMask(_violet_map_heights_extended[tile_height], &_smallmap_contours_andor[t]);
			} else {
				return ApplyMask(_violet_map_heights_extended[tile_height + 1], &_smallmap_contours_andor[t]);
			}
		} else {
			if(_settings_client.gui.smallmap_flood_warning) {
				return ApplyMask(_violet_map_heights_old[tile_height], &_smallmap_contours_andor[t]);
			} else {
				return ApplyMask(_violet_map_heights_old[tile_height + 1], &_smallmap_contours_andor[t]);
			}
		}
	}
}

/**
 * Return the colour a tile would be displayed with in the small map in mode "Vehicles".
 *
 * @param tile The tile of which we would like to get the colour.
 * @param t    Effective tile type of the tile (see #GetEffectiveTileType).
 * @return The colour of tile in the small map in mode "Vehicles"
 */
static inline uint32 GetSmallMapVehiclesPixels(TileIndex tile, TileType t)
{
	if (AllowMoreHeightlevels()) {
		const SmallMapColourScheme *cs = &_heightmap_schemes_extended[_settings_client.gui.smallmap_land_colour];
		return ApplyMask(cs->default_colour, &_smallmap_vehicles_andor[t]);
	} else {
		const SmallMapColourScheme *cs = &_heightmap_schemes_old[_settings_client.gui.smallmap_land_colour];
		return ApplyMask(cs->default_colour, &_smallmap_vehicles_andor[t]);
	}
}

/**
 * Return the colour a tile would be displayed with in the small map in mode "Industries".
 *
 * @param tile The tile of which we would like to get the colour.
 * @param t    Effective tile type of the tile (see #GetEffectiveTileType).
 * @return The colour of tile in the small map in mode "Industries"
 */
static inline uint32 GetSmallMapIndustriesPixels(TileIndex tile, TileType t)
{
	if (t == MP_INDUSTRY) {
		/* If industry is allowed to be seen, use its colour on the map */
		if (_legend_from_industries[_industry_to_list_pos[Industry::GetByTile(tile)->type]].show_on_map) {
			return GetIndustrySpec(Industry::GetByTile(tile)->type)->map_colour * 0x01010101;
		} else {
			/* Otherwise, return the colour which will make it disappear */
			t = (IsTileOnWater(tile) ? MP_WATER : MP_CLEAR);
		}
	}

	if (_settings_client.gui.smallmap_land_colour == 0) {
		if (AllowMoreHeightlevels()) {
			if(_settings_client.gui.smallmap_flood_warning) {
				return ApplyMask(_smallmap_show_heightmap ? _green_map_heights_extended[TileHeight(tile)] : MKCOLOUR(0x54545454), &_smallmap_vehicles_andor[t]);
			} else {
				return ApplyMask(_smallmap_show_heightmap ? _green_map_heights_extended[TileHeight(tile) + 1] : MKCOLOUR(0x54545454), &_smallmap_vehicles_andor[t]);
			}
		} else {
			if(_settings_client.gui.smallmap_flood_warning) {
				return ApplyMask(_smallmap_show_heightmap ? _green_map_heights_old[TileHeight(tile)] : MKCOLOUR(0x54545454), &_smallmap_vehicles_andor[t]);
			} else {
				return ApplyMask(_smallmap_show_heightmap ? _green_map_heights_old[TileHeight(tile) + 1] : MKCOLOUR(0x54545454), &_smallmap_vehicles_andor[t]);
			}
		}
	} else if (_settings_client.gui.smallmap_land_colour == 1) {
		if (AllowMoreHeightlevels()) {
			if(_settings_client.gui.smallmap_flood_warning) {
				return ApplyMask(_smallmap_show_heightmap ? _dark_green_map_heights_extended[TileHeight(tile)] : MKCOLOUR(0x62626262), &_smallmap_vehicles_andor[t]);
			} else {
				return ApplyMask(_smallmap_show_heightmap ? _dark_green_map_heights_extended[TileHeight(tile) + 1] : MKCOLOUR(0x62626262), &_smallmap_vehicles_andor[t]);
			}
		} else {
			if(_settings_client.gui.smallmap_flood_warning) {
				return ApplyMask(_smallmap_show_heightmap ? _dark_green_map_heights_old[TileHeight(tile)] : MKCOLOUR(0x62626262), &_smallmap_vehicles_andor[t]);
			} else {
				return ApplyMask(_smallmap_show_heightmap ? _dark_green_map_heights_old[TileHeight(tile) + 1] : MKCOLOUR(0x62626262), &_smallmap_vehicles_andor[t]);
			}
		}
	} else {
		if (AllowMoreHeightlevels()) {
			if(_settings_client.gui.smallmap_flood_warning) {
				return ApplyMask(_smallmap_show_heightmap ? _violet_map_heights_extended[TileHeight(tile)] : MKCOLOUR(0x82828282), &_smallmap_vehicles_andor[t]);
			} else {
				return ApplyMask(_smallmap_show_heightmap ? _violet_map_heights_extended[TileHeight(tile) + 1] : MKCOLOUR(0x82828282), &_smallmap_vehicles_andor[t]);
			}
		} else {
			if(_settings_client.gui.smallmap_flood_warning) {
				return ApplyMask(_smallmap_show_heightmap ? _violet_map_heights_old[TileHeight(tile)] : MKCOLOUR(0x82828282), &_smallmap_vehicles_andor[t]);
			} else {
				return ApplyMask(_smallmap_show_heightmap ? _violet_map_heights_old[TileHeight(tile) + 1] : MKCOLOUR(0x82828282), &_smallmap_vehicles_andor[t]);
			}
		}
	}
}

/**
 * Return the colour a tile would be displayed with in the small map in mode "Routes".
 *
 * @param tile The tile of which we would like to get the colour.
 * @param t    Effective tile type of the tile (see #GetEffectiveTileType).
 * @return The colour of tile  in the small map in mode "Routes"
 */
static inline uint32 GetSmallMapStuckRoutesPixels(TileIndex tile, TileType t)
{
	if (t == MP_STATION) {
		switch (GetStationType(tile)) {
			case STATION_RAIL:    return MKCOLOUR(0x56565656);
			case STATION_AIRPORT: return MKCOLOUR(0xB8B8B8B8);
			case STATION_TRUCK:   return MKCOLOUR(0xC2C2C2C2);
			case STATION_BUS:     return MKCOLOUR(0xBFBFBFBF);
			case STATION_DOCK:    return MKCOLOUR(0x98989898);
			default:              return MKCOLOUR(0xFFFFFFFF);
		}
	} else if (t == MP_RAILWAY) {
		byte c = GetStuckCounter(tile);
		if (c==0) return 0;
		return _stuck_counter_colours[c/32];
	}

	/* Ground colour */
	if (AllowMoreHeightlevels()) {
		const SmallMapColourScheme *cs = &_heightmap_schemes_extended[_settings_client.gui.smallmap_land_colour];
		return ApplyMask(cs->default_colour, &_smallmap_contours_andor[t]);
	} else {
		const SmallMapColourScheme *cs = &_heightmap_schemes_old[_settings_client.gui.smallmap_land_colour];
		return ApplyMask(cs->default_colour, &_smallmap_contours_andor[t]);
	}
}

/**
 * Return the colour a tile would be displayed with in the small map in mode "link stats" while showing height is disabled.
 *
 * @param tile The tile of which we would like to get the colour.
 * @param t    Effective tile type of the tile (see #GetEffectiveTileType).
 * @return The colour of tile  in the small map in mode "Routes"
 */
static inline uint32 GetSmallMapRoutesPixels(TileIndex tile, TileType t)
{
	if (t == MP_STATION) {
		switch (GetStationType(tile)) {
			case STATION_RAIL:    return MKCOLOUR_XXXX(PC_VERY_DARK_BROWN);
			case STATION_AIRPORT: return MKCOLOUR_XXXX(PC_RED);
			case STATION_TRUCK:   return MKCOLOUR_XXXX(PC_ORANGE);
			case STATION_BUS:     return MKCOLOUR_XXXX(PC_YELLOW);
			case STATION_DOCK:    return MKCOLOUR_XXXX(PC_LIGHT_BLUE);
			default:              return MKCOLOUR_FFFF;
		}
	} else if (t == MP_RAILWAY) {
		AndOr andor = {
			MKCOLOUR_0XX0(GetRailTypeInfo(GetRailType(tile))->map_colour),
			_smallmap_contours_andor[t].mand
		};

		if (AllowMoreHeightlevels()) {
			const SmallMapColourScheme *cs = &_heightmap_schemes_extended[_settings_client.gui.smallmap_land_colour];
			return ApplyMask(cs->default_colour, &andor);
		} else {
			const SmallMapColourScheme *cs = &_heightmap_schemes_old[_settings_client.gui.smallmap_land_colour];
			return ApplyMask(cs->default_colour, &andor);
		}
	}

	/* Ground colour */
	if (AllowMoreHeightlevels()) {
		const SmallMapColourScheme *cs = &_heightmap_schemes_extended[_settings_client.gui.smallmap_land_colour];
		return ApplyMask(cs->default_colour, &_smallmap_contours_andor[t]);
	} else {
		const SmallMapColourScheme *cs = &_heightmap_schemes_old[_settings_client.gui.smallmap_land_colour];
		return ApplyMask(cs->default_colour, &_smallmap_contours_andor[t]);
	}
}

/**
 * Return the colour a tile would be displayed with in the small map in mode "link stats".
 *
 * @param tile The tile of which we would like to get the colour.
 * @param t    Effective tile type of the tile (see #GetEffectiveTileType).
 * @return The colour of tile in the small map in mode "link stats"
 */
static inline uint32 GetSmallMapLinkStatsPixels(TileIndex tile, TileType t)
{
	return _smallmap_show_heightmap ? GetSmallMapContoursPixels(tile, t) : GetSmallMapRoutesPixels(tile, t);
}

static const uint32 _vegetation_clear_bits[] = {
	MKCOLOUR_XXXX(PC_GRASS_LAND), ///< full grass
	MKCOLOUR_XXXX(PC_ROUGH_LAND), ///< rough land
	MKCOLOUR_XXXX(PC_GREY),       ///< rocks
	MKCOLOUR_XXXX(PC_FIELDS),     ///< fields
	MKCOLOUR_XXXX(PC_LIGHT_BLUE), ///< snow
	MKCOLOUR_XXXX(PC_ORANGE),     ///< desert
	MKCOLOUR_XXXX(PC_GRASS_LAND), ///< unused
	MKCOLOUR_XXXX(PC_GRASS_LAND), ///< unused
};

/**
 * Return the colour a tile would be displayed with in the smallmap in mode "Vegetation".
 *
 * @param tile The tile of which we would like to get the colour.
 * @param t    Effective tile type of the tile (see #GetEffectiveTileType).
 * @return The colour of tile  in the smallmap in mode "Vegetation"
 */
static inline uint32 GetSmallMapVegetationPixels(TileIndex tile, TileType t)
{
	switch (t) {
		case MP_CLEAR:
			return (IsClearGround(tile, CLEAR_GRASS) && GetClearDensity(tile) < 3) ? MKCOLOUR_XXXX(PC_BARE_LAND) : _vegetation_clear_bits[GetClearGround(tile)];

		case MP_INDUSTRY:
			return GetIndustrySpec(Industry::GetByTile(tile)->type)->check_proc == CHECK_FOREST ? MKCOLOUR_XXXX(PC_GREEN) : MKCOLOUR_XXXX(PC_DARK_RED);

		case MP_TREES:
			if (GetTreeGround(tile) == TREE_GROUND_SNOW_DESERT || GetTreeGround(tile) == TREE_GROUND_ROUGH_SNOW) {
				return (_settings_game.game_creation.landscape == LT_ARCTIC) ? MKCOLOUR_XYYX(PC_LIGHT_BLUE, PC_TREES) : MKCOLOUR_XYYX(PC_ORANGE, PC_TREES);
			}
			return MKCOLOUR_XYYX(PC_GRASS_LAND, PC_TREES);

		default:
			return ApplyMask(MKCOLOUR_XXXX(PC_GRASS_LAND), &_smallmap_vehicles_andor[t]);
	}
}

/**
 * Return the colour a tile would be displayed with in the small map in mode "Owner".
 *
 * @param tile The tile of which we would like to get the colour.
 * @param t    Effective tile type of the tile (see #GetEffectiveTileType).
 * @return The colour of tile in the small map in mode "Owner"
 */
static inline uint32 GetSmallMapOwnerPixels(TileIndex tile, TileType t)
{
	Owner o;

	switch (t) {
		case MP_INDUSTRY: return MKCOLOUR_XXXX(PC_DARK_GREY);
		case MP_HOUSE:    return MKCOLOUR_XXXX(PC_DARK_RED);
		default:          o = GetTileOwner(tile); break;
		/* FIXME: For MP_ROAD there are multiple owners.
		 * GetTileOwner returns the rail owner (level crossing) resp. the owner of ROADTYPE_ROAD (normal road),
		 * even if there are no ROADTYPE_ROAD bits on the tile.
		 */
	}

	if ((o < MAX_COMPANIES && !_legend_land_owners[_company_to_list_pos[o]].show_on_map) || o == OWNER_NONE || o == OWNER_WATER) {
		if (t == MP_WATER) return MKCOLOUR_XXXX(PC_WATER);
		if (AllowMoreHeightlevels()) {
			const SmallMapColourScheme *cs = &_heightmap_schemes_extended[_settings_client.gui.smallmap_land_colour];
			if(_settings_client.gui.smallmap_flood_warning) {
				return _smallmap_show_heightmap ? cs->height_colours[TileHeight(tile)] : cs->default_colour;
			} else {
				return _smallmap_show_heightmap ? cs->height_colours[TileHeight(tile) + 1] : cs->default_colour;

			}
		} else {
			const SmallMapColourScheme *cs = &_heightmap_schemes_old[_settings_client.gui.smallmap_land_colour];
			if(_settings_client.gui.smallmap_flood_warning) {
				return _smallmap_show_heightmap ? cs->height_colours[TileHeight(tile)] : cs->default_colour;
			} else {
				return _smallmap_show_heightmap ? cs->height_colours[TileHeight(tile) + 1] : cs->default_colour;
			}
		}
	} else if (o == OWNER_TOWN) {
		return MKCOLOUR_XXXX(PC_DARK_RED);
	}

	return MKCOLOUR_XXXX(_legend_land_owners[_company_to_list_pos[o]].colour);
}

static Point TileCoordFromScreenCoord(int x, int y)
{
	/*  What we calculate here is the inverse function of RemapCoords,
	 *  assuming z = 0 in RemapCoords.
	 */
	Point pt;
	pt.x = (2 * y - x) / 4;
	pt.y = (x + 2 * y) / 4;
	return pt;
}

/** Vehicle colours in #SMT_VEHICLES mode. Indexed by #VehicleTypeByte. */
static const byte _vehicle_type_colours[6] = {
	PC_RED, PC_YELLOW, PC_LIGHT_BLUE, PC_WHITE, PC_BLACK, PC_RED
};

/**
 * Draw a square symbolizing a producer of cargo in the link stats view.
 * @param x the x coordinate of the middle of the vertex
 * @param y the y coordinate of the middle of the vertex
 * @param size the x and y extend of the vertex
 * @param colour the colour with which the vertex will be filled
 * @param border_colour the colour for the border of the vertex
 */
void DrawVertex(int x, int y, int size, int colour, int border_colour)
{
	size--;
	int w1 = size / 2;
	int w2 = size / 2 + size % 2;

	GfxFillRect(x - w1, y - w1, x + w2, y + w2, colour);

	w1++;
	w2++;
	GfxDrawLine(x - w1, y - w1, x + w2, y - w1, border_colour);
	GfxDrawLine(x - w1, y + w2, x + w2, y + w2, border_colour);
	GfxDrawLine(x - w1, y - w1, x - w1, y + w2, border_colour);
	GfxDrawLine(x + w2, y - w1, x + w2, y + w2, border_colour);
}

/** Class managing the smallmap window. */
class SmallMapWindow : public Window {
	/** Types of legends in the #SM_WIDGET_LEGEND widget. */
	enum SmallMapType {
		SMT_CONTOUR,
		SMT_VEHICLES,
		SMT_INDUSTRY,
		SMT_LINKSTATS,
		SMT_ROUTES,
		SMT_VEGETATION,
		SMT_OWNER,
	};

	/**
	 * Save the Vehicle's old position here, so that we don't get glitches when
	 * redrawing.
	 * The glitches happen when a vehicle occupies a larger area (zoom-in) and
	 * a partial redraw happens which only covers part of the vehicle. If the
	 * vehicle has moved in the meantime, it looks ugly afterwards.
	 */
	struct VehicleAndPosition {
		VehicleAndPosition(const Vehicle *v) : vehicle(v->index)
		{
			this->position.x = v->x_pos;
			this->position.y = v->y_pos;
		}

		Point position;
		VehicleID vehicle;
	};

	typedef std::list<VehicleAndPosition> VehicleList;
	VehicleList vehicles_on_map; ///< cached vehicle positions to avoid glitches
	
	/** Available kinds of zoomlevel changes. */
	enum ZoomLevelChange {
		ZLC_INITIALIZE, ///< Initialize zoom level.
		ZLC_ZOOM_OUT,   ///< Zoom out.
		ZLC_ZOOM_IN,    ///< Zoom in.
	};

	static SmallMapType map_type; ///< Currently displayed legends.
	static bool show_towns;       ///< Display town names in the smallmap.

	static const uint LEGEND_BLOB_WIDTH = 8;              ///< Width of the coloured blob in front of a line text in the #SM_WIDGET_LEGEND widget.
	static const uint INDUSTRY_MIN_NUMBER_OF_COLUMNS = 2; ///< Minimal number of columns in the #SM_WIDGET_LEGEND widget for the #SMT_INDUSTRY legend.
	uint min_number_of_fixed_rows; ///< Minimal number of rows in the legends for the fixed layouts only (all except #SMT_INDUSTRY).
	uint column_width;             ///< Width of a column in the #SM_WIDGET_LEGEND widget.

	bool HasButtons()
	{
		return this->map_type == SMT_INDUSTRY || this->map_type == SMT_LINKSTATS || this->map_type == SMT_OWNER;
	}

	Point cursor;

	struct BaseCargoDetail {
		BaseCargoDetail()
		{
			this->Clear();
		}

		void AddLink(const LinkStat & orig_link, const FlowStat & orig_flow)
		{
			this->capacity += orig_link.Capacity();
			this->usage += orig_link.Usage();
			this->planned += orig_flow.Planned();
			this->sent += orig_flow.Sent();
		}

		void Clear()
		{
			this->capacity = this->usage = this->planned = this->sent = 0;
		}

		uint capacity;
		uint usage;
		uint planned;
		uint sent;
	};

	struct CargoDetail : public BaseCargoDetail {
		CargoDetail(const LegendAndColour * c, const LinkStat &ls, const FlowStat &fs) : legend(c)
		{
			this->AddLink(ls, fs);
		}

		const LegendAndColour *legend;
	};

	typedef std::vector<CargoDetail> StatVector;

	struct LinkDetails {
		LinkDetails() {this->Clear();}

		StationID sta;
		StationID stb;
		StatVector a_to_b;
		StatVector b_to_a;

		void Clear()
		{
			this->sta = INVALID_STATION;
			this->stb = INVALID_STATION;
			this->a_to_b.clear();
			this->b_to_a.clear();
		}

		bool Empty() const
		{
			return this->sta == INVALID_STATION;
		}
	};

	/**
	 * those are detected while drawing the links and used when drawing
	 * the legend. They don't represent game state.
	 */
	mutable LinkDetails link_details;
	mutable StationID supply_details;

	int32 scroll_x;  ///< Horizontal world coordinate of the base tile left of the top-left corner of the smallmap display.
	int32 scroll_y;  ///< Vertical world coordinate of the base tile left of the top-left corner of the smallmap display.
	int32 subscroll; ///< Number of pixels (0..3) between the right end of the base tile and the pixel at the top-left corner of the smallmap display.
	int zoom;        ///< Zoom level. Bigger number means more zoom-out (further away).

	static const uint8 FORCE_REFRESH_PERIOD = 0x1F; ///< map is redrawn after that many ticks
	static const uint8 REFRESH_NEXT_TICK = 1;       ///< if refreh has this value the map is redrawn in the next tick
	uint8 refresh; ///< refresh counter, zeroed every FORCE_REFRESH_PERIOD ticks

	/**
	 * Remap tile to location on this smallmap.
	 * @param tile_x X coordinate of the tile.
	 * @param tile_y Y coordinate of the tile.
	 * @return Position to draw on.
	 */
	FORCEINLINE Point RemapTile(int tile_x, int tile_y) const
	{
		if (this->zoom > 0) {
			int x_offset = tile_x - this->scroll_x / (int)TILE_SIZE;
			int y_offset = tile_y - this->scroll_y / (int)TILE_SIZE;

			/* For negative offsets, round towards -inf. */
			if (x_offset < 0) x_offset -= this->zoom - 1;
			if (y_offset < 0) y_offset -= this->zoom - 1;

			return RemapCoords(x_offset / this->zoom, y_offset / this->zoom, 0);
		} else {
			int x_offset = tile_x * (-this->zoom) - this->scroll_x * (-this->zoom) / (int)TILE_SIZE;
			int y_offset = tile_y * (-this->zoom) - this->scroll_y * (-this->zoom) / (int)TILE_SIZE;

			return RemapCoords(x_offset, y_offset, 0);
		}
	}

	/**
	 * Determine the world coordinates relative to the base tile of the smallmap, and the pixel position at
	 * that location for a point in the smallmap.
	 * @param px       Horizontal coordinate of the pixel.
	 * @param py       Vertical coordinate of the pixel.
	 * @param sub[out] Pixel position at the tile (0..3).
	 * @param add_sub  Add current #subscroll to the position.
	 * @return world coordinates being displayed at the given position relative to #scroll_x and #scroll_y.
	 * @note The #subscroll offset is already accounted for.
	 */
	FORCEINLINE Point PixelToWorld(int px, int py, int *sub, bool add_sub = true) const
	{
		if (add_sub) px += this->subscroll;  // Total horizontal offset.

		/* For each two rows down, add a x and a y tile, and
		 * For each four pixels to the right, move a tile to the right. */
		Point pt = {
			((py >> 1) - (px >> 2)) * TILE_SIZE,
			((py >> 1) + (px >> 2)) * TILE_SIZE
		};

		if (this->zoom > 0) {
			pt.x *= this->zoom;
			pt.y *= this->zoom;
		} else {
			pt.x /= (-this->zoom);
			pt.y /= (-this->zoom);
		}

		px &= 3;

		if (py & 1) { // Odd number of rows, handle the 2 pixel shift.
			int offset = this->zoom > 0 ? this->zoom * TILE_SIZE : TILE_SIZE / (-this->zoom);
			if (px < 2) {
				pt.x += offset;
				px += 2;
			} else {
				pt.y += offset;
				px -= 2;
			}
		}

		*sub = px;
		return pt;
	}

	/**
	 * Compute base parameters of the smallmap such that tile (\a tx, \a ty) starts at pixel (\a x, \a y).
	 * @param tx        Tile x coordinate.
	 * @param ty        Tile y coordinate.
	 * @param x         Non-negative horizontal position in the display where the tile starts.
	 * @param y         Non-negative vertical position in the display where the tile starts.
	 * @param sub [out] Value of #subscroll needed.
	 * @return #scroll_x, #scroll_y values.
	 */
	Point ComputeScroll(int tx, int ty, int x, int y, int *sub)
	{
		assert(x >= 0 && y >= 0);

		int new_sub;
		Point tile_xy = PixelToWorld(x, y, &new_sub, false);
		tx -= tile_xy.x;
		ty -= tile_xy.y;

		int offset = this->zoom < 0 ? TILE_SIZE / (-this->zoom) : this->zoom * TILE_SIZE;

		Point scroll;
		if (new_sub == 0) {
			*sub = 0;
			scroll.x = tx + offset;
			scroll.y = ty - offset;
		} else {
			*sub = 4 - new_sub;
			scroll.x = tx + 2 * offset;
			scroll.y = ty - 2 * offset;
		}
		return scroll;
	}

	/**
	 * Initialize or change the zoom level.
	 * @param change  Way to change the zoom level.
	 * @param zoom_pt Position to keep fixed while zooming.
	 * @pre \c *zoom_pt should contain a point in the smallmap display when zooming in or out.
	 */
	void SetZoomLevel(ZoomLevelChange change, const Point *zoom_pt)
	{
		static const int zoomlevels[] = {-4, -2, 1, 2, 4, 6, 8}; // Available zoom levels. Bigger number means more zoom-out (further away).
		static const int MIN_ZOOM_INDEX = 0;
		static const int DEFAULT_ZOOM_INDEX = 2;
		static const int MAX_ZOOM_INDEX = lengthof(zoomlevels) - 1;

		int new_index, cur_index, sub;
		Point position;
		switch (change) {
			case ZLC_INITIALIZE:
				cur_index = - 1; // Definitely different from new_index.
				new_index = DEFAULT_ZOOM_INDEX;
				break;

			case ZLC_ZOOM_IN:
			case ZLC_ZOOM_OUT:
				for (cur_index = MIN_ZOOM_INDEX; cur_index <= MAX_ZOOM_INDEX; cur_index++) {
					if (this->zoom == zoomlevels[cur_index]) break;
				}
				assert(cur_index <= MAX_ZOOM_INDEX);

				position = this->PixelToWorld(zoom_pt->x, zoom_pt->y, &sub);
				new_index = Clamp(cur_index + ((change == ZLC_ZOOM_IN) ? -1 : 1), MIN_ZOOM_INDEX, MAX_ZOOM_INDEX);
				break;

			default: NOT_REACHED();
		}

		if (new_index != cur_index) {
			this->zoom = zoomlevels[new_index];
			if (cur_index >= 0) {
				Point new_pos = this->PixelToWorld(zoom_pt->x, zoom_pt->y, &sub);
				this->SetNewScroll(this->scroll_x + position.x - new_pos.x,
						this->scroll_y + position.y - new_pos.y, sub);
			}
			this->SetWidgetDisabledState(SM_WIDGET_ZOOM_IN,  this->zoom == zoomlevels[MIN_ZOOM_INDEX]);
			this->SetWidgetDisabledState(SM_WIDGET_ZOOM_OUT, this->zoom == zoomlevels[MAX_ZOOM_INDEX]);
			this->SetDirty();
		}
	}

	/**
	 * Decide which colours to show to the user for a group of tiles.
	 * @param ta Tile area to investigate.
	 * @return Colours to display.
	 */
	inline uint32 GetTileColours(const TileArea &ta) const
	{
		int importance = 0;
		TileIndex tile = INVALID_TILE; // Position of the most important tile.
		TileType et = MP_VOID;         // Effective tile type at that position.

		TILE_AREA_LOOP(ti, ta) {
			TileType ttype = GetEffectiveTileType(ti);
			if (_tiletype_importance[ttype] > importance) {
				importance = _tiletype_importance[ttype];
				tile = ti;
				et = ttype;
			}
		}

		switch (this->map_type) {
			case SMT_CONTOUR:
				return GetSmallMapContoursPixels(tile, et);

			case SMT_VEHICLES:
				return GetSmallMapVehiclesPixels(tile, et);

			case SMT_INDUSTRY:
				return GetSmallMapIndustriesPixels(tile, et);

			case SMT_ROUTES:
				return GetSmallMapStuckRoutesPixels(tile, et);

			case SMT_VEGETATION:
				return GetSmallMapVegetationPixels(tile, et);

			case SMT_OWNER:
				return GetSmallMapOwnerPixels(tile, et);

			case SMT_LINKSTATS:
				return GetSmallMapLinkStatsPixels(tile, et);

			default: NOT_REACHED();
		}
	}

	/**
	 * Draws one column of tiles of the small map in a certain mode onto the screen buffer, skipping the shifted rows in between.
	 *
	 * @param dst Pointer to a part of the screen buffer to write to.
	 * @param xc The world X coordinate of the rightmost place in the column.
	 * @param yc The world Y coordinate of the topmost place in the column.
	 * @param pitch Number of pixels to advance in the screen buffer each time a pixel is written.
	 * @param reps Number of lines to draw
	 * @param start_pos Position of first pixel to draw.
	 * @param end_pos Position of last pixel to draw (exclusive).
	 * @param blitter current blitter
	 * @note If pixel position is below \c 0, skip drawing.
	 * @see GetSmallMapPixels(TileIndex)
	 */
	void DrawSmallMapColumn(void *dst, uint xc, uint yc, int pitch, int reps, int start_pos, int end_pos, Blitter *blitter) const
	{
		void *dst_ptr_abs_end = blitter->MoveTo(_screen.dst_ptr, 0, _screen.height);
		uint min_xy = _settings_game.construction.freeform_edges ? 1 : 0;

		int increment = this->zoom > 0 ? this->zoom * TILE_SIZE : TILE_SIZE / (-this->zoom);
		int extent = this->zoom > 0 ? this->zoom : 1;

		do {
			/* Check if the tile (xc,yc) is within the map range */
			if (xc / TILE_SIZE >= MapMaxX() || yc / TILE_SIZE >= MapMaxY()) continue;

			/* Check if the dst pointer points to a pixel inside the screen buffer */
			if (dst < _screen.dst_ptr) continue;
			if (dst >= dst_ptr_abs_end) continue;

			/* Construct tilearea covered by (xc, yc, xc + this->zoom, yc + this->zoom) such that it is within min_xy limits. */
			TileArea ta;
			if (min_xy == 1 && (xc < TILE_SIZE || yc < TILE_SIZE)) {
				if (this->zoom <= 1) continue; // The tile area is empty, don't draw anything.

				ta = TileArea(TileXY(max(min_xy, xc / TILE_SIZE), max(min_xy, yc / TILE_SIZE)), this->zoom - (xc < TILE_SIZE), this->zoom - (yc < TILE_SIZE));
			} else {
				ta = TileArea(TileXY(xc / TILE_SIZE, yc / TILE_SIZE), extent, extent);
			}
			ta.ClampToMap(); // Clamp to map boundaries (may contain MP_VOID tiles!).

			uint32 val = this->GetTileColours(ta);
			uint8 *val8 = (uint8 *)&val;
			int idx = max(0, -start_pos);
			for (int pos = max(0, start_pos); pos < end_pos; pos++) {
				blitter->SetPixel(dst, idx, 0, val8[idx]);
				idx++;
			}
		/* Switch to next tile in the column */
		} while (xc += increment, yc += increment, dst = blitter->MoveTo(dst, pitch, 0), --reps != 0);
	}

	/**
	 * Adds vehicles to the smallmap.
	 * @param dpi the part of the smallmap to be drawn into
	 * @param blitter current blitter
	 */
	void DrawVehicles(const DrawPixelInfo *dpi, Blitter *blitter) const
	{
		for(VehicleList::const_iterator i = this->vehicles_on_map.begin(); i != this->vehicles_on_map.end(); ++i) {
			const Vehicle *v = Vehicle::GetIfValid(i->vehicle);
			if (v == NULL) continue;

			/* Remap into flat coordinates. */
			Point pt = RemapTile(i->position.x / (int)TILE_SIZE, i->position.y / (int)TILE_SIZE);

			int y = pt.y - dpi->top;
			int x = pt.x - this->subscroll - 3 - dpi->left; // Offset X coordinate.

			int scale = this->zoom < 0 ? -this->zoom : 1;

			/* Calculate pointer to pixel and the colour */
			byte colour = (this->map_type == SMT_VEHICLES) ? _vehicle_type_colours[v->type] : PC_WHITE;

			/* Draw rhombus */
			for (int dy = 0; dy < scale; dy++) {
				for (int dx = 0; dx < scale; dx++) {
					Point pt = RemapCoords(dx, dy, 0);
					if (IsInsideMM(y + pt.y, 0, dpi->height)) {
						if (IsInsideMM(x + pt.x, 0, dpi->width)) {
							blitter->SetPixel(dpi->dst_ptr, x + pt.x, y + pt.y, colour);
						}
						if (IsInsideMM(x + pt.x + 1, 0, dpi->width)) {
							blitter->SetPixel(dpi->dst_ptr, x + pt.x + 1, y + pt.y, colour);
						}
					}
				}
			}
		}
	}

	FORCEINLINE Point GetStationMiddle(const Station *st) const
	{
		int x = (st->rect.right + st->rect.left + 1) / 2;
		int y = (st->rect.bottom + st->rect.top + 1) / 2;
		Point ret = this->RemapTile(x, y);
		ret.x -= 3 + this->subscroll;
		if (this->zoom < 0) {
			/* add half a tile if width or height is odd */
			if (((st->rect.bottom - st->rect.top) & 1) == 0) {
				Point offset = RemapCoords(0, -this->zoom / 2, 0);
				ret.x += offset.x;
				ret.y += offset.y;
			}
			if (((st->rect.right - st->rect.left) & 1) == 0) {
				Point offset = RemapCoords(-this->zoom / 2, 0, 0);
				ret.x += offset.x;
				ret.y += offset.y;
			}
		}
		return ret;
	}

	StationID DrawStationDots() const
	{
		const Station *supply_details = NULL;

		const Station *st;
		FOR_ALL_STATIONS(st) {
			if (((st->owner != _local_company && Company::IsValidID(st->owner)) ||
					st->rect.IsEmpty()) && _settings_client.gui.linkgraph_companies == 0) continue; // test show all companies links

			Point pt = GetStationMiddle(st);

			if (supply_details == NULL && CheckStationSelected(&pt)) {
				supply_details = st;
			}

			/* Add up cargo supplied for each selected cargo type */
			uint q = 0;
			int colour = 0;
			int numCargos = 0;

			if (AllowMoreHeightlevels()) {
				for (int i = 0; i < _smallmap_cargo_count; ++i) {
					const LegendAndColour &tbl = _legend_table_extended[this->map_type][i];
					if (!tbl.show_on_map && supply_details != st) continue;
					uint supply = st->goods[tbl.type].supply;
					if (supply > 0) {
						q += supply;
						colour += tbl.colour;
						numCargos++;
					}
				}

			} else {
				for (int i = 0; i < _smallmap_cargo_count; ++i) {
					const LegendAndColour &tbl = _legend_table_old[this->map_type][i];
					if (!tbl.show_on_map && supply_details != st) continue;
					uint supply = st->goods[tbl.type].supply;
					if (supply > 0) {
						q += supply;
						colour += tbl.colour;
						numCargos++;
					}
				}
			}

			if (numCargos > 1) colour /= numCargos;

			uint r = 2;
			if (q >= 10) r++;
			if (q >= 20) r++;
			if (q >= 40) r++;
			if (q >= 80) r++;
			if (q >= 160) r++;

			DrawVertex(pt.x, pt.y, r, colour, _colour_gradient[COLOUR_GREY][supply_details == st ? 3 : 1]);
		}
		return (supply_details == NULL) ? INVALID_STATION : supply_details->index;
	}

	class LinkDrawer {

	protected:
		virtual void DrawContent() = 0;
		virtual void Highlight() {}
		virtual void AddLink(const LinkStat &orig_link, const FlowStat &orig_flow, const LegendAndColour &cargo_entry) = 0;

		FORCEINLINE bool IsLinkVisible()
		{
			const NWidgetBase *wi = this->window->GetWidget<NWidgetCore>(SM_WIDGET_MAP);
			return !((this->pta.x < 0 && this->ptb.x < 0) ||
					(this->pta.y < 0 && this->ptb.y < 0) ||
					(this->pta.x > (int)wi->current_x && this->ptb.x > (int)wi->current_x) ||
					(this->pta.y > (int)wi->current_y && this->ptb.y > (int)wi->current_y));
		}

		Point pta, ptb;
		bool search_link_details;
		LinkDetails link_details;
		const SmallMapWindow *window;

		void DrawLink(StationID sta, StationID stb)
		{
			bool highlight_empty = this->search_link_details && this->link_details.Empty();
			bool highlight =
					(sta == this->link_details.sta && stb == this->link_details.stb) ||
					(highlight_empty && window->CheckLinkSelected(&this->pta, &this->ptb));
			bool reverse_empty = this->link_details.b_to_a.empty();
			bool reverse_highlight = (sta == this->link_details.stb && stb == this->link_details.sta);
			if (highlight_empty && highlight) {
				this->link_details.sta = sta;
				this->link_details.stb = stb;
			}

			if (highlight || reverse_highlight) {
				this->Highlight();
			}

			if (AllowMoreHeightlevels()) {
				for (int i = 0; i < _smallmap_cargo_count; ++i) {
					const LegendAndColour &cargo_entry = _legend_table_extended[window->map_type][i];
					CargoID cargo = cargo_entry.type;
					if (cargo_entry.show_on_map || highlight || reverse_highlight) {
						GoodsEntry &ge = Station::Get(sta)->goods[cargo];
						FlowStat sum_flows = ge.GetSumFlowVia(stb);
						const LinkStatMap &ls_map = ge.link_stats;
						LinkStatMap::const_iterator i = ls_map.find(stb);
						if (i != ls_map.end()) {
							const LinkStat &link_stat = i->second;
							this->AddLink(link_stat, sum_flows, cargo_entry);
							if (highlight_empty && highlight) {
								this->link_details.a_to_b.push_back(CargoDetail(&cargo_entry, link_stat, sum_flows));
							} else if (reverse_empty && reverse_highlight) {
								this->link_details.b_to_a.push_back(CargoDetail(&cargo_entry, link_stat, sum_flows));
							}
						}
					}
				}

			} else {
				for (int i = 0; i < _smallmap_cargo_count; ++i) {
					const LegendAndColour &cargo_entry = _legend_table_old[window->map_type][i];
					CargoID cargo = cargo_entry.type;
					if (cargo_entry.show_on_map || highlight || reverse_highlight) {
						GoodsEntry &ge = Station::Get(sta)->goods[cargo];
						FlowStat sum_flows = ge.GetSumFlowVia(stb);
						const LinkStatMap &ls_map = ge.link_stats;
						LinkStatMap::const_iterator i = ls_map.find(stb);
						if (i != ls_map.end()) {
							const LinkStat &link_stat = i->second;
							this->AddLink(link_stat, sum_flows, cargo_entry);
							if (highlight_empty && highlight) {
								this->link_details.a_to_b.push_back(CargoDetail(&cargo_entry, link_stat, sum_flows));
							} else if (reverse_empty && reverse_highlight) {
								this->link_details.b_to_a.push_back(CargoDetail(&cargo_entry, link_stat, sum_flows));
							}
						}
					}
				}
			}
		}

		virtual void DrawForwBackLinks(StationID sta, StationID stb)
		{
			this->DrawLink(sta, stb);
			this->DrawContent();
			Swap(this->pta, this->ptb);
			this->DrawLink(stb, sta);
			this->DrawContent();
		}

	public:
		virtual ~LinkDrawer() {}

		LinkDetails DrawLinks(const SmallMapWindow * w, bool search)
		{
			this->link_details.Clear();
			this->window = w;
			this->search_link_details = search;
			std::set<StationID> seen_stations;
			std::set<std::pair<StationID, StationID> > seen_links;

			const Station *sta;
			if (AllowMoreHeightlevels()) {
				FOR_ALL_STATIONS(sta) {
					if (sta->owner != _local_company && Company::IsValidID(sta->owner) && _settings_client.gui.linkgraph_companies == 0) continue; // test show all companies links

					for (int i = 0; i < _smallmap_cargo_count; ++i) {
						const LegendAndColour &tbl = _legend_table_extended[window->map_type][i];
						if (!tbl.show_on_map) continue;

						CargoID c = tbl.type;
						const LinkStatMap &links = sta->goods[c].link_stats;
						for (LinkStatMap::const_iterator i = links.begin(); i != links.end(); ++i) {
							StationID from = sta->index;
							StationID to = i->first;
							if (Station::IsValidID(to) && seen_stations.find(to) == seen_stations.end()) {
								const Station *stb = Station::Get(to);

								if (stb->owner != _local_company && Company::IsValidID(stb->owner) && _settings_client.gui.linkgraph_companies == 0) continue; // test show all companies links
								if (sta->rect.IsEmpty() || stb->rect.IsEmpty()) continue;
								if (seen_links.find(std::make_pair(to, from)) != seen_links.end()) continue;

								this->pta = this->window->GetStationMiddle(sta);
								this->ptb = this->window->GetStationMiddle(stb);
								if (!this->IsLinkVisible()) continue;

								this->DrawForwBackLinks(sta->index, stb->index);
								seen_stations.insert(to);
							}
							seen_links.insert(std::make_pair(from, to));
						}
					}
					seen_stations.clear();
				}

			} else {
				FOR_ALL_STATIONS(sta) {
					if (sta->owner != _local_company && Company::IsValidID(sta->owner) && _settings_client.gui.linkgraph_companies == 0) continue; // test show all companies links

					for (int i = 0; i < _smallmap_cargo_count; ++i) {
						const LegendAndColour &tbl = _legend_table_old[window->map_type][i];
						if (!tbl.show_on_map) continue;

						CargoID c = tbl.type;
						const LinkStatMap &links = sta->goods[c].link_stats;
						for (LinkStatMap::const_iterator i = links.begin(); i != links.end(); ++i) {
							StationID from = sta->index;
							StationID to = i->first;
							if (Station::IsValidID(to) && seen_stations.find(to) == seen_stations.end()) {
								const Station *stb = Station::Get(to);

								if (stb->owner != _local_company && Company::IsValidID(stb->owner) && _settings_client.gui.linkgraph_companies == 0) continue; // test show all companies links
								if (sta->rect.IsEmpty() || stb->rect.IsEmpty()) continue;
								if (seen_links.find(std::make_pair(to, from)) != seen_links.end()) continue;

								this->pta = this->window->GetStationMiddle(sta);
								this->ptb = this->window->GetStationMiddle(stb);
								if (!this->IsLinkVisible()) continue;

								this->DrawForwBackLinks(sta->index, stb->index);
								seen_stations.insert(to);
							}
							seen_links.insert(std::make_pair(from, to));
						}
					}
				
					seen_stations.clear();
				}
			}
			return this->link_details;
		}

	};

	class LinkLineDrawer : public LinkDrawer {
	public:
		LinkLineDrawer() : highlight(false) {}

	protected:
		typedef std::set<uint16> ColourSet;
		ColourSet colours;
		bool highlight;

		virtual void DrawForwBackLinks(StationID sta, StationID stb)
		{
			this->DrawLink(sta, stb);
			this->DrawLink(stb, sta);
			this->DrawContent();
		}

		virtual void AddLink(const LinkStat & orig_link, const FlowStat & orig_flow, const LegendAndColour &cargo_entry)
		{
			this->colours.insert(cargo_entry.colour);
		}

		virtual void Highlight()
		{
			this->highlight = true;
		}

		virtual void DrawContent()
		{
			uint colour = 0;
			uint num_colours = 0;
			for (ColourSet::iterator i = colours.begin(); i != colours.end(); ++i) {
				colour += *i;
				num_colours++;
			}
			colour /= num_colours;
			byte border_colour = _colour_gradient[COLOUR_GREY][highlight ? 3 : 1];
			GfxDrawLine(this->pta.x - 1, this->pta.y, this->ptb.x - 1, this->ptb.y, border_colour);
			GfxDrawLine(this->pta.x + 1, this->pta.y, this->ptb.x + 1, this->ptb.y, border_colour);
			GfxDrawLine(this->pta.x, this->pta.y - 1, this->ptb.x, this->ptb.y - 1, border_colour);
			GfxDrawLine(this->pta.x, this->pta.y + 1, this->ptb.x, this->ptb.y + 1, border_colour);
			GfxDrawLine(this->pta.x, this->pta.y, this->ptb.x, this->ptb.y, colour);
			this->colours.clear();
			this->highlight = false;
		}
	};

	class LinkValueDrawer : public LinkDrawer, public BaseCargoDetail {
	protected:

		virtual void AddLink(const LinkStat & orig_link, const FlowStat & orig_flow, const LegendAndColour &cargo_entry)
		{
			this->BaseCargoDetail::AddLink(orig_link, orig_flow);
		}
	};

	class LinkTextDrawer : public LinkValueDrawer {
	protected:
		virtual void DrawContent()
		{
			Point ptm;
			ptm.x = (this->pta.x + 2*this->ptb.x) / 3;
			ptm.y = (this->pta.y + 2*this->ptb.y) / 3;
			int nums = 0;
			if (_legend_linkstats[_smallmap_cargo_count + STAT_CAPACITY].show_on_map) {
				SetDParam(nums++, this->capacity);
			}
			if (_legend_linkstats[_smallmap_cargo_count + STAT_USAGE].show_on_map) {
				SetDParam(nums++, this->usage);
			}
			if (_legend_linkstats[_smallmap_cargo_count + STAT_PLANNED].show_on_map) {
				SetDParam(nums++, this->planned);
			}
			if (_legend_linkstats[_smallmap_cargo_count + STAT_SENT].show_on_map) {
				SetDParam(nums++, this->sent);
			}
			StringID str;
			switch (nums) {
			case 0:
				str = STR_EMPTY; break;
			case 1:
				str = STR_NUM; break;
			case 2:
				str = STR_NUM_RELATION_2; break;
			case 3:
				str = STR_NUM_RELATION_3; break;
			case 4:
				str = STR_NUM_RELATION_4; break;
			default:
				NOT_REACHED();
			}
			DrawString(ptm.x, ptm.x + this->window->ColumnWidth(), ptm.y, str, TC_WHITE);
			this->Clear();
		}
	};

	class LinkGraphDrawer : public LinkValueDrawer {
		typedef std::multimap<uint, byte, std::greater<uint> > SizeMap;
	protected:
		virtual void DrawContent()
		{
			Point ptm;
			SizeMap sizes;
			/* these floats only serve to calculate the size of the coloured boxes for capacity, usage, planned, sent
			 * they are not reused anywhere, so it's network safe.
			 */
			const LegendAndColour *legend_entry = _legend_linkstats + _smallmap_cargo_count + STAT_USAGE;
			if (legend_entry->show_on_map && this->usage > 0) {
				sizes.insert(std::make_pair((uint)sqrt((float)this->usage), legend_entry->colour));
			}
			legend_entry = _legend_linkstats + _smallmap_cargo_count + STAT_CAPACITY;
			if (legend_entry->show_on_map && this->capacity > 0) {
				sizes.insert(std::make_pair((uint)sqrt((float)this->capacity), legend_entry->colour));
			}
			legend_entry = _legend_linkstats + _smallmap_cargo_count + STAT_PLANNED;
			if (legend_entry->show_on_map && this->planned > 0) {
				sizes.insert(std::make_pair((uint)sqrt((float)this->planned),  legend_entry->colour));
			}
			legend_entry = _legend_linkstats + _smallmap_cargo_count + STAT_SENT;
			if (legend_entry->show_on_map && this->sent > 0) {
				sizes.insert(std::make_pair((uint)sqrt((float)this->sent), legend_entry->colour));
			}

			ptm.x = (this->pta.x + this->ptb.x) / 2;
			ptm.y = (this->pta.y + this->ptb.y) / 2;

			for (SizeMap::iterator i = sizes.begin(); i != sizes.end(); ++i) {
				if (this->pta.x > this->ptb.x) {
					ptm.x -= 1;
					GfxFillRect(ptm.x - i->first / 2, ptm.y - i->first * 2, ptm.x, ptm.y, i->second);
				} else {
					ptm.x += 1;
					GfxFillRect(ptm.x, ptm.y - i->first * 2, ptm.x + i->first / 2, ptm.y, i->second);
				}
			}
			this->Clear();
		}
	};

	static const uint MORE_SPACE_NEEDED = 0x1000;

	uint DrawLinkDetails(StatVector &details, uint x, uint y, uint right, uint bottom) const
	{
		uint x_orig = x;
		SetDParam(0, 9999);
		static uint entry_width = LEGEND_BLOB_WIDTH +
				GetStringBoundingBox(STR_ABBREV_PASSENGERS).width +
				GetStringBoundingBox(STR_SMALLMAP_LINK_CAPACITY).width +
				GetStringBoundingBox(STR_SMALLMAP_LINK_USAGE).width +
				GetStringBoundingBox(STR_SMALLMAP_LINK_PLANNED).width +
				GetStringBoundingBox(STR_SMALLMAP_LINK_SENT).width;
		uint entries_per_row = (right - x_orig) / entry_width;
		if (details.empty()) {
			DrawString(x, x + entry_width, y, STR_TINY_NOTHING, TC_BLACK);
			return y + FONT_HEIGHT_SMALL;
		}
		for (uint i = 0; i < details.size(); ++i) {
			CargoDetail &detail = details[i];
			if (x + entry_width >= right) {
				x = x_orig;
				y += FONT_HEIGHT_SMALL;
				if (y + 2 * FONT_HEIGHT_SMALL > bottom && details.size() - i > entries_per_row) {
					return y | MORE_SPACE_NEEDED;
				}
			}
			uint x_next = x + entry_width;
			if (detail.legend->show_on_map) {
				GfxFillRect(x, y + 1, x + LEGEND_BLOB_WIDTH, y + FONT_HEIGHT_SMALL - 1, PC_BLACK); // outer border of the legend colour
			}
			GfxFillRect(x + 1, y + 2, x + LEGEND_BLOB_WIDTH - 1, y + FONT_HEIGHT_SMALL - 2, detail.legend->colour); // legend colour
			x += LEGEND_BLOB_WIDTH + WD_FRAMERECT_LEFT;
			TextColour textcol[4];
			for (int stat = STAT_CAPACITY; stat <= STAT_SENT; ++stat) {
				textcol[stat] = (detail.legend->show_on_map && _legend_linkstats[_smallmap_cargo_count + stat].show_on_map) ?
						TC_BLACK : TC_GREY;
			}

			SetDParam(0, CargoSpec::Get(detail.legend->type)->abbrev);
			x = DrawString(x, x_next - 1, y, STR_SMALLMAP_LINK, detail.legend->show_on_map ? TC_BLACK : TC_GREY);
			SetDParam(0, detail.capacity);
			x = DrawString(x, x_next - 1, y, STR_SMALLMAP_LINK_CAPACITY, textcol[STAT_CAPACITY]);
			SetDParam(0, detail.usage);
			x = DrawString(x, x_next - 1, y, STR_SMALLMAP_LINK_USAGE, textcol[STAT_USAGE]);
			SetDParam(0, detail.planned);
			x = DrawString(x, x_next - 1, y, STR_SMALLMAP_LINK_PLANNED, textcol[STAT_PLANNED]);
			SetDParam(0, detail.sent);
			x = DrawString(x, x_next - 1, y, STR_SMALLMAP_LINK_SENT, textcol[STAT_SENT]);
			x = x_next;
		}
		return y + FONT_HEIGHT_SMALL;
	}

	uint DrawLinkDetailCaption(uint x, uint y, uint right, StationID sta, StationID stb) const
	{
		SetDParam(0, sta);
		SetDParam(1, stb);
		static uint height = GetStringBoundingBox(STR_SMALLMAP_LINK_CAPTION).height;
		DrawString(x, right - 1, y, STR_SMALLMAP_LINK_CAPTION, TC_BLACK);
		y += height;
		return y;
	}

	void DrawLinkDetails(uint x, uint y, uint right, uint bottom) const
	{
		y = DrawLinkDetailCaption(x, y, right, this->link_details.sta, this->link_details.stb);
		if (y + 2 * FONT_HEIGHT_SMALL > bottom) {
			DrawString(x, right, y, "...", TC_BLACK);
			return;
		}
		y = DrawLinkDetails(this->link_details.a_to_b, x, y, right, bottom);
		if (y + 3 * FONT_HEIGHT_SMALL > bottom) {
			/* caption takes more space -> 3 * row height */
			DrawString(x, right, y, "...", TC_BLACK);
			return;
		}
		y = DrawLinkDetailCaption(x, y + 2, right, this->link_details.stb, this->link_details.sta);
		if (y + 2 * FONT_HEIGHT_SMALL > bottom) {
			DrawString(x, right, y, "...", TC_BLACK);
			return;
		}
		y = DrawLinkDetails(this->link_details.b_to_a, x, y, right, bottom);
		if (y & MORE_SPACE_NEEDED) {
			/* only draw "..." if more entries would have been drawn */
			DrawString(x, right, y ^ MORE_SPACE_NEEDED, "...", TC_BLACK);
			return;
		}
	}

	void DrawSupplyDetails(uint x, uint y_org, uint bottom) const
	{
		const Station *st = Station::GetIfValid(this->supply_details);
		if (st == NULL) return;
		SetDParam(0, this->supply_details);
		static uint height = GetStringBoundingBox(STR_SMALLMAP_SUPPLY_CAPTION).height;
		DrawString(x, x + 2 * this->column_width - 1, y_org, STR_SMALLMAP_SUPPLY_CAPTION, TC_BLACK);
		y_org += height;
		uint y = y_org;
		if (AllowMoreHeightlevels()) {
			for (int i = 0; i < _smallmap_cargo_count; ++i) {
				if (y + FONT_HEIGHT_SMALL - 1 >= bottom) {
					/* Column break needed, continue at top, SD_LEGEND_COLUMN_WIDTH pixels
					 * (one "row") to the right. */
					x += this->column_width;
					y = y_org;
				}

				const LegendAndColour &tbl = _legend_table_extended[this->map_type][i];

				CargoID c = tbl.type;
				uint supply = st->goods[c].supply;
				if (supply > 0) {
					TextColour textcol = TC_BLACK;
					if (tbl.show_on_map) {
						GfxFillRect(x, y + 1, x + LEGEND_BLOB_WIDTH, y + FONT_HEIGHT_SMALL - 1, PC_BLACK); // outer border of the legend colour
					} else {
						textcol = TC_GREY;
					}
					SetDParam(0, c);
					SetDParam(1, supply);
					DrawString(x + LEGEND_BLOB_WIDTH + WD_FRAMERECT_LEFT, x + this->column_width - 1, y, STR_SMALLMAP_SUPPLY, textcol);
					GfxFillRect(x + 1, y + 2, x + LEGEND_BLOB_WIDTH - 1, y + FONT_HEIGHT_SMALL - 2, tbl.colour); // legend colour
					y += FONT_HEIGHT_SMALL;
				}
			}

		} else {
			for (int i = 0; i < _smallmap_cargo_count; ++i) {
				if (y + FONT_HEIGHT_SMALL - 1 >= bottom) {
					/* Column break needed, continue at top, SD_LEGEND_COLUMN_WIDTH pixels
					 * (one "row") to the right. */
					x += this->column_width;
					y = y_org;
				}

				const LegendAndColour &tbl = _legend_table_old[this->map_type][i];

				CargoID c = tbl.type;
				uint supply = st->goods[c].supply;
				if (supply > 0) {
					TextColour textcol = TC_BLACK;
					if (tbl.show_on_map) {
						GfxFillRect(x, y + 1, x + LEGEND_BLOB_WIDTH, y + FONT_HEIGHT_SMALL - 1, PC_BLACK); // outer border of the legend colour
					} else {
						textcol = TC_GREY;
					}
					SetDParam(0, c);
					SetDParam(1, supply);
					DrawString(x + LEGEND_BLOB_WIDTH + WD_FRAMERECT_LEFT, x + this->column_width - 1, y, STR_SMALLMAP_SUPPLY, textcol);
					GfxFillRect(x + 1, y + 2, x + LEGEND_BLOB_WIDTH - 1, y + FONT_HEIGHT_SMALL - 2, tbl.colour); // legend colour
					y += FONT_HEIGHT_SMALL;
				}
			}
		}
	}

	/**
	 * Adds town names to the smallmap.
	 * @param dpi the part of the smallmap to be drawn into
	 */
	void DrawTowns(const DrawPixelInfo *dpi) const
	{
		const Town *t;
		FOR_ALL_TOWNS(t) {
			/* Remap the town coordinate */
			Point pt = this->RemapTile(TileX(t->xy), TileY(t->xy));
			int x = pt.x - this->subscroll - (t->sign.width_small >> 1);
			int y = pt.y;

			/* Check if the town sign is within bounds */
			if (x + t->sign.width_small > dpi->left &&
					x < dpi->left + dpi->width &&
					y + FONT_HEIGHT_SMALL > dpi->top &&
					y < dpi->top + dpi->height) {
				/* And draw it. */
				SetDParam(0, t->index);
				DrawString(x, x + t->sign.width_small, y, STR_SMALLMAP_TOWN);
			}
		}
	}

	/**
	 * Draws vertical part of map indicator
	 * @param x X coord of left/right border of main viewport
	 * @param y Y coord of top border of main viewport
	 * @param y2 Y coord of bottom border of main viewport
	 */
	static inline void DrawVertMapIndicator(int x, int y, int y2)
	{
		GfxFillRect(x, y,      x, y + 3, PC_VERY_LIGHT_YELLOW);
		GfxFillRect(x, y2 - 3, x, y2,    PC_VERY_LIGHT_YELLOW);
	}

	/**
	 * Draws horizontal part of map indicator
	 * @param x X coord of left border of main viewport
	 * @param x2 X coord of right border of main viewport
	 * @param y Y coord of top/bottom border of main viewport
	 */
	static inline void DrawHorizMapIndicator(int x, int x2, int y)
	{
		GfxFillRect(x,      y, x + 3, y, PC_VERY_LIGHT_YELLOW);
		GfxFillRect(x2 - 3, y, x2,    y, PC_VERY_LIGHT_YELLOW);
	}

	/**
	 * Adds map indicators to the smallmap.
	 */
	void DrawMapIndicators() const
	{
		/* Find main viewport. */
		const ViewPort *vp = FindWindowById(WC_MAIN_WINDOW, 0)->viewport;

		Point tile = InverseRemapCoords(vp->virtual_left, vp->virtual_top);
		Point tl = this->RemapTile(tile.x >> 4, tile.y >> 4);
		tl.x -= this->subscroll;

		tile = InverseRemapCoords(vp->virtual_left + vp->virtual_width, vp->virtual_top + vp->virtual_height);
		Point br = this->RemapTile(tile.x >> 4, tile.y >> 4);
		br.x -= this->subscroll;

		SmallMapWindow::DrawVertMapIndicator(tl.x, tl.y, br.y);
		SmallMapWindow::DrawVertMapIndicator(br.x, tl.y, br.y);

		SmallMapWindow::DrawHorizMapIndicator(tl.x, br.x, tl.y);
		SmallMapWindow::DrawHorizMapIndicator(tl.x, br.x, br.y);
	}

	/**
	 * Draws the small map.
	 *
	 * Basically, the small map is draw column of pixels by column of pixels. The pixels
	 * are drawn directly into the screen buffer. The final map is drawn in multiple passes.
	 * The passes are:
	 * <ol><li>The colours of tiles in the different modes.</li>
	 * <li>Town names (optional)</li></ol>
	 *
	 * @param dpi pointer to pixel to write onto
	 */
	void DrawSmallMap(DrawPixelInfo *dpi) const
	{
		Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
		DrawPixelInfo *old_dpi;

		old_dpi = _cur_dpi;
		_cur_dpi = dpi;

		/* Clear it */
		GfxFillRect(dpi->left, dpi->top, dpi->left + dpi->width - 1, dpi->top + dpi->height - 1, PC_BLACK);

		/* Which tile is displayed at (dpi->left, dpi->top)? */
		int dx;
		Point position = this->PixelToWorld(dpi->left, dpi->top, &dx);
		int pos_x = this->scroll_x + position.x;
		int pos_y = this->scroll_y + position.y;

		void *ptr = blitter->MoveTo(dpi->dst_ptr, -dx - 4, 0);
		int x = - dx - 4;
		int y = 0;
		int increment = this->zoom > 0 ? this->zoom * TILE_SIZE : TILE_SIZE / (-this->zoom); 

		for (;;) {
			/* Distance from left edge */
			if (x >= -3) {
				if (x >= dpi->width) break; // Exit the loop.

				int end_pos = min(dpi->width, x + 4);
				int reps = (dpi->height - y + 1) / 2; // Number of lines.
				if (reps > 0) {
					this->DrawSmallMapColumn(ptr, pos_x, pos_y, dpi->pitch * 2, reps, x, end_pos, blitter);
				}
			}

			if (y == 0) {
				pos_y += increment;
				y++;
				ptr = blitter->MoveTo(ptr, 0, 1);
			} else {
				pos_x -= increment;
				y--;
				ptr = blitter->MoveTo(ptr, 0, -1);
			}
			ptr = blitter->MoveTo(ptr, 2, 0);
			x += 2;
		}

		/* Draw vehicles */
		if (this->map_type == SMT_CONTOUR || this->map_type == SMT_VEHICLES) this->DrawVehicles(dpi, blitter);

		/* Draw the cargo linkgraphs */
		if (this->map_type == SMT_LINKSTATS && _game_mode == GM_NORMAL) {
			LinkLineDrawer lines;
			this->link_details = lines.DrawLinks(this, true);

			this->supply_details = DrawStationDots();

			if (_legend_linkstats[_smallmap_cargo_count + STAT_TEXT].show_on_map) {
				LinkTextDrawer text;
				text.DrawLinks(this, false);
			}
			if (_legend_linkstats[_smallmap_cargo_count + STAT_GRAPH].show_on_map) {
				LinkGraphDrawer graph;
				graph.DrawLinks(this, false);
			}
		}

		/* Draw town names */
		if (this->show_towns) this->DrawTowns(dpi);

		/* Draw map indicators */
		this->DrawMapIndicators();

		_cur_dpi = old_dpi;
	}

	bool CheckStationSelected(Point *pt) const
	{
		return abs(this->cursor.x - pt->x) < 7 && abs(this->cursor.y - pt->y) < 7;
	}

	bool CheckLinkSelected(Point *pta, Point *ptb) const
	{
		if (this->cursor.x == -1 && this->cursor.y == -1) return false;
		if (CheckStationSelected(pta) || CheckStationSelected(ptb)) return false;
		if (pta->x > ptb->x) Swap(pta, ptb);
		int minx = min(pta->x, ptb->x);
		int maxx = max(pta->x, ptb->x);
		int miny = min(pta->y, ptb->y);
		int maxy = max(pta->y, ptb->y);
		if (!IsInsideMM(cursor.x, minx - 3, maxx + 3) || !IsInsideMM(cursor.y, miny - 3, maxy + 3)) {
			return false;
		}

		if (pta->x == ptb->x || ptb->y == pta->y) {
			return true;
		} else {
			int incliney = (ptb->y - pta->y);
			int inclinex = (ptb->x - pta->x);
			int diff = (cursor.x - minx) * incliney / inclinex - (cursor.y - miny);
			if (incliney < 0) {
				diff += maxy - miny;
			}
			return abs(diff) < 4;
		}
	}

	/**
	 * recalculate which vehicles are visible and their positions.
	 */
	void RecalcVehiclePositions()
	{
		this->vehicles_on_map.clear();
		const Vehicle *v;
		const NWidgetCore *wi = this->GetWidget<NWidgetCore>(SM_WIDGET_MAP);
		int scale = this->zoom < 0 ? -this->zoom : 1;

		FOR_ALL_VEHICLES(v) {
			if (v->type == VEH_EFFECT) continue;
			if (v->vehstatus & (VS_HIDDEN | VS_UNCLICKABLE)) continue;

			/* Remap into flat coordinates. We have to do that again in DrawVehicles to account for scrolling. */
			Point pos = RemapTile(v->x_pos / (int)TILE_SIZE, v->y_pos / (int)TILE_SIZE);

			/* Check if rhombus is inside bounds */
			if (IsInsideMM(pos.x, -2 * scale, wi->current_x + 2 * scale) &&
				IsInsideMM(pos.y, -2 * scale, wi->current_y + 2 * scale)) {

				this->vehicles_on_map.push_back(VehicleAndPosition(v));
			}
		}
	}

	/**
	 * Function to set up widgets depending on the information being shown on the smallmap.
	 */
	void SetupWidgetData()
	{
		StringID legend_tooltip;
		StringID enable_all_tooltip;
		StringID disable_all_tooltip;
		int plane;
		switch (this->map_type) {
			case SMT_INDUSTRY:
				legend_tooltip = STR_SMALLMAP_TOOLTIP_INDUSTRY_SELECTION;
				enable_all_tooltip = STR_SMALLMAP_TOOLTIP_ENABLE_ALL_INDUSTRIES;
				disable_all_tooltip = STR_SMALLMAP_TOOLTIP_DISABLE_ALL_INDUSTRIES;
				plane = 0;
				break;

			case SMT_LINKSTATS:
				legend_tooltip = STR_SMALLMAP_TOOLTIP_LINK_STATS_SELECTION;
				enable_all_tooltip = STR_SMALLMAP_TOOLTIP_ENABLE_ALL_LINK_STATS;
				disable_all_tooltip = STR_SMALLMAP_TOOLTIP_DISABLE_ALL_LINK_STATS;
				plane = 0;
				break;

			case SMT_OWNER:
				legend_tooltip = STR_SMALLMAP_TOOLTIP_COMPANY_SELECTION;
				enable_all_tooltip = STR_SMALLMAP_TOOLTIP_ENABLE_ALL_COMPANIES;
				disable_all_tooltip = STR_SMALLMAP_TOOLTIP_DISABLE_ALL_COMPANIES;
				plane = 0;
				break;

			default:
				legend_tooltip = STR_NULL;
				enable_all_tooltip = STR_NULL;
				disable_all_tooltip = STR_NULL;
				plane = 1;
				break;
		}

		this->GetWidget<NWidgetCore>(SM_WIDGET_LEGEND)->SetDataTip(STR_NULL, legend_tooltip);
		this->GetWidget<NWidgetCore>(SM_WIDGET_ENABLE_ALL)->SetDataTip(STR_SMALLMAP_ENABLE_ALL, enable_all_tooltip);
		this->GetWidget<NWidgetCore>(SM_WIDGET_DISABLE_ALL)->SetDataTip(STR_SMALLMAP_DISABLE_ALL, disable_all_tooltip);
		this->GetWidget<NWidgetStacked>(SM_WIDGET_SELECT_BUTTONS)->SetDisplayedPlane(plane);
	}

public:
	uint min_number_of_columns;    ///< Minimal number of columns in legends.

	SmallMapWindow(const WindowDesc *desc, int window_number) : Window(), supply_details(INVALID_STATION), refresh(FORCE_REFRESH_PERIOD)
	{
		this->cursor.x = -1;
		this->cursor.y = -1;
		this->InitNested(desc, window_number);
		if (_smallmap_cargo_count == 0) {
			this->DisableWidget(SM_WIDGET_LINKSTATS);
			if (this->map_type == SMT_LINKSTATS) this->map_type = SMT_CONTOUR;
		}

		this->LowerWidget(this->map_type + SM_WIDGET_CONTOUR);

		BuildLandLegend();
		this->SetWidgetLoweredState(SM_WIDGET_SHOW_HEIGHT, _smallmap_show_heightmap);

		this->SetWidgetLoweredState(SM_WIDGET_TOGGLETOWNNAME, this->show_towns);

		this->SetupWidgetData();

		this->SetZoomLevel(ZLC_INITIALIZE, NULL);
		this->SmallMapCenterOnCurrentPos();
	}

//	/**
//	 * Compute maximal required height of the legends. // TODO: remove and fix
//	 * @return Maximally needed height for displaying the smallmap legends in pixels.
//	 */
//	inline uint GetMaxLegendHeight() const
//	{
//		return WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + this->GetMaxNumberRowsLegend(this->min_number_of_columns) * FONT_HEIGHT_SMALL;
//	}

	/**
	 * Compute minimal required width of the legends.
	 * @return Minimally needed width for displaying the smallmap legends in pixels.
	 */
	inline uint GetMinLegendWidth() const
	{
		return WD_FRAMERECT_LEFT + this->min_number_of_columns * this->column_width;
	}

	/**
	 * Return number of columns that can be displayed in \a width pixels.
	 * @return Number of columns to display.
	 */
	inline uint GetNumberColumnsLegend(uint width) const
	{
		return width / this->column_width;
	}

	/**
//	 * Compute height given a number of columns.
	 * Compute height given a width.
	 * @param Number of columns.
	 * @return Needed height for displaying the smallmap legends in pixels.
	 */
	uint GetLegendHeight(uint num_columns) const
//	uint GetLegendHeight(uint width) const
	{
//		uint num_rows = max(this->min_number_of_fixed_rows, CeilDiv(max(_smallmap_company_count, _smallmap_industry_count), num_columns));
//		return WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + num_rows * FONT_HEIGHT_SMALL;
// 		uint num_columns = this->GetNumberColumnsLegend(width);
		return WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + this->GetNumberRowsLegend(num_columns) * FONT_HEIGHT_SMALL;
	}

	virtual void SetStringParameters(int widget) const
	{
		switch (widget) {
			case SM_WIDGET_CAPTION:
				SetDParam(0, STR_SMALLMAP_TYPE_CONTOURS + this->map_type);
				break;
		}
	}

	virtual void OnInit()
	{
		uint min_width = 0;
		this->min_number_of_columns = INDUSTRY_MIN_NUMBER_OF_COLUMNS;
//		this->min_number_of_fixed_rows = 0;
		this->min_number_of_fixed_rows = lengthof(_legend_linkstats) / 2 + 1;
		if (AllowMoreHeightlevels()) {
			for (uint i = 0; i < lengthof(_legend_table_extended); i++) {
				uint height = 0;
				uint num_columns = 1;
				for (const LegendAndColour *tbl = _legend_table_extended[i]; !tbl->end; ++tbl) {
					StringID str;
					if (i == SMT_INDUSTRY) {
						SetDParam(0, tbl->legend);
						SetDParam(1, IndustryPool::MAX_SIZE);
						str = STR_SMALLMAP_INDUSTRY;
					} else if (i == SMT_LINKSTATS) {
						SetDParam(0, tbl->legend);
						str = STR_SMALLMAP_LINKSTATS;
					} else if (i == SMT_OWNER) {
						if (tbl->company != INVALID_COMPANY) {
							if (!Company::IsValidID(tbl->company)) {
								/* Rebuild the owner legend. */
								BuildOwnerLegend();
								this->OnInit();
								return;
							}
							/* Non-fixed legend entries for the owner view. */
							SetDParam(0, tbl->company);
							str = STR_SMALLMAP_COMPANY;
						} else {
							str = tbl->legend;
	 					}
					} else {
						if (tbl->col_break) {
							this->min_number_of_fixed_rows = max(this->min_number_of_fixed_rows, height);
							height = 0;
							num_columns++;
						}
						height++;
						str = tbl->legend;
					}
					min_width = max(GetStringBoundingBox(str).width, min_width);
				}
				this->min_number_of_fixed_rows = max(this->min_number_of_fixed_rows, height);
				this->min_number_of_columns = max(this->min_number_of_columns, num_columns);
			}

		} else {
			for (uint i = 0; i < lengthof(_legend_table_old); i++) {
				uint height = 0;
				uint num_columns = 1;
				for (const LegendAndColour *tbl = _legend_table_old[i]; !tbl->end; ++tbl) {
					StringID str;
					if (i == SMT_INDUSTRY) {
						SetDParam(0, tbl->legend);
						SetDParam(1, IndustryPool::MAX_SIZE);
						str = STR_SMALLMAP_INDUSTRY;
					} else if (i == SMT_LINKSTATS) {
						SetDParam(0, tbl->legend);
						str = STR_SMALLMAP_LINKSTATS;
					} else if (i == SMT_OWNER) {
						if (tbl->company != INVALID_COMPANY) {
							if (!Company::IsValidID(tbl->company)) {
								/* Rebuild the owner legend. */
								BuildOwnerLegend();
								this->OnInit();
								return;
							}
							/* Non-fixed legend entries for the owner view. */
							SetDParam(0, tbl->company);
							str = STR_SMALLMAP_COMPANY;
						} else {
							str = tbl->legend;
	 					}
					} else {
						if (tbl->col_break) {
							this->min_number_of_fixed_rows = max(this->min_number_of_fixed_rows, height);
							height = 0;
							num_columns++;
						}
						height++;
						str = tbl->legend;
					}
					min_width = max(GetStringBoundingBox(str).width, min_width);
				}
				this->min_number_of_fixed_rows = max(this->min_number_of_fixed_rows, height);
				this->min_number_of_columns = max(this->min_number_of_columns, num_columns);
			}
		}

		/* The width of a column is the minimum width of all texts + the size of the blob + some spacing */
		this->column_width = min_width + LEGEND_BLOB_WIDTH + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
	}

	virtual void OnPaint()
	{
		if (this->map_type == SMT_OWNER) {
			if (AllowMoreHeightlevels()) {
				for (const LegendAndColour *tbl = _legend_table_extended[this->map_type]; !tbl->end; ++tbl) {
					if (tbl->company != INVALID_COMPANY && !Company::IsValidID(tbl->company)) {
						/* Rebuild the owner legend. */
						BuildOwnerLegend();
						this->InvalidateData(1);
						break;
					}
				}
			} else {
				for (const LegendAndColour *tbl = _legend_table_old[this->map_type]; !tbl->end; ++tbl) {
					if (tbl->company != INVALID_COMPANY && !Company::IsValidID(tbl->company)) {
						/* Rebuild the owner legend. */
						BuildOwnerLegend();
						this->InvalidateData(1);
						break;
					}
				}
			}
		}

		this->DrawWidgets();
	}

	virtual void DrawWidget(const Rect &r, int widget) const
	{
		switch (widget) {
			case SM_WIDGET_MAP: {
				DrawPixelInfo new_dpi;
				if (!FillDrawPixelInfo(&new_dpi, r.left + 1, r.top + 1, r.right - r.left - 1, r.bottom - r.top - 1)) return;
				this->DrawSmallMap(&new_dpi);
				break;
			}

			case SM_WIDGET_LEGEND: {
				uint y_org = r.top + WD_FRAMERECT_TOP;
				uint x = r.left + WD_FRAMERECT_LEFT;
				if (this->supply_details != INVALID_STATION) {
					this->DrawSupplyDetails(x, y_org, r.bottom - WD_FRAMERECT_BOTTOM);
				} else if (!this->link_details.Empty()) {
					this->DrawLinkDetails(x, y_org, r.right - WD_FRAMERECT_RIGHT, r.bottom - WD_FRAMERECT_BOTTOM);
				} else {
					uint columns = this->GetNumberColumnsLegend(r.right - r.left + 1);
					uint number_of_rows = this->GetNumberRowsLegend(columns);
					bool rtl = _current_text_dir == TD_RTL;
					uint y_org = r.top + WD_FRAMERECT_TOP;
					uint x = rtl ? r.right - this->column_width - WD_FRAMERECT_RIGHT : r.left + WD_FRAMERECT_LEFT;
					uint y = y_org;
					uint i = 0; // Row counter for industry legend.
					uint row_height = FONT_HEIGHT_SMALL;

					uint text_left  = rtl ? 0 : LEGEND_BLOB_WIDTH + WD_FRAMERECT_LEFT;
					uint text_right = this->column_width - 1 - (rtl ? LEGEND_BLOB_WIDTH + WD_FRAMERECT_RIGHT : 0);
					uint blob_left  = rtl ? this->column_width - 1 - LEGEND_BLOB_WIDTH : 0;
					uint blob_right = rtl ? this->column_width - 1 : LEGEND_BLOB_WIDTH;

					StringID string = STR_NULL;
					switch (this->map_type) {
						case SMT_INDUSTRY:
							string = STR_SMALLMAP_INDUSTRY;
							break;
						case SMT_LINKSTATS:
							string = STR_SMALLMAP_LINKSTATS;
							break;
						case SMT_OWNER:
							string = STR_SMALLMAP_COMPANY;
							break;
						default:
							break;
					}

					if (AllowMoreHeightlevels()) {
						for (const LegendAndColour *tbl = _legend_table_extended[this->map_type]; !tbl->end; ++tbl) {
							if (tbl->col_break || ((this->map_type == SMT_INDUSTRY || this->map_type == SMT_LINKSTATS || this->map_type == SMT_OWNER) && i++ >= number_of_rows)) {
								/* Column break needed, continue at top, COLUMN_WIDTH pixels
								 * (one "row") to the right. */
								x += rtl ? -(int)this->column_width : this->column_width;
								y = y_org;
								i = 1;
							}

							switch(this->map_type) {
								case SMT_INDUSTRY:
									/* Industry name must be formatted, since it's not in tiny font in the specs.
									 * So, draw with a parameter and use the STR_SMALLMAP_INDUSTRY string, which is tiny font. */
									SetDParam(1, Industry::GetIndustryTypeCount(tbl->type));
								case SMT_LINKSTATS:
									SetDParam(0, tbl->legend);
								case SMT_OWNER:
									if (this->map_type != SMT_OWNER || tbl->company != INVALID_COMPANY) {
										if (this->map_type == SMT_OWNER) SetDParam(0, tbl->company);
										if (!tbl->show_on_map) {
											/* Simply draw the string, not the black border of the legend colour.
											* This will enforce the idea of the disabled item */
											DrawString(x + text_left, x + text_right, y, string, TC_GREY);
										} else {
											DrawString(x + text_left, x + text_right, y, string, TC_BLACK);
											GfxFillRect(x + blob_left, y + 1, x + blob_right, y + row_height - 1, PC_BLACK); // Outer border of the legend colour
										}
									break;
									} // else fall through
								default:
									if (this->map_type == SMT_CONTOUR) SetDParam(0, tbl->height * TILE_HEIGHT_STEP);

									/* Anything that is not an industry or a company is using normal process */
									GfxFillRect(x + blob_left, y + 1, x + blob_right, y + row_height - 1, PC_BLACK);
									DrawString(x + text_left, x + text_right, y, tbl->legend);
									break;
							}
							GfxFillRect(x + blob_left + 1, y + 2, x + blob_right - 1, y + row_height - 2, tbl->colour); // Legend colour.

							y += row_height;
						}
					} else {
						for (const LegendAndColour *tbl = _legend_table_old[this->map_type]; !tbl->end; ++tbl) {
							if (tbl->col_break || ((this->map_type == SMT_INDUSTRY || this->map_type == SMT_LINKSTATS || this->map_type == SMT_OWNER) && i++ >= number_of_rows)) {
								/* Column break needed, continue at top, COLUMN_WIDTH pixels
								 * (one "row") to the right. */
								x += rtl ? -(int)this->column_width : this->column_width;
								y = y_org;
								i = 1;
							}

							switch(this->map_type) {
								case SMT_INDUSTRY:
									/* Industry name must be formatted, since it's not in tiny font in the specs.
									 * So, draw with a parameter and use the STR_SMALLMAP_INDUSTRY string, which is tiny font. */
									SetDParam(1, Industry::GetIndustryTypeCount(tbl->type));
								case SMT_LINKSTATS:
									SetDParam(0, tbl->legend);
								case SMT_OWNER:
									if (this->map_type != SMT_OWNER || tbl->company != INVALID_COMPANY) {
										if (this->map_type == SMT_OWNER) SetDParam(0, tbl->company);
										if (!tbl->show_on_map) {
											/* Simply draw the string, not the black border of the legend colour.
											* This will enforce the idea of the disabled item */
											DrawString(x + text_left, x + text_right, y, string, TC_GREY);
										} else {
											DrawString(x + text_left, x + text_right, y, string, TC_BLACK);
											GfxFillRect(x + blob_left, y + 1, x + blob_right, y + row_height - 1, PC_BLACK); // Outer border of the legend colour
										}
									break;
									} // else fall through
								default:
									if (this->map_type == SMT_CONTOUR) SetDParam(0, tbl->height * TILE_HEIGHT_STEP);

									/* Anything that is not an industry or a company is using normal process */
									GfxFillRect(x + blob_left, y + 1, x + blob_right, y + row_height - 1, PC_BLACK);
									DrawString(x + text_left, x + text_right, y, tbl->legend);
									break;
							}
							GfxFillRect(x + blob_left + 1, y + 2, x + blob_right - 1, y + row_height - 2, tbl->colour); // Legend colour

							y += row_height;
						}
					}
				}
			} break;
		}
	}

	/**
	 * Get the number of rows in the legend from the number of columns. Those
	 * are at least min_number_of_fixed_rows and possibly more if there are so
	 * many cargoes, industry types or companies that they won't fit in the
	 * available space.
	 * @param columns Number of columns in the legend.
	 * @return Number of rows needed for everything to fit in.
	 */
	uint GetNumberRowsLegend(uint columns) const
	{
		/* reserve one column for link colours */
		uint num_rows_linkstats = CeilDiv(_smallmap_cargo_count, columns - 1);

		uint num_rows_others = CeilDiv(max(_smallmap_industry_count,_smallmap_company_count), columns);
		return max(this->min_number_of_fixed_rows, max(num_rows_linkstats, num_rows_others));
	}

	/**
	 * Select and toggle a legend item. When CTRL is pressed, disable all other
	 * items in the group defined by begin_legend_item and end_legend_item and
	 * keep the clicked one enabled even if it was already enabled before. If
	 * the other items in the group are all disabled already and CTRL is pressed
	 * enable them instead.
	 * @param click_pos the index of the item being selected
	 * @param legend the legend from which we select
	 * @param end_legend_item index one past the last item in the group to be inverted
	 * @param begin_legend_item index of the first item in the group to be inverted
	 */
	void SelectLegendItem(int click_pos, LegendAndColour *legend, int end_legend_item, int begin_legend_item = 0)
	{
		if (_ctrl_pressed) {
			/* Disable all, except the clicked one */
			bool changes = false;
			for (int i = begin_legend_item; i != end_legend_item; i++) {
				bool new_state = (i == click_pos);
				if (legend[i].show_on_map != new_state) {
					changes = true;
					legend[i].show_on_map = new_state;
				}
			}
			if (!changes) {
				/* Nothing changed? Then show all (again). */
				for (int i = begin_legend_item; i != end_legend_item; i++) {
					legend[i].show_on_map = true;
				}
			}
		} else {
			legend[click_pos].show_on_map = !legend[click_pos].show_on_map;
		}
	}

	/**
	 * Select a new map type.
	 * @param map_type New map type.
	 */
	void SwitchMapType(SmallMapType map_type)
	{
		this->RaiseWidget(this->map_type + SM_WIDGET_CONTOUR);
		this->map_type = map_type;
		this->LowerWidget(this->map_type + SM_WIDGET_CONTOUR);

		this->SetupWidgetData();

		this->SetDirty();
	}

	virtual void OnClick(Point pt, int widget, int click_count)
	{
		/* User clicked something, notify the industry chain window to stop sending newly selected industries. */
		InvalidateWindowClassesData(WC_INDUSTRY_CARGOES, NUM_INDUSTRYTYPES);

		switch (widget) {
			case SM_WIDGET_MAP: { // Map window
				/*
				 * XXX: scrolling with the left mouse button is done by subsequently
				 * clicking with the left mouse button; clicking once centers the
				 * large map at the selected point. So by unclicking the left mouse
				 * button here, it gets reclicked during the next inputloop, which
				 * would make it look like the mouse is being dragged, while it is
				 * actually being (virtually) clicked every inputloop.
				 */
				_left_button_clicked = false;

				const NWidgetBase *wid = this->GetWidget<NWidgetBase>(SM_WIDGET_MAP);

				/* We need to take the height at the clicked position into account
				 * (i.e. move the map northwards).
				 * Basically, we compute the inverse of function RemapX/Y here.
				 * Note that we have to subtract 2 from x and 16 from y here because
				 * _cursor_pos.x/y - this->left/top includes the edge of the small map. */
				int offset_inside_sm_x = _cursor.pos.x - this->left + wid->pos_x;
				int offset_inside_sm_y = _cursor.pos.y - this->top - wid->pos_y;
				int clicked_screen_x = offset_inside_sm_x * TILE_SIZE + pt.x;
				int clicked_screen_y = offset_inside_sm_y * TILE_SIZE + pt.y;
				Point clicked_tile = TileCoordFromScreenCoord(clicked_screen_x, clicked_screen_y);
				clicked_tile.x /= TILE_SIZE;
				clicked_tile.y /= TILE_SIZE;
				int clicked_tile_height = TileHeightOutsideMap(clicked_tile.x, clicked_tile.y);

				DEBUG(map, 9, "clicked: offset_inside_sm (%i,%i), clicked_tile (%i,%i), clicked_screen (%i,%i), clicked_tile_height %i",
						offset_inside_sm_x, offset_inside_sm_y, clicked_tile.x, clicked_tile.y, clicked_screen_x, clicked_screen_y, clicked_tile_height);

				Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
				int sub;
				pt = this->PixelToWorld(pt.x - wid->pos_x, pt.y - wid->pos_y, &sub);
				int offset = this->zoom > 0 ? this->zoom * TILE_SIZE : TILE_SIZE / (-this->zoom);
				pt = RemapCoords(this->scroll_x + pt.x + offset - offset * sub / 4,
						this->scroll_y + pt.y + sub * offset / 4, 0);

				w->viewport->follow_vehicle = INVALID_VEHICLE;
				w->viewport->dest_scrollpos_x = pt.x - (w->viewport->virtual_width  >> 1);
				w->viewport->dest_scrollpos_y = pt.y - ((clicked_tile_height * TILE_HEIGHT) + (w->viewport->virtual_height >> 1)); // TODO: add moreheightlevels_v29 and merge with cargodist (when clicking the smallmap main vieport positioning is slighlty off)

				DEBUG(map, 9, "OnClick: scroll_x, scroll_y = (%i,%i), pt = (%i,%i), dest_scrollpos = (%i,%i), cursor = (%i,%i), left/top = (%i, %i), virtual = (%i,%i)",
						this->scroll_x, this->scroll_y, pt.x, pt.y,
						w->viewport->dest_scrollpos_x, w->viewport->dest_scrollpos_y,
						_cursor.pos.x, _cursor.pos.y, this->left, this->top,
						w->viewport->virtual_width, w->viewport->virtual_height);

				this->SetDirty();
				break;
			}

			case SM_WIDGET_ZOOM_IN:
			case SM_WIDGET_ZOOM_OUT: {
				const NWidgetBase *wid = this->GetWidget<NWidgetBase>(SM_WIDGET_MAP);
				Point pt = {wid->current_x / 2, wid->current_y / 2};
				this->SetZoomLevel((widget == SM_WIDGET_ZOOM_IN) ? ZLC_ZOOM_IN : ZLC_ZOOM_OUT, &pt);
				SndPlayFx(SND_15_BEEP);
				break;
			}

			case SM_WIDGET_CONTOUR:    // Show land contours
			case SM_WIDGET_VEHICLES:   // Show vehicles
			case SM_WIDGET_INDUSTRIES: // Show industries
			case SM_WIDGET_LINKSTATS:  // Show route map
			case SM_WIDGET_ROUTES:     // Show transport routes
			case SM_WIDGET_VEGETATION: // Show vegetation
			case SM_WIDGET_OWNERS:     // Show land owners
				this->SwitchMapType((SmallMapType)(widget - SM_WIDGET_CONTOUR));
				SndPlayFx(SND_15_BEEP);
				break;

			case SM_WIDGET_CENTERMAP: // Center the smallmap again
				this->SmallMapCenterOnCurrentPos();
				this->HandleButtonClick(SM_WIDGET_CENTERMAP);
				SndPlayFx(SND_15_BEEP);
				break;

			case SM_WIDGET_TOGGLETOWNNAME: // Toggle town names
				this->show_towns = !this->show_towns;
				this->SetWidgetLoweredState(SM_WIDGET_TOGGLETOWNNAME, this->show_towns);

				this->SetDirty();
				SndPlayFx(SND_15_BEEP);
				break;

			case SM_WIDGET_LEGEND: // Legend
				/* If industry type small map*/
				if (this->map_type == SMT_INDUSTRY || this->map_type == SMT_LINKSTATS || this->map_type == SMT_OWNER) {
					/* If click on industries label, find right industry type and enable/disable it */
					const NWidgetBase *wi = this->GetWidget<NWidgetBase>(SM_WIDGET_LEGEND); // Label panel
					uint line = (pt.y - wi->pos_y - WD_FRAMERECT_TOP) / FONT_HEIGHT_SMALL;
					uint columns = this->GetNumberColumnsLegend(wi->current_x);
					uint number_of_rows = this->GetNumberRowsLegend(columns);
					if (line >= number_of_rows) break;

					bool rtl = _current_text_dir == TD_RTL;
					int x = pt.x - wi->pos_x;
					if (rtl) x = wi->current_x - x;
					uint column = (x - WD_FRAMERECT_LEFT) / this->column_width;
					int click_pos = (column * number_of_rows) + line;

					/* Check if click is on industry label*/
					if (this->map_type == SMT_INDUSTRY) {
						if (click_pos < _smallmap_industry_count) {
							this->SelectLegendItem(click_pos, _legend_from_industries, _smallmap_industry_count);
						}
					/* Check if click was on linkstats label*/
					} else if (this->map_type == SMT_LINKSTATS) {
						if (click_pos < _smallmap_cargo_count) {
							this->SelectLegendItem(click_pos, _legend_linkstats, _smallmap_cargo_count);
						} else {
							uint stats_column = CeilDiv(_smallmap_cargo_count, number_of_rows);
							if (column == stats_column && line < NUM_STATS) {
								this->SelectLegendItem(_smallmap_cargo_count + line, _legend_linkstats,
										_smallmap_cargo_count + NUM_STATS, _smallmap_cargo_count);
							}
						}
					/* Check if click is on company label. */
					} else if (this->map_type == SMT_OWNER) {
						if (click_pos < _smallmap_company_count) {
						this->SelectLegendItem(click_pos, _legend_land_owners, _smallmap_company_count, NUM_NO_COMPANY_ENTRIES);
						}
					}
					this->SetDirty();
				}
				break;

			case SM_WIDGET_ENABLE_ALL: // enable/diable all items
			case SM_WIDGET_DISABLE_ALL: {
				LegendAndColour *tbl = NULL;
					switch (this->map_type) {
						case SMT_INDUSTRY:
							tbl = _legend_from_industries;
							break;
						case SMT_OWNER:
							tbl = &(_legend_land_owners[NUM_NO_COMPANY_ENTRIES]);
							break;
						case SMT_LINKSTATS:
							tbl = _legend_linkstats;
							break;
						default:
							NOT_REACHED();
					}

				for (;!tbl->end; ++tbl) tbl->show_on_map = (widget == SM_WIDGET_ENABLE_ALL);
				this->SetDirty();
				break;
			}

			case SM_WIDGET_SHOW_HEIGHT: // Enable/disable showing of heightmap.
				_smallmap_show_heightmap = !_smallmap_show_heightmap;
				this->SetWidgetLoweredState(SM_WIDGET_SHOW_HEIGHT, _smallmap_show_heightmap);
				this->SetDirty();
				break;
		}
	}

	virtual void OnMouseOver(Point pt, int widget)
	{
		static Point invalid = {-1, -1};
		if (widget == SM_WIDGET_MAP) {
			const NWidgetBase *wid = this->GetWidget<NWidgetBase>(SM_WIDGET_MAP);
			pt.x -= wid->pos_x;
			pt.y -= wid->pos_y;
			if (pt.x != cursor.x || pt.y != cursor.y) {
				this->refresh = 1;
				cursor = pt;
			}
		} else {
			cursor = invalid;
		}
	}

	/**
	 * Some data on this window has become invalid.
	 * @param data Information about the changed data.
	 * - data = 0: Displayed industries at the industry chain window have changed.
	 * - data = 1: Companies have changed.
	 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
	 */
	virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
	{
		if (!gui_scope) return;
		switch (data) {
			case 1:
				/* The owner legend has already been rebuilt. */
				this->ReInit();
				break;

			case 0: {
				extern uint64 _displayed_industries;
				if (this->map_type != SMT_INDUSTRY) this->SwitchMapType(SMT_INDUSTRY);

				for (int i = 0; i != _smallmap_industry_count; i++) {
					_legend_from_industries[i].show_on_map = HasBit(_displayed_industries, _legend_from_industries[i].type);
				}
				break;
			}

			default: NOT_REACHED();
		}
		this->SetDirty();
	}

	virtual bool OnRightClick(Point pt, int widget)
	{
		if (widget != SM_WIDGET_MAP || _scrolling_viewport) return false;

		_scrolling_viewport = true;
		return true;
	}

	virtual void OnMouseWheel(int wheel)
	{
		if (_settings_client.gui.scrollwheel_scrolling == 0) {
			const NWidgetBase *wid = this->GetWidget<NWidgetBase>(SM_WIDGET_MAP);
			int cursor_x = _cursor.pos.x - this->left - wid->pos_x;
			int cursor_y = _cursor.pos.y - this->top  - wid->pos_y;
			if (IsInsideMM(cursor_x, 0, wid->current_x) && IsInsideMM(cursor_y, 0, wid->current_y)) {
				Point pt = {cursor_x, cursor_y};
				this->SetZoomLevel((wheel < 0) ? ZLC_ZOOM_IN : ZLC_ZOOM_OUT, &pt);
			}
		}
	}

	virtual void OnTick()
	{
		/* Update the window every now and then */
		if (--this->refresh != 0) return;

		this->RecalcVehiclePositions();

		this->refresh = FORCE_REFRESH_PERIOD;
		this->SetDirty();
	}

	/**
	 * Set new #scroll_x, #scroll_y, and #subscroll values after limiting them such that the center
	 * of the smallmap always contains a part of the map.
	 * @param sx  Proposed new #scroll_x
	 * @param sy  Proposed new #scroll_y
	 * @param sub Proposed new #subscroll
	 */
	void SetNewScroll(int sx, int sy, int sub)
	{
		const NWidgetBase *wi = this->GetWidget<NWidgetBase>(SM_WIDGET_MAP);
		Point hv = InverseRemapCoords(wi->current_x * TILE_SIZE / 2, wi->current_y * TILE_SIZE / 2);
		if (this->zoom > 0) {
			hv.x *= this->zoom;
			hv.y *= this->zoom;
		} else {
			hv.x /= (-this->zoom);
			hv.y /= (-this->zoom);
		}

		if (sx < -hv.x) {
			sx = -hv.x;
			sub = 0;
		}
		if (sx > (int)(MapMaxX() * TILE_SIZE) - hv.x) {
			sx = MapMaxX() * TILE_SIZE - hv.x;
			sub = 0;
		}
		if (sy < -hv.y) {
			sy = -hv.y;
			sub = 0;
		}
		if (sy > (int)(MapMaxY() * TILE_SIZE) - hv.y) {
			sy = MapMaxY() * TILE_SIZE - hv.y;
			sub = 0;
		}

		this->scroll_x = sx;
		this->scroll_y = sy;
		this->subscroll = sub;
	}

	virtual void OnScroll(Point delta)
	{
		_cursor.fix_at = true;

		/* While tile is at (delta.x, delta.y)? */
		int sub;
		Point pt = this->PixelToWorld(delta.x, delta.y, &sub);
		this->SetNewScroll(this->scroll_x + pt.x, this->scroll_y + pt.y, sub);

		this->SetDirty();
	}

	void SmallMapCenterOnCurrentPos()
	{
		const ViewPort *vp = FindWindowById(WC_MAIN_WINDOW, 0)->viewport;
		Point pt = InverseRemapCoords(vp->virtual_left + vp->virtual_width  / 2, vp->virtual_top  + vp->virtual_height / 2);

		int sub;
		const NWidgetBase *wid = this->GetWidget<NWidgetBase>(SM_WIDGET_MAP);
		Point sxy = this->ComputeScroll(pt.x, pt.y, max(0, (int)wid->current_x / 2 - 2), wid->current_y / 2, &sub);
		this->SetNewScroll(sxy.x, sxy.y, sub);
		this->SetDirty();
	}

	uint ColumnWidth() const {return column_width;}
};

SmallMapWindow::SmallMapType SmallMapWindow::map_type = SMT_CONTOUR;
bool SmallMapWindow::show_towns = true;

/**
 * Custom container class for displaying smallmap with a vertically resizing legend panel.
 * The legend panel has a smallest height that depends on its width. Standard containers cannot handle this case.
 *
 * @note The container assumes it has two childs, the first is the display, the second is the bar with legends and selection image buttons.
 *       Both childs should be both horizontally and vertically resizable and horizontally fillable.
 *       The bar should have a minimal size with a zero-size legends display. Child padding is not supported.
 */
class NWidgetSmallmapDisplay : public NWidgetContainer {
	const SmallMapWindow *smallmap_window; ///< Window manager instance.
public:
	NWidgetSmallmapDisplay() : NWidgetContainer(NWID_VERTICAL)
	{
		this->smallmap_window = NULL;
	}

	virtual void SetupSmallestSize(Window *w, bool init_array)
	{
		NWidgetBase *display = this->head;
		NWidgetBase *bar = display->next;

		display->SetupSmallestSize(w, init_array);
		bar->SetupSmallestSize(w, init_array);

		this->smallmap_window = dynamic_cast<SmallMapWindow *>(w);
		this->smallest_x = max(display->smallest_x, bar->smallest_x + smallmap_window->GetMinLegendWidth());
		this->smallest_y = display->smallest_y + max(bar->smallest_y, smallmap_window->GetLegendHeight(smallmap_window->min_number_of_columns));
//		this->smallest_y = display->smallest_y + max(bar->smallest_y, smallmap_window->GetLegendHeight());
		this->fill_x = max(display->fill_x, bar->fill_x);
		this->fill_y = (display->fill_y == 0 && bar->fill_y == 0) ? 0 : min(display->fill_y, bar->fill_y);
		this->resize_x = max(display->resize_x, bar->resize_x);
		this->resize_y = min(display->resize_y, bar->resize_y);
	}

	virtual void AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl)
	{
		this->pos_x = x;
		this->pos_y = y;
		this->current_x = given_width;
		this->current_y = given_height;

		NWidgetBase *display = this->head;
		NWidgetBase *bar = display->next;

		if (sizing == ST_SMALLEST) {
			this->smallest_x = given_width;
			this->smallest_y = given_height;
			/* Make display and bar exactly equal to their minimal size. */
			display->AssignSizePosition(ST_SMALLEST, x, y, display->smallest_x, display->smallest_y, rtl);
			bar->AssignSizePosition(ST_SMALLEST, x, y + display->smallest_y, bar->smallest_x, bar->smallest_y, rtl);
		}

//		uint bar_height = max(bar->smallest_y, this->smallmap_window->GetLegendHeight(this->smallmap_window->GetNumberColumnsLegend(given_width - bar->smallest_x)));
		uint bar_height = max(bar->smallest_y, this->smallmap_window->GetLegendHeight(given_width - bar->smallest_x));
		uint display_height = given_height - bar_height;
		display->AssignSizePosition(ST_RESIZE, x, y, given_width, display_height, rtl);
		bar->AssignSizePosition(ST_RESIZE, x, y + display_height, given_width, bar_height, rtl);
	}

	virtual NWidgetCore *GetWidgetFromPos(int x, int y)
	{
		if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return NULL;
		for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
			NWidgetCore *widget = child_wid->GetWidgetFromPos(x, y);
			if (widget != NULL) return widget;
		}
		return NULL;
	}

	virtual void Draw(const Window *w)
	{
		for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) child_wid->Draw(w);
	}
};

/** Widget parts of the smallmap display. */
static const NWidgetPart _nested_smallmap_display[] = {
	NWidget(WWT_PANEL, COLOUR_BROWN, SM_WIDGET_MAP_BORDER),
		NWidget(WWT_INSET, COLOUR_BROWN, SM_WIDGET_MAP), SetMinimalSize(346, 140), SetResize(1, 1), SetPadding(2, 2, 2, 2), EndContainer(),
	EndContainer(),
};

/** Widget parts of the smallmap legend bar + image buttons. */
static const NWidgetPart _nested_smallmap_bar[] = {
	NWidget(WWT_PANEL, COLOUR_BROWN),
		NWidget(NWID_HORIZONTAL),
			NWidget(WWT_EMPTY, INVALID_COLOUR, SM_WIDGET_LEGEND), SetResize(1, 1),
			NWidget(NWID_VERTICAL),
				/* Top button row. */
				NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
					NWidget(WWT_PUSHIMGBTN, COLOUR_BROWN, SM_WIDGET_ZOOM_IN),
							SetDataTip(SPR_IMG_ZOOMIN, STR_TOOLBAR_TOOLTIP_ZOOM_THE_VIEW_IN), SetFill(1, 1),
					NWidget(WWT_PUSHIMGBTN, COLOUR_BROWN, SM_WIDGET_CENTERMAP),
							SetDataTip(SPR_IMG_SMALLMAP, STR_SMALLMAP_CENTER), SetFill(1, 1),
					NWidget(WWT_IMGBTN, COLOUR_BROWN, SM_WIDGET_BLANK), SetMinimalSize(22, 22),
							SetDataTip(SPR_DOT_SMALL, STR_NULL), SetFill(1, 1),
					NWidget(WWT_IMGBTN, COLOUR_BROWN, SM_WIDGET_CONTOUR),
							SetDataTip(SPR_IMG_SHOW_COUNTOURS, STR_SMALLMAP_TOOLTIP_SHOW_LAND_CONTOURS_ON_MAP), SetFill(1, 1),
					NWidget(WWT_IMGBTN, COLOUR_BROWN, SM_WIDGET_VEHICLES),
							SetDataTip(SPR_IMG_SHOW_VEHICLES, STR_SMALLMAP_TOOLTIP_SHOW_VEHICLES_ON_MAP), SetFill(1, 1),
					NWidget(WWT_IMGBTN, COLOUR_BROWN, SM_WIDGET_INDUSTRIES),
							SetDataTip(SPR_IMG_INDUSTRY, STR_SMALLMAP_TOOLTIP_SHOW_INDUSTRIES_ON_MAP), SetFill(1, 1),
				EndContainer(),
				/* Bottom button row. */
				NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
					NWidget(WWT_PUSHIMGBTN, COLOUR_BROWN, SM_WIDGET_ZOOM_OUT),
							SetDataTip(SPR_IMG_ZOOMOUT, STR_TOOLBAR_TOOLTIP_ZOOM_THE_VIEW_OUT), SetFill(1, 1),
					NWidget(WWT_IMGBTN, COLOUR_BROWN, SM_WIDGET_TOGGLETOWNNAME),
							SetDataTip(SPR_IMG_TOWN, STR_SMALLMAP_TOOLTIP_TOGGLE_TOWN_NAMES_ON_OFF), SetFill(1, 1),
					NWidget(WWT_IMGBTN, COLOUR_BROWN, SM_WIDGET_LINKSTATS),
							SetDataTip(SPR_IMG_GRAPHS, STR_SMALLMAP_TOOLTIP_SHOW_LINK_STATS_ON_MAP), SetFill(1, 1),
					NWidget(WWT_IMGBTN, COLOUR_BROWN, SM_WIDGET_ROUTES),
							SetDataTip(SPR_IMG_SHOW_ROUTES, STR_SMALLMAP_TOOLTIP_SHOW_TRANSPORT_ROUTES_ON), SetFill(1, 1),
					NWidget(WWT_IMGBTN, COLOUR_BROWN, SM_WIDGET_VEGETATION),
							SetDataTip(SPR_IMG_PLANTTREES, STR_SMALLMAP_TOOLTIP_SHOW_VEGETATION_ON_MAP), SetFill(1, 1),
					NWidget(WWT_IMGBTN, COLOUR_BROWN, SM_WIDGET_OWNERS),
							SetDataTip(SPR_IMG_COMPANY_GENERAL, STR_SMALLMAP_TOOLTIP_SHOW_LAND_OWNERS_ON_MAP), SetFill(1, 1),
				EndContainer(),
				NWidget(NWID_SPACER), SetResize(0, 1),
			EndContainer(),
		EndContainer(),
	EndContainer(),
};

static NWidgetBase *SmallMapDisplay(int *biggest_index)
{
	NWidgetContainer *map_display = new NWidgetSmallmapDisplay;

	MakeNWidgets(_nested_smallmap_display, lengthof(_nested_smallmap_display), biggest_index, map_display);
	MakeNWidgets(_nested_smallmap_bar, lengthof(_nested_smallmap_bar), biggest_index, map_display);
	return map_display;
}


static const NWidgetPart _nested_smallmap_widgets[] = {
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
		NWidget(WWT_CAPTION, COLOUR_BROWN, SM_WIDGET_CAPTION), SetDataTip(STR_SMALLMAP_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
		NWidget(WWT_SHADEBOX, COLOUR_BROWN),
		NWidget(WWT_STICKYBOX, COLOUR_BROWN),
	EndContainer(),
	NWidgetFunction(SmallMapDisplay), // Smallmap display and legend bar + image buttons.
	/* Bottom button row and resize box. */
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_PANEL, COLOUR_BROWN),
			NWidget(NWID_HORIZONTAL),
				NWidget(NWID_SELECTION, INVALID_COLOUR, SM_WIDGET_SELECT_BUTTONS),
					NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
						NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, SM_WIDGET_ENABLE_ALL), SetDataTip(STR_SMALLMAP_ENABLE_ALL, STR_NULL),
						NWidget(WWT_PUSHTXTBTN, COLOUR_BROWN, SM_WIDGET_DISABLE_ALL), SetDataTip(STR_SMALLMAP_DISABLE_ALL, STR_NULL),
						NWidget(WWT_TEXTBTN, COLOUR_BROWN, SM_WIDGET_SHOW_HEIGHT), SetDataTip(STR_SMALLMAP_SHOW_HEIGHT, STR_SMALLMAP_TOOLTIP_SHOW_HEIGHT),
					EndContainer(),
					NWidget(NWID_SPACER), SetFill(1, 1),
				EndContainer(),
				NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
			EndContainer(),
		EndContainer(),
		NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
	EndContainer(),
};

static const WindowDesc _smallmap_desc(
	WDP_AUTO, 484, 314,
	WC_SMALLMAP, WC_NONE,
	WDF_UNCLICK_BUTTONS,
	_nested_smallmap_widgets, lengthof(_nested_smallmap_widgets)
);

/**
 * Show the smallmap window.
 */
void ShowSmallMap()
{
	AllocateWindowDescFront<SmallMapWindow>(&_smallmap_desc, 0);
}

/**
 * Scrolls the main window to given coordinates.
 * @param x x coordinate
 * @param y y coordinate
 * @param z z coordinate; -1 to scroll to terrain height
 * @param instant scroll instantly (meaningful only when smooth_scrolling is active)
 * @return did the viewport position change?
 */
bool ScrollMainWindowTo(int x, int y, int z, bool instant)
{
	bool res = ScrollWindowTo(x, y, z, FindWindowById(WC_MAIN_WINDOW, 0), instant);

	/* If a user scrolls to a tile (via what way what so ever) and already is on
	 * that tile (e.g.: pressed twice), move the smallmap to that location,
	 * so you directly see where you are on the smallmap. */

	if (res) return res;

	SmallMapWindow *w = dynamic_cast<SmallMapWindow*>(FindWindowById(WC_SMALLMAP, 0));
	if (w != NULL) w->SmallMapCenterOnCurrentPos();

	return res;
}
