(svn r10766) [NewGRF_ports] -Sync: with trunk r10651-10765 NewGRF_ports
authorrichk
Fri, 03 Aug 2007 18:10:15 +0000
branchNewGRF_ports
changeset 6743 cabfaa4a0295
parent 6742 1337d6c9b97b
child 6744 e7bf3233928b
(svn r10766) [NewGRF_ports] -Sync: with trunk r10651-10765
config.lib
src/ai/default/default.cpp
src/ai/trolly/build.cpp
src/ai/trolly/pathfinder.cpp
src/ai/trolly/trolly.cpp
src/aircraft.h
src/aircraft_cmd.cpp
src/aircraft_gui.cpp
src/airport_gui.cpp
src/autoreplace_gui.cpp
src/bmp.cpp
src/bridge.h
src/bridge_gui.cpp
src/bridge_map.cpp
src/bridge_map.h
src/build_vehicle_gui.cpp
src/cargopacket.cpp
src/cargopacket.h
src/clear_cmd.cpp
src/command.h
src/console.cpp
src/console_cmds.cpp
src/date.cpp
src/depot.cpp
src/depot.h
src/depot_gui.cpp
src/direction.h
src/disaster_cmd.cpp
src/dock_gui.cpp
src/driver.h
src/dummy_land.cpp
src/economy.cpp
src/economy.h
src/elrail.cpp
src/endian_check.cpp
src/engine.cpp
src/engine.h
src/engine_gui.cpp
src/fileio.cpp
src/functions.h
src/genworld_gui.cpp
src/gfx.cpp
src/gfx.h
src/graph_gui.cpp
src/group.h
src/group_cmd.cpp
src/group_gui.cpp
src/industry.h
src/industry_cmd.cpp
src/industry_gui.cpp
src/industry_map.h
src/intro_gui.cpp
src/landscape.cpp
src/landscape.h
src/lang/catalan.txt
src/lang/croatian.txt
src/lang/german.txt
src/lang/polish.txt
src/macros.h
src/main_gui.cpp
src/map.cpp
src/map.h
src/misc_gui.cpp
src/mixer.h
src/music_gui.cpp
src/network/core/udp.cpp
src/network/network_gamelist.cpp
src/network/network_gui.cpp
src/network/network_udp.cpp
src/newgrf_callbacks.h
src/newgrf_canal.cpp
src/newgrf_cargo.cpp
src/newgrf_cargo.h
src/newgrf_commons.h
src/newgrf_engine.cpp
src/newgrf_engine.h
src/newgrf_fsmports.cpp
src/newgrf_fsmports.h
src/newgrf_gui.cpp
src/newgrf_house.cpp
src/newgrf_house.h
src/newgrf_industries.cpp
src/newgrf_industries.h
src/newgrf_industrytiles.cpp
src/newgrf_industrytiles.h
src/newgrf_spritegroup.h
src/newgrf_station.cpp
src/newgrf_station.h
src/news_gui.cpp
src/npf.cpp
src/oldloader.cpp
src/oldpool.cpp
src/oldpool.h
src/openttd.cpp
src/openttd.h
src/order.h
src/order_cmd.cpp
src/order_gui.cpp
src/os/macosx/splash.cpp
src/os2.cpp
src/player.h
src/player_gui.cpp
src/queue.h
src/rail.cpp
src/rail.h
src/rail_cmd.cpp
src/rail_gui.cpp
src/rail_map.h
src/road.h
src/road_cmd.cpp
src/road_gui.cpp
src/road_map.cpp
src/road_map.h
src/roadveh.h
src/roadveh_cmd.cpp
src/roadveh_gui.cpp
src/saveload.cpp
src/settings_gui.cpp
src/ship.h
src/ship_cmd.cpp
src/ship_gui.cpp
src/signs.cpp
src/signs.h
src/signs_gui.cpp
src/slope.h
src/smallmap_gui.cpp
src/sprite.h
src/station.cpp
src/station.h
src/station_cmd.cpp
src/station_gui.cpp
src/station_map.h
src/strgen/strgen.cpp
src/string.h
src/strings.cpp
src/strings.h
src/subsidy_gui.cpp
src/table/ai_rail.h
src/table/build_industry.h
src/table/sprites.h
src/terraform_gui.cpp
src/thread.h
src/tile.cpp
src/tile.h
src/timetable_gui.cpp
src/town.h
src/town_cmd.cpp
src/town_gui.cpp
src/town_map.h
src/train_cmd.cpp
src/train_gui.cpp
src/transparency_gui.cpp
src/tree_cmd.cpp
src/tunnel_map.cpp
src/tunnelbridge_cmd.cpp
src/unmovable_cmd.cpp
src/variables.h
src/vehicle.cpp
src/vehicle.h
src/vehicle_gui.cpp
src/video/cocoa_v.mm
src/video/sdl_v.cpp
src/video/win32_v.cpp
src/viewport.cpp
src/viewport.h
src/water_cmd.cpp
src/waypoint.cpp
src/waypoint.h
src/win32.cpp
src/window.cpp
src/window.h
src/yapf/yapf_costrail.hpp
src/yapf/yapf_road.cpp
--- a/config.lib	Tue Jul 31 23:31:45 2007 +0000
+++ b/config.lib	Fri Aug 03 18:10:15 2007 +0000
@@ -62,7 +62,7 @@
 	with_psp_config="1"
 	with_threads="1"
 
-	save_params_array="build host cc_build cc_host cxx_build cxx_host windres strip awk lipo os cpu_type revision endian config_log prefix_dir binary_dir data_dir icon_dir personal_dir install_dir enable_install enable_debug enable_profiling enable_dedicated enable_network enable_static enable_translator enable_assert enable_strip with_distcc with_osx_sysroot enable_universal enable_osx_g5 enable_unicode with_application_bundle with_sdl with_cocoa with_zlib with_png with_makedepend with_direct_music with_sort with_iconv with_midi with_midi_arg with_libtimidity with_freetype with_fontconfig with_psp_config with_threads CC CXX CFLAGS LDFLAGS"
+	save_params_array="build host cc_build cc_host cxx_build cxx_host windres strip awk lipo os cpu_type revision endian config_log prefix_dir binary_dir data_dir icon_dir personal_dir install_dir enable_debug enable_profiling enable_dedicated enable_network enable_static enable_translator enable_assert enable_strip with_distcc with_osx_sysroot enable_universal enable_osx_g5 enable_unicode with_application_bundle with_sdl with_cocoa with_zlib with_png with_makedepend with_direct_music with_sort with_iconv with_midi with_midi_arg with_libtimidity with_freetype with_fontconfig with_psp_config with_threads CC CXX CFLAGS LDFLAGS"
 }
 
 detect_params() {
--- a/src/ai/default/default.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/ai/default/default.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -426,7 +426,7 @@
 {
 	const Vehicle* v = p->ai.cur_veh;
 
-	if (!IsValidVehicle(v) ||
+	if (!v->IsValid() ||
 			v->owner != _current_player ||
 			v->type > VEH_SHIP ||
 			_veh_check_replace_proc[v->type - VEH_TRAIN](p, v) == INVALID_ENGINE) {
@@ -443,7 +443,7 @@
 
 	p->ai.state = AIS_VEH_LOOP;
 	// vehicle is not owned by the player anymore, something went very wrong.
-	if (!IsValidVehicle(v) || v->owner != _current_player) return;
+	if (!v->IsValid() || v->owner != _current_player) return;
 	_veh_do_replace_proc[v->type - VEH_TRAIN](p);
 }
 
@@ -462,7 +462,7 @@
 static Industry *AiFindRandomIndustry()
 {
 	int num = RandomRange(GetMaxIndustryIndex());
-	if (IsValidIndustry(GetIndustry(num))) return GetIndustry(num);
+	if (IsValidIndustryID(num)) return GetIndustry(num);
 
 	return NULL;
 }
@@ -1691,7 +1691,7 @@
 			/* signals too? */
 			if (j & 3) {
 				// Can't build signals on a road.
-				if (IsTileType(c, MP_STREET)) return CMD_ERROR;
+				if (IsTileType(c, MP_ROAD)) return CMD_ERROR;
 
 				if (flag & DC_EXEC) {
 					j = 4 - j;
@@ -1774,7 +1774,7 @@
 	8,  4
 };
 
-static void AiDoTerraformLand(TileIndex tile, int dir, int unk, int mode)
+static void AiDoTerraformLand(TileIndex tile, DiagDirection dir, int unk, int mode)
 {
 	PlayerID old_player;
 	uint32 r;
@@ -1793,10 +1793,8 @@
 
 		r >>= 2;
 		if (r & 2) {
-			dir++;
-			if (r & 1) dir -= 2;
+			dir = ChangeDiagDir(dir, (r & 1) ? DIAGDIRDIFF_90LEFT : DIAGDIRDIFF_90RIGHT);
 		}
-		dir &= 3;
 	} while (--unk >= 0);
 
 	slope = GetTileSlope(tile, &h);
@@ -1855,7 +1853,7 @@
 			if (rule == -1) {
 				// cannot build, terraform after a while
 				if (p->ai.state_counter >= 600) {
-					AiDoTerraformLand(aib->use_tile, Random() & 3, 3, (int8)p->ai.state_mode);
+					AiDoTerraformLand(aib->use_tile, (DiagDirection)(Random() & 3), 3, (int8)p->ai.state_mode);
 				}
 				// also try the other terraform direction
 				if (++p->ai.state_counter >= 1000) {
@@ -1888,7 +1886,7 @@
 	p->ai.state_mode = 255;
 }
 
-static TileIndex AiGetEdgeOfDefaultRailBlock(byte rule, TileIndex tile, byte cmd, int *dir)
+static TileIndex AiGetEdgeOfDefaultRailBlock(byte rule, TileIndex tile, byte cmd, DiagDirection *dir)
 {
 	const AiDefaultBlockData *p = _default_rail_track_data[rule]->data;
 
@@ -1926,18 +1924,18 @@
 	arpfd.tile2 = p->ai.cur_tile_a;
 	arpfd.flag = false;
 	arpfd.count = 0;
-	FollowTrack(p->ai.cur_tile_a + TileOffsByDiagDir(p->ai.cur_dir_a), 0x2000 | TRANSPORT_RAIL, 0, (DiagDirection)(p->ai.cur_dir_a ^ 2),
+	FollowTrack(p->ai.cur_tile_a + TileOffsByDiagDir(p->ai.cur_dir_a), 0x2000 | TRANSPORT_RAIL, 0, ReverseDiagDir(p->ai.cur_dir_a),
 		(TPFEnumProc*)AiEnumFollowTrack, NULL, &arpfd);
 	return arpfd.count > 8;
 }
 
 struct AiRailFinder {
 	TileIndex final_tile;
-	byte final_dir;
+	DiagDirection final_dir;
 	byte depth;
 	byte recursive_mode;
-	byte cur_best_dir;
-	byte best_dir;
+	DiagDirection cur_best_dir;
+	DiagDirection best_dir;
 	byte cur_best_depth;
 	byte best_depth;
 	uint cur_best_dist;
@@ -1988,7 +1986,7 @@
 	}
 }
 
-static void AiBuildRailRecursive(AiRailFinder *arf, TileIndex tile, int dir);
+static void AiBuildRailRecursive(AiRailFinder *arf, TileIndex tile, DiagDirection dir);
 
 static bool AiCheckRailPathBetter(AiRailFinder *arf, const byte *p)
 {
@@ -2027,7 +2025,7 @@
 	uint z;
 	bool flag;
 
-	int dir2 = p[0] & 3;
+	DiagDirection dir2 = (DiagDirection)(p[0] & 3);
 
 	tileh = GetTileSlope(tile, &z);
 	if (tileh == _dir_table_1[dir2] || (tileh == SLOPE_FLAT && z != 0)) {
@@ -2046,7 +2044,7 @@
 				if (!flag) return;
 				break;
 			}
-			if (type != MP_WATER && type != MP_RAILWAY && type != MP_STREET) return;
+			if (type != MP_WATER && type != MP_RAILWAY && type != MP_ROAD) return;
 			flag = true;
 		}
 
@@ -2071,14 +2069,14 @@
 		CommandCost cost = DoCommand(tile, arf->player->ai.railtype_to_use, 0, DC_AUTO, CMD_BUILD_TUNNEL);
 
 		if (CmdSucceeded(cost) && cost.GetCost() <= (arf->player->player_money >> 4)) {
-			AiBuildRailRecursive(arf, _build_tunnel_endtile, p[0] & 3);
+			AiBuildRailRecursive(arf, _build_tunnel_endtile, (DiagDirection)(p[0] & 3));
 			if (arf->depth == 1) AiCheckRailPathBetter(arf, p);
 		}
 	}
 }
 
 
-static void AiBuildRailRecursive(AiRailFinder *arf, TileIndex tile, int dir)
+static void AiBuildRailRecursive(AiRailFinder *arf, TileIndex tile, DiagDirection dir)
 {
 	const byte *p;
 
@@ -2086,7 +2084,7 @@
 
 	// Reached destination?
 	if (tile == arf->final_tile) {
-		if (arf->final_dir != (dir ^ 2)) {
+		if (arf->final_dir != ReverseDiagDir(dir)) {
 			if (arf->recursive_mode != 2) arf->recursive_mode = 1;
 		} else if (arf->recursive_mode != 2) {
 			arf->recursive_mode = 2;
@@ -2125,7 +2123,7 @@
 			// Make sure the tile is not in the list of banned tiles and that a rail can be built here.
 			if (!AiIsTileBanned(arf->player, tile, p[0]) &&
 					CmdSucceeded(DoCommand(tile, arf->player->ai.railtype_to_use, p[0], DC_AUTO | DC_NO_WATER | DC_NO_RAIL_OVERLAP, CMD_BUILD_SINGLE_RAIL))) {
-				AiBuildRailRecursive(arf, tile, p[1]);
+				AiBuildRailRecursive(arf, tile, (DiagDirection)p[1]);
 			}
 
 			// At the bottom depth?
@@ -2228,7 +2226,7 @@
 		p->ai.state_counter = 0;
 	} else {
 		// rail
-		p->ai.cur_dir_a = arf.best_ptr[1];
+		p->ai.cur_dir_a = (DiagDirection)(arf.best_ptr[1] & 3);
 		DoCommand(p->ai.cur_tile_a, p->ai.railtype_to_use, arf.best_ptr[0],
 			DC_EXEC | DC_AUTO | DC_NO_WATER | DC_NO_RAIL_OVERLAP, CMD_BUILD_SINGLE_RAIL);
 		p->ai.state_counter = 0;
@@ -2290,9 +2288,9 @@
 		return false;
 
 	// Find the direction at the other edge of the rail.
-	ptr = _ai_table_15[p->ai.cur_dir_a ^ 2];
+	ptr = _ai_table_15[ReverseDiagDir(p->ai.cur_dir_a)];
 	while (ptr[0] != bit) ptr += 2;
-	p->ai.cur_dir_a = ptr[1] ^ 2;
+	p->ai.cur_dir_a = ReverseDiagDir((DiagDirection)ptr[1]);
 
 	// And then also switch tile.
 	p->ai.cur_tile_a = TILE_MASK(p->ai.cur_tile_a - TileOffsByDiagDir(p->ai.cur_dir_a));
@@ -2351,7 +2349,7 @@
 	AiBuildRec *aib;
 	byte cmd;
 	TileIndex tile;
-	int dir;
+	DiagDirection dir;
 
 	// time out?
 	if (++p->ai.timeout_counter == 1388) {
@@ -2641,7 +2639,7 @@
 		_cleared_town = NULL;
 
 		if (p->mode == 2) {
-			if (IsTileType(c, MP_STREET) &&
+			if (IsTileType(c, MP_ROAD) &&
 					GetRoadTileType(c) == ROAD_TILE_NORMAL &&
 					(GetRoadBits(c, ROADTYPE_ROAD) & p->attr) != 0) {
 				roadflag |= 2;
@@ -2684,7 +2682,7 @@
 
 			if (GetTileSlope(c, NULL) != SLOPE_FLAT) return CMD_ERROR;
 
-			if (!IsTileType(c, MP_STREET) || GetRoadTileType(c) != ROAD_TILE_NORMAL) {
+			if (!IsTileType(c, MP_ROAD) || GetRoadTileType(c) != ROAD_TILE_NORMAL) {
 				ret = DoCommand(c, 0, 0, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_LANDSCAPE_CLEAR);
 				if (CmdFailed(ret)) return CMD_ERROR;
 			}
@@ -2751,7 +2749,7 @@
 			if (rule == -1) {
 				// cannot build, terraform after a while
 				if (p->ai.state_counter >= 600) {
-					AiDoTerraformLand(aib->use_tile, Random() & 3, 3, (int8)p->ai.state_mode);
+					AiDoTerraformLand(aib->use_tile, (DiagDirection)(Random() & 3), 3, (int8)p->ai.state_mode);
 				}
 				// also try the other terraform direction
 				if (++p->ai.state_counter >= 1000) {
@@ -2788,11 +2786,11 @@
 
 struct AiRoadFinder {
 	TileIndex final_tile;
-	byte final_dir;
+	DiagDirection final_dir;
 	byte depth;
 	byte recursive_mode;
-	byte cur_best_dir;
-	byte best_dir;
+	DiagDirection cur_best_dir;
+	DiagDirection best_dir;
 	byte cur_best_depth;
 	byte best_depth;
 	uint cur_best_dist;
@@ -2810,13 +2808,13 @@
 	uint best_dist;
 };
 
-static const byte _dir_by_track[] = {
-	0, 1, 0, 1, 2, 1,
-	0, 0,
-	2, 3, 3, 2, 3, 0,
+static const DiagDirection _dir_by_track[] = {
+	DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_SE,
+	DIAGDIR_NE, DIAGDIR_NE,
+	DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NE,
 };
 
-static void AiBuildRoadRecursive(AiRoadFinder *arf, TileIndex tile, int dir);
+static void AiBuildRoadRecursive(AiRoadFinder *arf, TileIndex tile, DiagDirection dir);
 
 static bool AiCheckRoadPathBetter(AiRoadFinder *arf, const byte *p)
 {
@@ -2859,7 +2857,7 @@
 	if (dist <= a->best_dist) {
 		TileIndex tile2 = TILE_MASK(tile + TileOffsByDiagDir(_dir_by_track[track]));
 
-		if (IsTileType(tile2, MP_STREET) && GetRoadTileType(tile2) == ROAD_TILE_NORMAL) {
+		if (IsTileType(tile2, MP_ROAD) && GetRoadTileType(tile2) == ROAD_TILE_NORMAL) {
 			a->best_dist = dist;
 			a->best_tile = tile;
 			a->best_track = track;
@@ -2880,7 +2878,7 @@
 {
 	AiRoadEnum are;
 	TileIndex tile;
-	int dir = p->ai.cur_dir_a;
+	DiagDirection dir = p->ai.cur_dir_a;
 	uint32 bits;
 	int i;
 
@@ -2926,7 +2924,7 @@
 	uint z;
 	bool flag;
 
-	int dir2 = p[0] & 3;
+	DiagDirection dir2 = (DiagDirection)(p[0] & 3);
 
 	tileh = GetTileSlope(tile, &z);
 	if (tileh == _dir_table_1[dir2] || (tileh == SLOPE_FLAT && z != 0)) {
@@ -2947,7 +2945,7 @@
 				if (!flag) return;
 				break;
 			}
-			if (type != MP_WATER && type != MP_RAILWAY && type != MP_STREET) return;
+			if (type != MP_WATER && type != MP_RAILWAY && type != MP_ROAD) return;
 			flag = true;
 		}
 
@@ -2971,7 +2969,7 @@
 		CommandCost cost = DoCommand(tile, 0x200, 0, DC_AUTO, CMD_BUILD_TUNNEL);
 
 		if (CmdSucceeded(cost) && cost.GetCost() <= (arf->player->player_money >> 4)) {
-			AiBuildRoadRecursive(arf, _build_tunnel_endtile, p[0] & 3);
+			AiBuildRoadRecursive(arf, _build_tunnel_endtile, (DiagDirection)(p[0] & 3));
 			if (arf->depth == 1)  AiCheckRoadPathBetter(arf, p);
 		}
 	}
@@ -2979,7 +2977,7 @@
 
 
 
-static void AiBuildRoadRecursive(AiRoadFinder *arf, TileIndex tile, int dir)
+static void AiBuildRoadRecursive(AiRoadFinder *arf, TileIndex tile, DiagDirection dir)
 {
 	const byte *p;
 
@@ -2987,7 +2985,7 @@
 
 	// Reached destination?
 	if (tile == arf->final_tile) {
-		if ((arf->final_dir ^ 2) == dir) {
+		if (ReverseDiagDir(arf->final_dir) == dir) {
 			arf->recursive_mode = 2;
 			arf->cur_best_depth = arf->depth;
 		}
@@ -3020,7 +3018,7 @@
 		do {
 			// Make sure that a road can be built here.
 			if (AiBuildRoadHelper(tile, DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, p[0])) {
-				AiBuildRoadRecursive(arf, tile, p[1]);
+				AiBuildRoadRecursive(arf, tile, (DiagDirection)p[1]);
 			}
 
 			// At the bottom depth?
@@ -3081,7 +3079,7 @@
 			p->ai.state_mode = 1;
 
 			p->ai.cur_tile_a = TILE_MASK(p->ai.cur_tile_a + TileOffsByDiagDir(p->ai.cur_dir_a));
-			p->ai.cur_dir_a ^= 2;
+			p->ai.cur_dir_a = ReverseDiagDir(p->ai.cur_dir_a);
 			p->ai.state_counter = 0;
 		}
 		return;
@@ -3121,7 +3119,7 @@
 		if (!AiBuildRoadHelper(tile, DC_EXEC | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, arf.best_ptr[0]))
 			goto do_some_terraform;
 
-		p->ai.cur_dir_a = arf.best_ptr[1];
+		p->ai.cur_dir_a = (DiagDirection)(arf.best_ptr[1] & 3);
 		p->ai.cur_tile_a = tile;
 		p->ai.state_counter = 0;
 	}
@@ -3157,7 +3155,7 @@
 	}
 }
 
-static TileIndex AiGetRoadBlockEdge(byte rule, TileIndex tile, int *dir)
+static TileIndex AiGetRoadBlockEdge(byte rule, TileIndex tile, DiagDirection *dir)
 {
 	const AiDefaultBlockData *p = _road_default_block_data[rule]->data;
 	while (p->mode != 1) p++;
@@ -3172,7 +3170,7 @@
 	AiBuildRec *aib;
 	byte cmd;
 	TileIndex tile;
-	int dir;
+	DiagDirection dir;
 
 	// time out?
 	if (++p->ai.timeout_counter == 1388) {
@@ -3477,7 +3475,7 @@
 			if (rule == -1) {
 				// cannot build, terraform after a while
 				if (p->ai.state_counter >= 600) {
-					AiDoTerraformLand(aib->use_tile, Random() & 3, 3, (int8)p->ai.state_mode);
+					AiDoTerraformLand(aib->use_tile, (DiagDirection)(Random() & 3), 3, (int8)p->ai.state_mode);
 				}
 				// also try the other terraform direction
 				if (++p->ai.state_counter >= 1000) {
@@ -3682,7 +3680,7 @@
 			if (rails & TRACK_BIT_3WAY_NE) {
 pos_0:
 				if ((GetRailTrackStatus(TILE_MASK(tile - TileDiffXY(1, 0))) & TRACK_BIT_3WAY_SW) == 0) {
-					p->ai.cur_dir_a = 0;
+					p->ai.cur_dir_a = DIAGDIR_NE;
 					p->ai.cur_tile_a = tile;
 					p->ai.state = AIS_REMOVE_SINGLE_RAIL_TILE;
 					return;
@@ -3692,7 +3690,7 @@
 			if (rails & TRACK_BIT_3WAY_SE) {
 pos_1:
 				if ((GetRailTrackStatus(TILE_MASK(tile + TileDiffXY(0, 1))) & TRACK_BIT_3WAY_NW) == 0) {
-					p->ai.cur_dir_a = 1;
+					p->ai.cur_dir_a = DIAGDIR_SE;
 					p->ai.cur_tile_a = tile;
 					p->ai.state = AIS_REMOVE_SINGLE_RAIL_TILE;
 					return;
@@ -3702,7 +3700,7 @@
 			if (rails & TRACK_BIT_3WAY_SW) {
 pos_2:
 				if ((GetRailTrackStatus(TILE_MASK(tile + TileDiffXY(1, 0))) & TRACK_BIT_3WAY_NE) == 0) {
-					p->ai.cur_dir_a = 2;
+					p->ai.cur_dir_a = DIAGDIR_SW;
 					p->ai.cur_tile_a = tile;
 					p->ai.state = AIS_REMOVE_SINGLE_RAIL_TILE;
 					return;
@@ -3712,7 +3710,7 @@
 			if (rails & TRACK_BIT_3WAY_NW) {
 pos_3:
 				if ((GetRailTrackStatus(TILE_MASK(tile - TileDiffXY(0, 1))) & TRACK_BIT_3WAY_SE) == 0) {
-					p->ai.cur_dir_a = 3;
+					p->ai.cur_dir_a = DIAGDIR_NW;
 					p->ai.cur_tile_a = tile;
 					p->ai.state = AIS_REMOVE_SINGLE_RAIL_TILE;
 					return;
@@ -3728,7 +3726,7 @@
 
 			DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
 		}
-	} else if (IsTileType(tile, MP_STREET)) {
+	} else if (IsTileType(tile, MP_ROAD)) {
 		if (!IsTileOwner(tile, _current_player)) return;
 
 		if (IsLevelCrossing(tile)) goto is_rail_crossing;
--- a/src/ai/trolly/build.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/ai/trolly/build.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -199,7 +199,7 @@
 					// Build the tile
 					res = AI_DoCommand(route[part], dir, 0, flag | DC_NO_WATER, CMD_BUILD_ROAD);
 					// Currently, we ignore CMD_ERRORs!
-					if (CmdFailed(res) && flag == DC_EXEC && !IsTileType(route[part], MP_STREET) && !EnsureNoVehicle(route[part])) {
+					if (CmdFailed(res) && flag == DC_EXEC && !IsTileType(route[part], MP_ROAD) && !EnsureNoVehicle(route[part])) {
 						// Problem.. let's just abort it all!
 						DEBUG(ai, 0, "[BuidPath] route building failed at tile 0x%X, aborting", route[part]);
 						p->ainew.state = AI_STATE_NOTHING;
--- a/src/ai/trolly/pathfinder.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/ai/trolly/pathfinder.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -41,8 +41,8 @@
 static bool IsRoad(TileIndex tile)
 {
 	return
-		// MP_STREET, but not a road depot?
-		(IsTileType(tile, MP_STREET) && !IsTileDepotType(tile, TRANSPORT_ROAD)) ||
+		// MP_ROAD, but not a road depot?
+		(IsTileType(tile, MP_ROAD) && !IsTileDepotType(tile, TRANSPORT_ROAD)) ||
 		(IsTileType(tile, MP_TUNNELBRIDGE) && (
 			(IsTunnel(tile) && GetTunnelTransportType(tile) == TRANSPORT_ROAD) ||
 			(IsBridge(tile) && GetBridgeTransportType(tile) == TRANSPORT_ROAD)
@@ -319,7 +319,7 @@
 		// Bridges can only be build on land that is not flat
 		//  And if there is a road or rail blocking
 		if (tileh != SLOPE_FLAT ||
-				(PathFinderInfo->rail_or_road && IsTileType(tile + TileOffsByDiagDir(dir), MP_STREET)) ||
+				(PathFinderInfo->rail_or_road && IsTileType(tile + TileOffsByDiagDir(dir), MP_ROAD)) ||
 				(!PathFinderInfo->rail_or_road && IsTileType(tile + TileOffsByDiagDir(dir), MP_RAILWAY))) {
 			for (;;) {
 				new_tile += TileOffsByDiagDir(dir);
@@ -362,9 +362,9 @@
 }
 
 
-extern uint GetRailFoundation(Slope tileh, TrackBits bits); // XXX function declaration in .c
-extern uint GetRoadFoundation(Slope tileh, RoadBits bits); // XXX function declaration in .c
-extern uint GetBridgeFoundation(Slope tileh, Axis); // XXX function declaration in .c
+extern Foundation GetRailFoundation(Slope tileh, TrackBits bits); // XXX function declaration in .c
+extern Foundation GetRoadFoundation(Slope tileh, RoadBits bits); // XXX function declaration in .c
+extern Foundation GetBridgeFoundation(Slope tileh, Axis); // XXX function declaration in .c
 enum BridgeFoundation {
 	BRIDGE_NO_FOUNDATION = 1 << 0 | 1 << 3 | 1 << 6 | 1 << 9 | 1 << 12,
 };
@@ -373,7 +373,7 @@
 static int32 AyStar_AiPathFinder_CalculateG(AyStar *aystar, AyStarNode *current, OpenListNode *parent)
 {
 	Ai_PathFinderInfo *PathFinderInfo = (Ai_PathFinderInfo*)aystar->user_target;
-	int r, res = 0;
+	int res = 0;
 	Slope tileh = GetTileSlope(current->tile, NULL);
 	Slope parent_tileh = GetTileSlope(parent->path.node.tile, NULL);
 
@@ -409,17 +409,17 @@
 		// Skip if the tile was from a bridge or tunnel
 		if (parent->path.node.user_data[0] == 0 && current->user_data[0] == 0) {
 			if (PathFinderInfo->rail_or_road) {
-				r = GetRailFoundation(parent_tileh, (TrackBits)(1 << AiNew_GetRailDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile)));
+				Foundation f = GetRailFoundation(parent_tileh, (TrackBits)(1 << AiNew_GetRailDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile)));
 				// Maybe is BRIDGE_NO_FOUNDATION a bit strange here, but it contains just the right information..
-				if (r >= 15 || (r == 0 && HASBIT(BRIDGE_NO_FOUNDATION, tileh))) {
+				if (IsInclinedFoundation(f) || (!IsFoundation(f) && HASBIT(BRIDGE_NO_FOUNDATION, parent_tileh))) {
 					res += AI_PATHFINDER_TILE_GOES_UP_PENALTY;
 				} else {
 					res += AI_PATHFINDER_FOUNDATION_PENALTY;
 				}
 			} else {
 				if (!IsRoad(parent->path.node.tile) || !IsTileType(parent->path.node.tile, MP_TUNNELBRIDGE)) {
-					r = GetRoadFoundation(parent_tileh, (RoadBits)AiNew_GetRoadDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile));
-					if (r >= 15 || r == 0) {
+					Foundation f = GetRoadFoundation(parent_tileh, (RoadBits)AiNew_GetRoadDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile));
+					if (IsInclinedFoundation(f) || (!IsFoundation(f) == 0 && HASBIT(BRIDGE_NO_FOUNDATION, parent_tileh))) {
 						res += AI_PATHFINDER_TILE_GOES_UP_PENALTY;
 					} else {
 						res += AI_PATHFINDER_FOUNDATION_PENALTY;
@@ -431,6 +431,7 @@
 
 	// Are we part of a tunnel?
 	if ((AI_PATHFINDER_FLAG_TUNNEL & current->user_data[0]) != 0) {
+		int r;
 		// Tunnels are very expensive when build on long routes..
 		// Ironicly, we are using BridgeCode here ;)
 		r = AI_PATHFINDER_TUNNEL_PENALTY * GetBridgeLength(current->tile, parent->path.node.tile);
@@ -444,13 +445,13 @@
 		// Check if we are going up or down, first for the starting point
 		// In user_data[0] is at the 8th bit the direction
 		if (!HASBIT(BRIDGE_NO_FOUNDATION, parent_tileh)) {
-			if (GetBridgeFoundation(parent_tileh, (Axis)((current->user_data[0] >> 8) & 1)) < 15) {
+			if (IsLeveledFoundation(GetBridgeFoundation(parent_tileh, (Axis)((current->user_data[0] >> 8) & 1)))) {
 				res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
 			}
 		}
 		// Second for the end point
 		if (!HASBIT(BRIDGE_NO_FOUNDATION, tileh)) {
-			if (GetBridgeFoundation(tileh, (Axis)((current->user_data[0] >> 8) & 1)) < 15) {
+			if (IsLeveledFoundation(GetBridgeFoundation(tileh, (Axis)((current->user_data[0] >> 8) & 1)))) {
 				res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
 			}
 		}
--- a/src/ai/trolly/trolly.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/ai/trolly/trolly.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -573,7 +573,7 @@
 	int count = 0;
 	EngineID i;
 	TileIndex new_tile = 0;
-	byte direction = 0;
+	DiagDirection direction = DIAGDIR_NE;
 	Town *town = NULL;
 	assert(p->ainew.state == AI_STATE_FIND_STATION);
 
@@ -692,13 +692,13 @@
 		r = AiNew_Build_Station(p, p->ainew.tbt, new_tile, 0, 0, 0, DC_QUERY_COST);
 		p->ainew.new_cost += r.GetCost();
 
-		direction = AI_PATHFINDER_NO_DIRECTION;
+		direction = (DiagDirection)AI_PATHFINDER_NO_DIRECTION;
 	} else if (new_tile == 0 && p->ainew.tbt == AI_TRUCK) {
 		// Truck station locater works differently.. a station can be on any place
 		//  as long as it is in range. So we give back code AI_STATION_RANGE
 		//  so the pathfinder routine can work it out!
 		new_tile = AI_STATION_RANGE;
-		direction = AI_PATHFINDER_NO_DIRECTION;
+		direction = (DiagDirection)AI_PATHFINDER_NO_DIRECTION;
 	}
 
 	if (p->ainew.from_tile == 0) {
@@ -800,7 +800,7 @@
 		for (j = DIAGDIR_BEGIN; j < DIAGDIR_END; j++) {
 			TileIndex t = tile + TileOffsByDiagDir(j);
 
-			if (IsTileType(t, MP_STREET) &&
+			if (IsTileType(t, MP_ROAD) &&
 					GetRoadTileType(t) == ROAD_TILE_DEPOT &&
 					IsTileOwner(t, _current_player) &&
 					GetRoadDepotDirection(t) == ReverseDiagDir(j)) {
@@ -1035,58 +1035,54 @@
 		if (p->ainew.tbt == AI_TRUCK && !_patches.roadveh_queue) {
 			// If they not queue, they have to go up and down to try again at a station...
 			// We don't want that, so try building some road left or right of the station
-			int dir1, dir2, dir3;
+			DiagDirection dir1, dir2, dir3;
 			TileIndex tile;
 			CommandCost ret;
 			for (int i = 0; i < 2; i++) {
 				if (i == 0) {
 					tile = p->ainew.from_tile + TileOffsByDiagDir(p->ainew.from_direction);
-					dir1 = p->ainew.from_direction - 1;
-					if (dir1 < 0) dir1 = 3;
-					dir2 = p->ainew.from_direction + 1;
-					if (dir2 > 3) dir2 = 0;
+					dir1 = ChangeDiagDir(p->ainew.from_direction, DIAGDIRDIFF_90LEFT);
+					dir2 = ChangeDiagDir(p->ainew.from_direction, DIAGDIRDIFF_90RIGHT);
 					dir3 = p->ainew.from_direction;
 				} else {
 					tile = p->ainew.to_tile + TileOffsByDiagDir(p->ainew.to_direction);
-					dir1 = p->ainew.to_direction - 1;
-					if (dir1 < 0) dir1 = 3;
-					dir2 = p->ainew.to_direction + 1;
-					if (dir2 > 3) dir2 = 0;
+					dir1 = ChangeDiagDir(p->ainew.to_direction, DIAGDIRDIFF_90LEFT);
+					dir2 = ChangeDiagDir(p->ainew.to_direction, DIAGDIRDIFF_90RIGHT);
 					dir3 = p->ainew.to_direction;
 				}
 
-				ret = AI_DoCommand(tile, DiagDirToRoadBits(ReverseDiagDir((DiagDirection)dir1)), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+				ret = AI_DoCommand(tile, DiagDirToRoadBits(ReverseDiagDir(dir1)), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
 				if (CmdSucceeded(ret)) {
-					dir1 = TileOffsByDiagDir(dir1);
-					if (IsTileType(tile + dir1, MP_CLEAR) || IsTileType(tile + dir1, MP_TREES)) {
-						ret = AI_DoCommand(tile+dir1, AiNew_GetRoadDirection(tile, tile+dir1, tile+dir1+dir1), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+					TileIndex offset = TileOffsByDiagDir(dir1);
+					if (IsTileType(tile + offset, MP_CLEAR) || IsTileType(tile + offset, MP_TREES)) {
+						ret = AI_DoCommand(tile + offset, AiNew_GetRoadDirection(tile, tile + offset, tile + offset + offset), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
 						if (CmdSucceeded(ret)) {
-							if (IsTileType(tile + dir1 + dir1, MP_CLEAR) || IsTileType(tile + dir1 + dir1, MP_TREES))
-								AI_DoCommand(tile+dir1+dir1, AiNew_GetRoadDirection(tile+dir1, tile+dir1+dir1, tile+dir1+dir1+dir1), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+							if (IsTileType(tile + offset + offset, MP_CLEAR) || IsTileType(tile + offset + offset, MP_TREES))
+								AI_DoCommand(tile + offset + offset, AiNew_GetRoadDirection(tile + offset, tile + offset + offset, tile + offset + offset + offset), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
 						}
 					}
 				}
 
-				ret = AI_DoCommand(tile, DiagDirToRoadBits(ReverseDiagDir((DiagDirection)dir2)), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+				ret = AI_DoCommand(tile, DiagDirToRoadBits(ReverseDiagDir(dir2)), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
 				if (CmdSucceeded(ret)) {
-					dir2 = TileOffsByDiagDir(dir2);
-					if (IsTileType(tile + dir2, MP_CLEAR) || IsTileType(tile + dir2, MP_TREES)) {
-						ret = AI_DoCommand(tile+dir2, AiNew_GetRoadDirection(tile, tile+dir2, tile+dir2+dir2), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+					TileIndex offset = TileOffsByDiagDir(dir2);
+					if (IsTileType(tile + offset, MP_CLEAR) || IsTileType(tile + offset, MP_TREES)) {
+						ret = AI_DoCommand(tile + offset, AiNew_GetRoadDirection(tile, tile + offset, tile + offset + offset), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
 						if (CmdSucceeded(ret)) {
-							if (IsTileType(tile + dir2 + dir2, MP_CLEAR) || IsTileType(tile + dir2 + dir2, MP_TREES))
-								AI_DoCommand(tile+dir2+dir2, AiNew_GetRoadDirection(tile+dir2, tile+dir2+dir2, tile+dir2+dir2+dir2), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+							if (IsTileType(tile + offset + offset, MP_CLEAR) || IsTileType(tile + offset + offset, MP_TREES))
+								AI_DoCommand(tile + offset + offset, AiNew_GetRoadDirection(tile + offset, tile + offset + offset, tile + offset + offset + offset), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
 						}
 					}
 				}
 
-				ret = AI_DoCommand(tile, DiagDirToRoadBits((DiagDirection)dir3), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+				ret = AI_DoCommand(tile, DiagDirToRoadBits(dir3), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
 				if (CmdSucceeded(ret)) {
-					dir3 = TileOffsByDiagDir(dir3);
-					if (IsTileType(tile + dir3, MP_CLEAR) || IsTileType(tile + dir3, MP_TREES)) {
-						ret = AI_DoCommand(tile+dir3, AiNew_GetRoadDirection(tile, tile+dir3, tile+dir3+dir3), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+					TileIndex offset = TileOffsByDiagDir(dir3);
+					if (IsTileType(tile + offset, MP_CLEAR) || IsTileType(tile + offset, MP_TREES)) {
+						ret = AI_DoCommand(tile + offset, AiNew_GetRoadDirection(tile, tile + offset, tile + offset + offset), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
 						if (CmdSucceeded(ret)) {
-							if (IsTileType(tile + dir3 + dir3, MP_CLEAR) || IsTileType(tile + dir3 + dir3, MP_TREES))
-								AI_DoCommand(tile+dir3+dir3, AiNew_GetRoadDirection(tile+dir3, tile+dir3+dir3, tile+dir3+dir3+dir3), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+							if (IsTileType(tile + offset + offset, MP_CLEAR) || IsTileType(tile + offset + offset, MP_TREES))
+								AI_DoCommand(tile + offset + offset, AiNew_GetRoadDirection(tile + offset, tile + offset + offset, tile + offset + offset + offset), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
 						}
 					}
 				}
@@ -1105,7 +1101,7 @@
 	CommandCost res;
 	assert(p->ainew.state == AI_STATE_BUILD_DEPOT);
 
-	if (IsTileType(p->ainew.depot_tile, MP_STREET) && GetRoadTileType(p->ainew.depot_tile) == ROAD_TILE_DEPOT) {
+	if (IsTileType(p->ainew.depot_tile, MP_ROAD) && GetRoadTileType(p->ainew.depot_tile) == ROAD_TILE_DEPOT) {
 		if (IsTileOwner(p->ainew.depot_tile, _current_player)) {
 			// The depot is already built
 			p->ainew.state = AI_STATE_BUILD_VEHICLE;
--- a/src/aircraft.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/aircraft.h	Fri Aug 03 18:10:15 2007 +0000
@@ -35,7 +35,7 @@
  * @param v vehicle to check
  * @return true if in hangar
  */
-static inline bool IsAircraftInHangar(const Vehicle* v)
+static inline bool IsAircraftInHangar(const Vehicle *v)
 {
 	assert(v->type == VEH_AIRCRAFT);
 	return v->vehstatus & VS_HIDDEN && IsHangarTile(v->tile);
@@ -45,7 +45,7 @@
  * @param v vehicle to check
  * @return true if in hangar and stopped
  */
-static inline bool IsAircraftInHangarStopped(const Vehicle* v)
+static inline bool IsAircraftInHangarStopped(const Vehicle *v)
 {
 	return IsAircraftInHangar(v) && v->vehstatus & VS_STOPPED;
 }
--- a/src/aircraft_cmd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/aircraft_cmd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -1145,7 +1145,7 @@
 	bool hard_limit = true;
 
 	if (amd->flag & AMED_NOSPDCLAMP)   speed_limit = SPEED_LIMIT_NONE;
-	if (amd->flag & AMED_HOLD)       { speed_limit = SPEED_LIMIT_HOLD;     hard_limit = false; }
+	if ((amd->flag & AMED_HOLD) && (v->u.air.previous_pos != v->u.air.pos))      { speed_limit = SPEED_LIMIT_HOLD;     hard_limit = false; }
 	if (amd->flag & AMED_LAND)       { speed_limit = SPEED_LIMIT_APPROACH; hard_limit = false; }
 	if (amd->flag & AMED_BRAKE)      { speed_limit = SPEED_LIMIT_TAXI;     hard_limit = false; }
 
@@ -1780,7 +1780,13 @@
 	 * 1. in case all terminals are busy AirportFindFreeTerminal() returns false or
 	 * 2. not going for terminal (but depot, no order),
 	 * --> get out of the way to the hangar. */
+
 	if (v->current_order.type == OT_GOTO_STATION) {
+
+	//TODO: search through command list for an explicit terminal selection command.
+	//if present, select terminal using that instruction, checking blocks first
+	//if not, continue with these default actions
+
 		if (AirportFindFreeTerminal(v, apc)) return;
 	}
 	v->u.air.state = HANGAR;
@@ -1897,15 +1903,28 @@
 					v->u.air.owned_blocks.ReserveBlocks(&current->reserveblock);
 					st->airport_flags.ReserveBlocks(&current->reserveblock);
 					/* set target position */
-					v->u.air.previous_pos = v->u.air.pos; // save previous location
-					v->u.air.pos = current->next_position;
+					v->u.air.previous_pos = v->u.air.pos;  // save previous location
+					v->u.air.pos = current->next_position; // move to next position
 					UpdateAircraftCache(v);
-			} // move to next position
-			return false;
+					return false;
+			}
+			//TODO: HOLD
+			//if state=heading, and hold on fail bit set, stop vehicle (break from loop)
 		}
+		//TODO: Choose terminal / helipad. terms/pads normally chosen by endlanding.
+		//if encountered in normal sequence, check blocks are clear, unreserve any existing term/pad,
+		//check indicated term/pad group, and reserve if clear and set new u.air.state
+		//NOTE: does not exit after selection, and continues looking for a subsequent movement instruction
+		//if a 2nd terminal/helipad instruction encountered, only react if no terminal was chosen in first etc
+
 		current = current->next;
 	} while (current != NULL);
 
+	/* else stop vehicle */
+	v->cur_speed = 0;
+	v->subspeed = 0;
+	return true;
+
 	DEBUG(misc, 0, "[Ap] cannot move further on Airport! (pos %d state %d) for vehicle %d", v->u.air.pos, v->u.air.state, v->index);
 	assert(0);
 	return false;
@@ -1925,9 +1944,6 @@
 		v->u.air.owned_blocks.HasBlocks(&current_pos->reserveblock))
 		return false;
 
-	/* else stop vehicle */
-	v->cur_speed = 0;
-	v->subspeed = 0;
 	return true;
 }
 
--- a/src/aircraft_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/aircraft_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -216,7 +216,7 @@
 };
 
 static const WindowDesc _aircraft_details_desc = {
-	WDP_AUTO, WDP_AUTO, 390, 126,
+	WDP_AUTO, WDP_AUTO, 390, 126, 390, 126,
 	WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_aircraft_details_widgets,
@@ -380,7 +380,7 @@
 
 
 static const WindowDesc _aircraft_view_desc = {
-	WDP_AUTO, WDP_AUTO, 250, 116,
+	WDP_AUTO, WDP_AUTO, 250, 116, 250, 116,
 	WC_VEHICLE_VIEW, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_aircraft_view_widgets,
--- a/src/airport_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/airport_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -149,7 +149,7 @@
 
 
 static const WindowDesc _air_toolbar_desc = {
-	WDP_ALIGN_TBR, 22, 64, 36,
+	WDP_ALIGN_TBR, 22, 64, 36, 64, 36,
 	WC_BUILD_TOOLBAR, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
 	_air_toolbar_widgets,
@@ -393,7 +393,7 @@
 };
 
 static const WindowDesc _build_airport_desc = {
-	WDP_AUTO, WDP_AUTO, 148, 240,
+	WDP_AUTO, WDP_AUTO, 148, 240, 148, 240,
 	WC_BUILD_STATION, WC_BUILD_TOOLBAR,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_build_airport_picker_widgets,
@@ -401,7 +401,7 @@
 };
 
 static const WindowDesc _newports_build_airport_desc = {
-	WDP_AUTO, WDP_AUTO, 148, 330,
+	WDP_AUTO, WDP_AUTO, 148, 330, 148, 330,
 	WC_BUILD_STATION, WC_BUILD_TOOLBAR,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_newports_build_airport_picker_widgets,
--- a/src/autoreplace_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/autoreplace_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -467,7 +467,7 @@
 };
 
 static const WindowDesc _replace_rail_vehicle_desc = {
-	WDP_AUTO, WDP_AUTO, 456, 252,
+	WDP_AUTO, WDP_AUTO, 456, 252, 456, 252,
 	WC_REPLACE_VEHICLE, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_replace_rail_vehicle_widgets,
@@ -475,7 +475,7 @@
 };
 
 static const WindowDesc _replace_road_vehicle_desc = {
-	WDP_AUTO, WDP_AUTO, 456, 230,
+	WDP_AUTO, WDP_AUTO, 456, 230, 456, 230,
 	WC_REPLACE_VEHICLE, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_replace_road_vehicle_widgets,
@@ -483,7 +483,7 @@
 };
 
 static const WindowDesc _replace_ship_aircraft_vehicle_desc = {
-	WDP_AUTO, WDP_AUTO, 456, 214,
+	WDP_AUTO, WDP_AUTO, 456, 214, 456, 214,
 	WC_REPLACE_VEHICLE, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_replace_ship_aircraft_vehicle_widgets,
--- a/src/bmp.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/bmp.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -9,7 +9,8 @@
 #include "macros.h"
 #include "helpers.hpp"
 
-void BmpInitializeBuffer(BmpBuffer *buffer, FILE *file) {
+void BmpInitializeBuffer(BmpBuffer *buffer, FILE *file)
+{
 	buffer->pos      = -1;
 	buffer->file     = file;
 	buffer->read     = 0;
--- a/src/bridge.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/bridge.h	Fri Aug 03 18:10:15 2007 +0000
@@ -27,7 +27,7 @@
 extern const Bridge orig_bridge[MAX_BRIDGES];
 extern Bridge _bridge[MAX_BRIDGES];
 
-uint GetBridgeFoundation(Slope tileh, Axis axis);
+Foundation GetBridgeFoundation(Slope tileh, Axis axis);
 
 static inline const Bridge *GetBridge(uint i)
 {
@@ -35,6 +35,6 @@
 	return &_bridge[i];
 }
 
-void DrawBridgeMiddle(const TileInfo* ti);
+void DrawBridgeMiddle(const TileInfo *ti);
 
 #endif /* BRIDGE_H */
--- a/src/bridge_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/bridge_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -86,7 +86,7 @@
 };
 
 static const WindowDesc _build_bridge_desc = {
-	WDP_AUTO, WDP_AUTO, 200, 102,
+	WDP_AUTO, WDP_AUTO, 200, 102, 200, 102,
 	WC_BUILD_BRIDGE, WC_BUILD_TOOLBAR,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_build_bridge_widgets,
@@ -103,7 +103,7 @@
 };
 
 static const WindowDesc _build_road_bridge_desc = {
-	WDP_AUTO, WDP_AUTO, 200, 102,
+	WDP_AUTO, WDP_AUTO, 200, 102, 200, 102,
 	WC_BUILD_BRIDGE, WC_BUILD_TOOLBAR,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_build_road_bridge_widgets,
--- a/src/bridge_map.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/bridge_map.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -44,11 +44,11 @@
 {
 	uint h;
 	Slope tileh = GetTileSlope(t, &h);
-	uint f = GetBridgeFoundation(tileh, DiagDirToAxis(GetBridgeRampDirection(t)));
+	Foundation f = GetBridgeFoundation(tileh, DiagDirToAxis(GetBridgeRampDirection(t)));
 
 	/* one height level extra if the ramp is on a flat foundation */
 	return
 		h + TILE_HEIGHT +
-		(IS_INT_INSIDE(f, 1, 15) ? TILE_HEIGHT : 0) +
+		(IsLeveledFoundation(f) ? TILE_HEIGHT : 0) +
 		(IsSteepSlope(tileh) ? TILE_HEIGHT : 0);
 }
--- a/src/bridge_map.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/bridge_map.h	Fri Aug 03 18:10:15 2007 +0000
@@ -46,7 +46,7 @@
 	return
 		IsTileType(t, MP_CLEAR) ||
 		IsTileType(t, MP_RAILWAY) ||
-		IsTileType(t, MP_STREET) ||
+		IsTileType(t, MP_ROAD) ||
 		IsTileType(t, MP_WATER) ||
 		IsTileType(t, MP_TUNNELBRIDGE) ||
 		IsTileType(t, MP_UNMOVABLE);
--- a/src/build_vehicle_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/build_vehicle_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -53,13 +53,13 @@
 	{ WWT_PUSHTXTBTN,   RESIZE_NONE,    14,     0,    80,    14,    25, STR_SORT_BY,             STR_SORT_ORDER_TIP},
 	{      WWT_PANEL,  RESIZE_RIGHT,    14,    81,   227,    14,    25, 0x0,                     STR_SORT_CRITERIA_TIP},
 	{    WWT_TEXTBTN,     RESIZE_LR,    14,   228,   239,    14,    25, STR_0225,                STR_SORT_CRITERIA_TIP},
-	{     WWT_MATRIX,     RESIZE_RB,    14,     0,   227,    26,   121, 0x0,                     STR_NULL },
-	{  WWT_SCROLLBAR,    RESIZE_LRB,    14,   228,   239,    26,   121, 0x0,                     STR_0190_SCROLL_BAR_SCROLLS_LIST },
-	{      WWT_PANEL,    RESIZE_RTB,    14,     0,   239,   122,   243, 0x0,                     STR_NULL },
+	{     WWT_MATRIX,     RESIZE_RB,    14,     0,   227,    26,    39, 0x101,                   STR_NULL },
+	{  WWT_SCROLLBAR,    RESIZE_LRB,    14,   228,   239,    26,    39, 0x0,                     STR_0190_SCROLL_BAR_SCROLLS_LIST },
+	{      WWT_PANEL,    RESIZE_RTB,    14,     0,   239,    40,   161, 0x0,                     STR_NULL },
 
-	{ WWT_PUSHTXTBTN,     RESIZE_TB,    14,     0,   114,   244,   255, 0x0,                     STR_NULL },
-	{ WWT_PUSHTXTBTN,    RESIZE_RTB,    14,   115,   227,   244,   255, 0x0,                     STR_NULL },
-	{  WWT_RESIZEBOX,   RESIZE_LRTB,    14,   228,   239,   244,   255, 0x0,                     STR_RESIZE_BUTTON },
+	{ WWT_PUSHTXTBTN,     RESIZE_TB,    14,     0,   114,   162,   173, 0x0,                     STR_NULL },
+	{ WWT_PUSHTXTBTN,    RESIZE_RTB,    14,   115,   227,   162,   173, 0x0,                     STR_NULL },
+	{  WWT_RESIZEBOX,   RESIZE_LRTB,    14,   228,   239,   162,   173, 0x0,                     STR_RESIZE_BUTTON },
 	{   WIDGETS_END},
 };
 
@@ -979,6 +979,19 @@
 	buildvehicle_d *bv = &WP(w, buildvehicle_d);
 
 	switch (e->event) {
+		case WE_CREATE: {
+			bv->vehicle_type = *(VehicleType*)e->we.create.data;
+			int vlh = GetVehicleListHeight(bv->vehicle_type);
+
+			ResizeWindow(w, 0, vlh - 14);
+			w->resize.step_height = vlh;
+			w->vscroll.cap = 1;
+			w->widget[BUILD_VEHICLE_WIDGET_LIST].data = 0x101;
+
+			w->resize.width  = w->width;
+			w->resize.height = w->height;
+		} break;
+
 		case WE_INVALIDATE_DATA:
 			bv->regenerate_list = true;
 			SetWindowDirty(w);
@@ -1044,7 +1057,7 @@
 }
 
 static const WindowDesc _build_vehicle_desc = {
-	WDP_AUTO, WDP_AUTO, 240, 256,
+	WDP_AUTO, WDP_AUTO, 240, 174, 240, 256,
 	WC_BUILD_VEHICLE, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
 	_build_vehicle_widgets,
@@ -1065,20 +1078,16 @@
 
 	DeleteWindowById(WC_BUILD_VEHICLE, num);
 
-	w = AllocateWindowDescFront(&_build_vehicle_desc, num);
+	w = AllocateWindowDescFront(&_build_vehicle_desc, num, &type);
 
 	if (w == NULL) return;
 
 	w->caption_color = (tile != 0) ? GetTileOwner(tile) : _local_player;
-	w->resize.step_height = GetVehicleListHeight(type);
-	w->vscroll.cap = w->resize.step_height == 24 ? 4 : 8;
-	w->widget[BUILD_VEHICLE_WIDGET_LIST].data = (w->vscroll.cap << 8) + 1;
 
 	bv = &WP(w, buildvehicle_d);
 	EngList_Create(&bv->eng_list);
 	bv->sel_engine      = INVALID_ENGINE;
 
-	bv->vehicle_type    = type;
 	bv->regenerate_list = false;
 
 	bv->sort_criteria         = _last_sort_criteria[type];
@@ -1088,11 +1097,9 @@
 		default: NOT_REACHED();
 		case VEH_TRAIN:
 			WP(w, buildvehicle_d).filter.railtype = (tile == 0) ? RAILTYPE_END : GetRailType(tile);
-			ResizeWindow(w, 0, 16);
 			break;
 		case VEH_ROAD:
 			WP(w, buildvehicle_d).filter.roadtypes = (tile == 0) ? ROADTYPES_ALL : GetRoadTypes(tile);
-			ResizeWindow(w, 0, 16);
 		case VEH_SHIP:
 			break;
 		case VEH_AIRCRAFT:
@@ -1103,9 +1110,6 @@
 	SetupWindowStrings(w, type);
 	ResizeButtons(w, BUILD_VEHICLE_WIDGET_BUILD, BUILD_VEHICLE_WIDGET_RENAME);
 
-	w->resize.width  = w->width;
-	w->resize.height = w->height;
-
 	GenerateBuildList(w); // generate the list, since we need it in the next line
 	/* Select the first engine in the list as default when opening the window */
 	if (EngList_Count(&bv->eng_list) > 0) bv->sel_engine = bv->eng_list[0];
--- a/src/cargopacket.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/cargopacket.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -8,36 +8,14 @@
 #include "cargopacket.h"
 #include "saveload.h"
 
-/** Cache for speeding up lookups in AllocateRaw */
-static uint _first_free_cargo_packet_index;
-
-/**
- * Called if a new block is added to the station-pool
- */
-static void CargoPacketPoolNewBlock(uint cpart_item)
-{
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 *  TODO - This is just a temporary stage, this will be removed. */
-	for (CargoPacket *cp = GetCargoPacket(cpart_item); cp != NULL; cp = (cp->index + 1U < GetCargoPacketPoolSize()) ? GetCargoPacket(cp->index + 1U) : NULL) cp->index = cpart_item++;
-}
-
-static void CargoPacketPoolCleanBlock(uint cpart_item, uint end_item)
-{
-	for (uint i = cpart_item; i <= end_item; i++) {
-		CargoPacket *cp = GetCargoPacket(i);
-		if (cp->IsValid()) cp->~CargoPacket();
-	}
-}
-
 /* Initialize the cargopacket-pool */
-DEFINE_OLD_POOL(CargoPacket, CargoPacket, CargoPacketPoolNewBlock, CargoPacketPoolCleanBlock)
+DEFINE_OLD_POOL_GENERIC(CargoPacket, CargoPacket)
 
 void InitializeCargoPackets()
 {
-	_first_free_cargo_packet_index = 0;
 	/* Clean the cargo packet pool and create 1 block in it */
-	CleanPool(&_CargoPacket_pool);
-	AddBlockToPool(&_CargoPacket_pool);
+	_CargoPacket_pool.CleanPool();
+	_CargoPacket_pool.AddBlockToPool();
 
 	/* Check whether our &cargolist == &cargolist.packets "hack" works */
 	CargoList::AssertOnWrongPacketOffset();
@@ -59,7 +37,6 @@
 
 CargoPacket::~CargoPacket()
 {
-	if (this->index < _first_free_cargo_packet_index) _first_free_cargo_packet_index = this->index;
 	this->count = 0;
 }
 
@@ -68,52 +45,6 @@
 	return this->source_xy == cp->source_xy && this->days_in_transit == cp->days_in_transit && this->paid_for == cp->paid_for;
 }
 
-void *CargoPacket::operator new(size_t size)
-{
-	CargoPacket *cp = AllocateRaw();
-	return cp;
-}
-
-void *CargoPacket::operator new(size_t size, CargoPacket::ID cp_idx)
-{
-	if (!AddBlockIfNeeded(&_CargoPacket_pool, cp_idx))
-		error("CargoPackets: failed loading savegame: too many cargo packets");
-
-	CargoPacket *cp = GetCargoPacket(cp_idx);
-	return cp;
-}
-
-void CargoPacket::operator delete(void *p)
-{
-}
-
-void CargoPacket::operator delete(void *p, CargoPacket::ID cp_idx)
-{
-}
-
-/*static*/ CargoPacket *CargoPacket::AllocateRaw()
-{
-	CargoPacket *cp = NULL;
-
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (cp = GetCargoPacket(_first_free_cargo_packet_index); cp != NULL; cp = (cp->index + 1U < GetCargoPacketPoolSize()) ? GetCargoPacket(cp->index + 1U) : NULL) {
-		if (!cp->IsValid()) {
-			CargoPacket::ID index = cp->index;
-
-			memset(cp, 0, sizeof(CargoPacket));
-			cp->index = index;
-			_first_free_cargo_packet_index = cp->index;
-			return cp;
-		}
-	}
-
-	/* Check if we can add a block to the pool */
-	if (AddBlockToPool(&_CargoPacket_pool)) return AllocateRaw();
-
-	error("CargoPackets: too many cargo packets");
-}
-
 static const SaveLoad _cargopacket_desc[] = {
 	SLE_VAR(CargoPacket, source,          SLE_UINT16),
 	SLE_VAR(CargoPacket, source_xy,       SLE_UINT32),
@@ -141,11 +72,7 @@
 	int index;
 
 	while ((index = SlIterateArray()) != -1) {
-		if (!AddBlockIfNeeded(&_CargoPacket_pool, index)) {
-			error("CargoPackets: failed loading savegame: too many cargo packets");
-		}
-
-		CargoPacket *cp = GetCargoPacket(index);
+		CargoPacket *cp = new (index) CargoPacket();
 		SlObject(cp, _cargopacket_desc);
 	}
 }
--- a/src/cargopacket.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/cargopacket.h	Fri Aug 03 18:10:15 2007 +0000
@@ -7,14 +7,17 @@
 
 #include <list>
 
+typedef uint32 CargoPacketID;
+struct CargoPacket;
+
+/** We want to use a pool */
+DECLARE_OLD_POOL(CargoPacket, CargoPacket, 10, 1000)
+
+
 /**
  * Container for cargo from the same location and time
  */
-struct CargoPacket {
-	typedef uint32 ID;      ///< Type for cargopacket identifiers
-
-	ID index;               ///< The unique index of this packet
-
+struct CargoPacket : PoolItem<CargoPacket, CargoPacketID, &_CargoPacket_pool> {
 	StationID source;       ///< The station where the cargo came from first
 	TileIndex source_xy;    ///< The origin of the cargo (first station in feeder chain)
 	TileIndex loaded_at_xy; ///< Location where this cargo has been loaded into the vehicle
@@ -33,7 +36,7 @@
 	CargoPacket(StationID source = INVALID_STATION, uint16 count = 0);
 
 	/** Destroy the packet */
-	~CargoPacket();
+	virtual ~CargoPacket();
 
 
 	/**
@@ -49,27 +52,8 @@
 	 * @return true if and only if days_in_transit and source_xy are equal
 	 */
 	bool SameSource(CargoPacket *cp);
-
-
-	/* normal new/delete operators. Used when building/removing station */
-	void* operator new (size_t size);
-	void operator delete(void *p);
-
-	/* new/delete operators accepting station index. Used when loading station from savegame. */
-	void* operator new (size_t size, CargoPacket::ID cp_idx);
-	void operator delete(void *p, CargoPacket::ID cp_idx);
-
-private:
-	/**
-	 * Allocate the raw memory for this cargo packet
-	 * @return the allocated memory
-	 */
-	static CargoPacket *AllocateRaw();
 };
 
-/** We want to use a pool */
-DECLARE_OLD_POOL(CargoPacket, CargoPacket, 10, 1000)
-
 /**
  * Iterate over all _valid_ cargo packets from the given start
  * @param cp    the variable used as "iterator"
--- a/src/clear_cmd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/clear_cmd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -179,7 +179,7 @@
 
 	_error_message = STR_1004_TOO_HIGH;
 
-	if (height > 15) return false;
+	if (height > MAX_TILE_HEIGHT) return false;
 
 	nh = TerraformGetHeightOfTile(ts, tile);
 	if (nh < 0 || height == nh) return false;
@@ -573,9 +573,9 @@
 	return z + GetPartialZ(x & 0xF, y & 0xF, tileh);
 }
 
-static Slope GetSlopeTileh_Clear(TileIndex tile, Slope tileh)
+static Foundation GetFoundation_Clear(TileIndex tile, Slope tileh)
 {
-	return tileh;
+	return FOUNDATION_NONE;
 }
 
 static void GetAcceptedCargo_Clear(TileIndex tile, AcceptedCargo ac)
@@ -758,7 +758,7 @@
 				SetClearGroundDensity(tile, CLEAR_ROCKS, 3);
 				do {
 					if (--j == 0) goto get_out;
-					tile_new = tile + TileOffsByDiagDir(GB(Random(), 0, 2));
+					tile_new = tile + TileOffsByDiagDir((DiagDirection)GB(Random(), 0, 2));
 				} while (!IsTileType(tile_new, MP_CLEAR) || IsClearGround(tile_new, CLEAR_DESERT));
 				tile = tile_new;
 			}
@@ -819,5 +819,5 @@
 	ChangeTileOwner_Clear,    ///< change_tile_owner_clear
 	NULL,                     ///< get_produced_cargo_proc
 	NULL,                     ///< vehicle_enter_tile_proc
-	GetSlopeTileh_Clear,      ///< get_slope_tileh_proc
+	GetFoundation_Clear,      ///< get_foundation_proc
 };
--- a/src/command.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/command.h	Fri Aug 03 18:10:15 2007 +0000
@@ -195,9 +195,9 @@
 static inline bool CmdFailed(CommandCost cost) { return cost.Failed(); }
 static inline bool CmdSucceeded(CommandCost cost) { return cost.Succeeded(); }
 
-static const CommandCost CMD_ERROR = CommandCost((StringID)INVALID_STRING_ID);
+static const CommandCost CMD_ERROR = CommandCost(INVALID_STRING_ID);
 
-#define return_cmd_error(errcode) do { return CommandCost((StringID)(errcode)); } while (0)
+#define return_cmd_error(errcode) do { return CommandCost(errcode); } while (0)
 
 /* command.cpp */
 typedef void CommandCallback(bool success, TileIndex tile, uint32 p1, uint32 p2);
--- a/src/console.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/console.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -200,7 +200,7 @@
 };
 
 static const WindowDesc _iconsole_window_desc = {
-	0, 0, 2, 2,
+	0, 0, 2, 2, 2, 2,
 	WC_CONSOLE, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_iconsole_window_widgets,
@@ -463,7 +463,7 @@
 /**
  * Change a string into its number representation. Supports
  * decimal and hexadecimal numbers as well as 'on'/'off' 'true'/'false'
- * @param *value the variable a successfull conversion will be put in
+ * @param *value the variable a successful conversion will be put in
  * @param *arg the string to be converted
  * @return Return true on success or false on failure
  */
@@ -517,7 +517,7 @@
  * there is a function associated with that and if so, execute it
  * @param hooks IConsoleHooks structure that will be checked
  * @param type type of hook, trigger that needs to be activated
- * @return true on a successfull execution of the hook command or if there
+ * @return true on a successful execution of the hook command or if there
  * is no hook/trigger present at all. False otherwise
  */
 static bool IConsoleHookHandle(const IConsoleHooks *hooks, IConsoleHookTypes type)
--- a/src/console_cmds.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/console_cmds.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -1079,6 +1079,8 @@
 		return true;
 	}
 
+	if (_game_mode == GM_NORMAL && _patches.autosave_on_exit) DoExitSave();
+
 	_exit_game = true;
 	return true;
 }
--- a/src/date.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/date.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -220,7 +220,7 @@
 	for (i = daytick; i < total; i += DAY_TICKS) {
 		Vehicle *v = GetVehicle(i);
 
-		if (IsValidVehicle(v)) _on_new_vehicle_day_proc[v->type](v);
+		if (v->IsValid()) _on_new_vehicle_day_proc[v->type](v);
 	}
 }
 
--- a/src/depot.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/depot.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -14,21 +14,7 @@
 #include "saveload.h"
 #include "order.h"
 
-
-/**
- * Called if a new block is added to the depot-pool
- */
-static void DepotPoolNewBlock(uint start_item)
-{
-	Depot *d;
-
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (d = GetDepot(start_item); d != NULL; d = (d->index + 1U < GetDepotPoolSize()) ? GetDepot(d->index + 1U) : NULL) d->index = start_item++;
-}
-
-DEFINE_OLD_POOL(Depot, Depot, DepotPoolNewBlock, NULL)
-
+DEFINE_OLD_POOL_GENERIC(Depot, Depot)
 
 /**
  * Gets a depot from a tile
@@ -47,50 +33,22 @@
 }
 
 /**
- * Allocate a new depot
- */
-Depot *AllocateDepot()
-{
-	Depot *d;
-
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (d = GetDepot(0); d != NULL; d = (d->index + 1U < GetDepotPoolSize()) ? GetDepot(d->index + 1U) : NULL) {
-		if (!IsValidDepot(d)) {
-			DepotID index = d->index;
-
-			memset(d, 0, sizeof(Depot));
-			d->index = index;
-
-			return d;
-		}
-	}
-
-	/* Check if we can add a block to the pool */
-	if (AddBlockToPool(&_Depot_pool)) return AllocateDepot();
-
-	return NULL;
-}
-
-/**
  * Clean up a depot
  */
-void DestroyDepot(Depot *depot)
+Depot::~Depot()
 {
-	/* Clear the tile */
-	DoClearSquare(depot->xy);
-
 	/* Clear the depot from all order-lists */
-	RemoveOrderFromAllVehicles(OT_GOTO_DEPOT, depot->index);
+	RemoveOrderFromAllVehicles(OT_GOTO_DEPOT, this->index);
 
 	/* Delete the depot-window */
-	DeleteWindowById(WC_VEHICLE_DEPOT, depot->xy);
+	DeleteWindowById(WC_VEHICLE_DEPOT, this->xy);
+	this->xy = 0;
 }
 
 void InitializeDepots()
 {
-	CleanPool(&_Depot_pool);
-	AddBlockToPool(&_Depot_pool);
+	_Depot_pool.CleanPool();
+	_Depot_pool.AddBlockToPool();
 }
 
 
@@ -116,12 +74,7 @@
 	int index;
 
 	while ((index = SlIterateArray()) != -1) {
-		Depot *depot;
-
-		if (!AddBlockIfNeeded(&_Depot_pool, index))
-			error("Depots: failed loading savegame: too many depots");
-
-		depot = GetDepot(index);
+		Depot *depot = new (index) Depot();
 		SlObject(depot, _depot_desc);
 	}
 }
--- a/src/depot.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/depot.h	Fri Aug 03 18:10:15 2007 +0000
@@ -13,38 +13,27 @@
 #include "rail_map.h"
 #include "water_map.h"
 
-struct Depot {
-	TileIndex xy;
-	TownID town_index;
-	DepotID index;
-};
-
+struct Depot;
 DECLARE_OLD_POOL(Depot, Depot, 3, 8000)
 
-/**
- * Check if a depot really exists.
- */
-static inline bool IsValidDepot(const Depot *depot)
-{
-	return depot != NULL && depot->xy != 0;
-}
+struct Depot : PoolItem<Depot, DepotID, &_Depot_pool> {
+	TileIndex xy;
+	TownID town_index;
 
-static inline bool IsValidDepotID(uint index)
-{
-	return index < GetDepotPoolSize() && IsValidDepot(GetDepot(index));
-}
+	Depot(TileIndex xy = 0) : xy(xy) {}
+	~Depot();
 
-void DestroyDepot(Depot *depot);
+	bool IsValid() const { return this->xy != 0; }
+};
 
-static inline void DeleteDepot(Depot *depot)
+static inline bool IsValidDepotID(DepotID index)
 {
-	DestroyDepot(depot);
-	depot->xy = 0;
+	return index < GetDepotPoolSize() && GetDepot(index)->IsValid();
 }
 
 void ShowDepotWindow(TileIndex tile, VehicleType type);
 
-#define FOR_ALL_DEPOTS_FROM(d, start) for (d = GetDepot(start); d != NULL; d = (d->index + 1U < GetDepotPoolSize()) ? GetDepot(d->index + 1U) : NULL) if (IsValidDepot(d))
+#define FOR_ALL_DEPOTS_FROM(d, start) for (d = GetDepot(start); d != NULL; d = (d->index + 1U < GetDepotPoolSize()) ? GetDepot(d->index + 1U) : NULL) if (d->IsValid())
 #define FOR_ALL_DEPOTS(d) FOR_ALL_DEPOTS_FROM(d, 0)
 
 #define MIN_SERVINT_PERCENT  5
@@ -74,7 +63,7 @@
 			return IsTileType(tile, MP_RAILWAY) && GetRailTileType(tile)  == RAIL_TILE_DEPOT;
 
 		case TRANSPORT_ROAD:
-			return IsTileType(tile, MP_STREET)  && GetRoadTileType(tile)  == ROAD_TILE_DEPOT;
+			return IsTileType(tile, MP_ROAD)  && GetRoadTileType(tile)  == ROAD_TILE_DEPOT;
 
 		case TRANSPORT_WATER:
 			return IsTileType(tile, MP_WATER)   && GetWaterTileType(tile) == WATER_TILE_DEPOT;
@@ -108,7 +97,6 @@
 
 Depot *GetDepotByTile(TileIndex tile);
 void InitializeDepots();
-Depot *AllocateDepot();
 
 void DeleteDepotHighlightOfVehicle(const Vehicle *v);
 
--- a/src/depot_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/depot_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -97,7 +97,7 @@
 static void DepotWndProc(Window *w, WindowEvent *e);
 
 static const WindowDesc _train_depot_desc = {
-	WDP_AUTO, WDP_AUTO, 36, 27,
+	WDP_AUTO, WDP_AUTO, 36, 27, 36, 27,
 	WC_VEHICLE_DEPOT, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_depot_widgets,
@@ -105,7 +105,7 @@
 };
 
 static const WindowDesc _road_depot_desc = {
-	WDP_AUTO, WDP_AUTO, 36, 27,
+	WDP_AUTO, WDP_AUTO, 36, 27, 36, 27,
 	WC_VEHICLE_DEPOT, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_depot_widgets,
@@ -113,7 +113,7 @@
 };
 
 static const WindowDesc _ship_depot_desc = {
-	WDP_AUTO, WDP_AUTO, 36, 27,
+	WDP_AUTO, WDP_AUTO, 36, 27, 36, 27,
 	WC_VEHICLE_DEPOT, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_depot_widgets,
@@ -121,7 +121,7 @@
 };
 
 static const WindowDesc _aircraft_depot_desc = {
-	WDP_AUTO, WDP_AUTO, 36, 27,
+	WDP_AUTO, WDP_AUTO, 36, 27, 36, 27,
 	WC_VEHICLE_DEPOT, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_depot_widgets,
--- a/src/direction.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/direction.h	Fri Aug 03 18:10:15 2007 +0000
@@ -7,66 +7,128 @@
 
 #include "helpers.hpp"
 
-/* Direction as commonly used in v->direction, 8 way. */
+/**
+ * Defines the 8 directions on the map.
+ *
+ * This enum defines 8 possible directions which are used for
+ * the vehicles in the game. The directions are aligned straight
+ * to the viewport, not to the map. So north points to the top of
+ * your viewport and not rotated by 45 degrees left or right to get
+ * a "north" used in you games.
+ */
 enum Direction {
-	DIR_BEGIN = 0,
-	DIR_N   = 0,
-	DIR_NE  = 1,      ///< Northeast, upper right on your monitor
-	DIR_E   = 2,
-	DIR_SE  = 3,
-	DIR_S   = 4,
-	DIR_SW  = 5,
-	DIR_W   = 6,
-	DIR_NW  = 7,
-	DIR_END,
-	INVALID_DIR = 0xFF,
+	DIR_BEGIN = 0,          ///< Used to iterate
+	DIR_N   = 0,            ///< North
+	DIR_NE  = 1,            ///< Northeast
+	DIR_E   = 2,            ///< East
+	DIR_SE  = 3,            ///< Southeast
+	DIR_S   = 4,            ///< South
+	DIR_SW  = 5,            ///< Southwest
+	DIR_W   = 6,            ///< West
+	DIR_NW  = 7,            ///< Northwest
+	DIR_END,                ///< Used to iterate
+	INVALID_DIR = 0xFF,     ///< Flag for an invalid direction
 };
 
 /** Define basic enum properties */
 template <> struct EnumPropsT<Direction> : MakeEnumPropsT<Direction, byte, DIR_BEGIN, DIR_END, INVALID_DIR> {};
 typedef TinyEnumT<Direction> DirectionByte; //typedefing-enumification of Direction
 
+/**
+ * Return the reverse of a direction
+ *
+ * @param d The direction to get the reverse from
+ * @return The reverse Direction
+ */
 static inline Direction ReverseDir(Direction d)
 {
 	return (Direction)(4 ^ d);
 }
 
 
+/**
+ * Enumeration for the difference between two directions.
+ *
+ * This enumeration is used to mark differences between
+ * two directions. If you get one direction you can align
+ * a second direction in 8 different ways. This enumeration
+ * only contains 6 of these 8 differences, but the remaining
+ * two can be calculated by adding to differences together.
+ * This also means you can add two differences together and
+ * get the difference you really want to get. The difference
+ * of 45 degrees left + the difference of 45 degrees right results in the
+ * difference of 0 degrees.
+ *
+ * @note To get this mentioned addition of direction you must use
+ *       modulo DIR_END or use the #ChangeDirDiff(DirDiff, DirDiff) function.
+ * @see ChangeDirDiff(DirDiff, DirDiff)
+ */
 enum DirDiff {
-	DIRDIFF_SAME    = 0,
-	DIRDIFF_45RIGHT = 1,
-	DIRDIFF_90RIGHT = 2,
-	DIRDIFF_REVERSE = 4,
-	DIRDIFF_90LEFT  = 6,
-	DIRDIFF_45LEFT  = 7
+	DIRDIFF_SAME    = 0,    ///< Both directions faces to the same direction
+	DIRDIFF_45RIGHT = 1,    ///< Angle of 45 degrees right
+	DIRDIFF_90RIGHT = 2,    ///< Angle of 90 degrees right
+	DIRDIFF_REVERSE = 4,    ///< One direction is the opposit of the other one
+	DIRDIFF_90LEFT  = 6,    ///< Angle of 90 degrees left
+	DIRDIFF_45LEFT  = 7     ///< Angle of 45 degrees left
 };
 
+/**
+ * Calculate the difference between to directions
+ *
+ * @param d0 The first direction as the base
+ * @param d1 The second direction as the offset from the base
+ * @return The difference how the second directions drifts of the first one.
+ */
 static inline DirDiff DirDifference(Direction d0, Direction d1)
 {
 	return (DirDiff)((d0 + 8 - d1) % 8);
 }
 
+/**
+ * Applies two differences together
+ *
+ * This function adds two differences together and return the resulting
+ * difference. So adding two DIRDIFF_REVERSE together results in the
+ * DIRDIFF_SAME difference.
+ *
+ * @param d The first difference
+ * @param delta The second difference to add on
+ * @return The resulting difference
+ */
 static inline DirDiff ChangeDirDiff(DirDiff d, DirDiff delta)
 {
 	return (DirDiff)((d + delta) % 8);
 }
 
-
+/**
+ * Change a direction by a given difference
+ *
+ * This functions returns a new direction of the given direction
+ * which is rotated by the given difference.
+ *
+ * @param d The direction to get a new direction from
+ * @param delta The offset/drift applied to the direction
+ * @return The new direction
+ */
 static inline Direction ChangeDir(Direction d, DirDiff delta)
 {
 	return (Direction)((d + delta) % 8);
 }
 
 
-/* Direction commonly used as the direction of entering and leaving tiles, 4-way */
+/**
+ * Enumeration for diagonal directions.
+ *
+ * This enumeration is used for the 4 direction of the tile-edges.
+ */
 enum DiagDirection {
-	DIAGDIR_BEGIN = 0,
-	DIAGDIR_NE  = 0,      ///< Northeast, upper right on your monitor
-	DIAGDIR_SE  = 1,
-	DIAGDIR_SW  = 2,
-	DIAGDIR_NW  = 3,
-	DIAGDIR_END,
-	INVALID_DIAGDIR = 0xFF,
+	DIAGDIR_BEGIN = 0,      ///< Used for iterations
+	DIAGDIR_NE  = 0,        ///< Northeast, upper right on your monitor
+	DIAGDIR_SE  = 1,        ///< Southeast
+	DIAGDIR_SW  = 2,        ///< Southwest
+	DIAGDIR_NW  = 3,        ///< Northwest
+	DIAGDIR_END,            ///< Used for iterations
+	INVALID_DIAGDIR = 0xFF, ///< Flag for an invalid DiagDirection
 };
 
 DECLARE_POSTFIX_INCREMENT(DiagDirection);
@@ -75,60 +137,135 @@
 template <> struct EnumPropsT<DiagDirection> : MakeEnumPropsT<DiagDirection, byte, DIAGDIR_BEGIN, DIAGDIR_END, INVALID_DIAGDIR> {};
 typedef TinyEnumT<DiagDirection> DiagDirectionByte; //typedefing-enumification of DiagDirection
 
+/**
+ * Returns the reverse direction of the given DiagDirection
+ *
+ * @param d The DiagDirection to get the reverse from
+ * @return The reverse direction
+ */
 static inline DiagDirection ReverseDiagDir(DiagDirection d)
 {
 	return (DiagDirection)(2 ^ d);
 }
 
-
+/**
+ * Enumeration for the difference between to DiagDirection.
+ *
+ * As the DiagDirection only contains 4 possible directions the
+ * difference between two of these directions can only be in 4 ways.
+ * As the DirDiff enumeration the values can be added together and
+ * you will get the resulting difference (use modulo DIAGDIR_END).
+ *
+ * @see DirDiff
+ */
 enum DiagDirDiff {
-	DIAGDIRDIFF_SAME    = 0,
-	DIAGDIRDIFF_90RIGHT = 1,
-	DIAGDIRDIFF_REVERSE = 2,
-	DIAGDIRDIFF_90LEFT  = 3
+	DIAGDIRDIFF_SAME    = 0,        ///< Same directions
+	DIAGDIRDIFF_90RIGHT = 1,        ///< 90 degrees right
+	DIAGDIRDIFF_REVERSE = 2,        ///< Reverse directions
+	DIAGDIRDIFF_90LEFT  = 3         ///< 90 degrees left
 };
 
+/**
+ * Applies a difference on a DiagDirection
+ *
+ * This function applies a difference on a DiagDirection and returns
+ * the new DiagDirection.
+ *
+ * @param d The DiagDirection
+ * @param delta The difference to applie on
+ * @return The new direction which was calculated
+ */
 static inline DiagDirection ChangeDiagDir(DiagDirection d, DiagDirDiff delta)
 {
 	return (DiagDirection)((d + delta) % 4);
 }
 
-
+/**
+ * Convert a Direction to a DiagDirection.
+ *
+ * This function can be used to convert the 8-way Direction to
+ * the 4-way DiagDirection. If the direction cannot be mapped its
+ * "rounded clockwise". So DIR_N becomes DIAGDIR_NE.
+ *
+ * @param dir The direction to convert
+ * @return The resulting DiagDirection, maybe "rounded clockwise".
+ */
 static inline DiagDirection DirToDiagDir(Direction dir)
 {
 	return (DiagDirection)(dir >> 1);
 }
 
-
+/**
+ * Convert a DiagDirection to a Direction.
+ *
+ * This function can be used to convert the 4-way DiagDirection
+ * to the 8-way Direction. As 4-way are less than 8-way not all
+ * possible directions can be calculated.
+ *
+ * @param dir The direction to convert
+ * @return The resulting Direction
+ */
 static inline Direction DiagDirToDir(DiagDirection dir)
 {
 	return (Direction)(dir * 2 + 1);
 }
 
 
-/* the 2 axis */
+/**
+ * Enumeration for the two axis X and Y
+ *
+ * This enumeration represente the two axis X and Y in the game.
+ * The X axis is the one which goes align the north-west edge
+ * (and south-east edge). The Y axis must be so the one which goes
+ * align the north-east edge (and south-west) edge.
+ */
 enum Axis {
-	AXIS_X = 0,
-	AXIS_Y = 1,
-	AXIS_END
+	AXIS_X = 0,     ///< The X axis
+	AXIS_Y = 1,     ///< The y axis
+	AXIS_END        ///< Used for iterations
 };
 
 
+/**
+ * Select the other axis as provided.
+ *
+ * This is basically the not-operator for the axis.
+ *
+ * @param a The given axis
+ * @return The other axis
+ */
 static inline Axis OtherAxis(Axis a)
 {
 	return (Axis)(a ^ 1);
 }
 
 
+/**
+ * Convert a DiagDirection to the axis.
+ *
+ * This function returns the axis which belongs to the given
+ * DiagDirection. The axis X belongs to the DiagDirection
+ * north-east and south-west.
+ *
+ * @param d The DiagDirection
+ * @return The axis which belongs to the direction
+ */
 static inline Axis DiagDirToAxis(DiagDirection d)
 {
 	return (Axis)(d & 1);
 }
 
 
-/*
+/**
  * Converts an Axis to a DiagDirection
- * Points always in the positive direction, i.e. S[EW]
+ *
+ * This function returns the DiagDirection which
+ * belongs to the axis. As 2 directions are mapped to an axis
+ * this function returns the one which points to south,
+ * either south-west (on X axis) or south-east (on Y axis)
+ *
+ * @param a The axis
+ * @return The direction pointed to south
  */
 static inline DiagDirection AxisToDiagDir(Axis a)
 {
@@ -146,17 +283,34 @@
 	return (DiagDirection)(xy * 3 ^ ns * 2);
 }
 
-
+/**
+ * Checks if an interger value is a valid DiagDirection
+ *
+ * @param d The value to check
+ * @return True if the value belongs to a DiagDirection, else false
+ */
 static inline bool IsValidDiagDirection(DiagDirection d)
 {
 	return d < DIAGDIR_END;
 }
 
+/**
+ * Checks if an integer value is a valid Direction
+ *
+ * @param d The value to check
+ * @return True if the value belongs to a Direction, else false
+ */
 static inline bool IsValidDirection(Direction d)
 {
 	return d < DIR_END;
 }
 
+/**
+ * Checks if an integer value is a valid Axis
+ *
+ * @param d The value to check
+ * @return True if the value belongs to an Axis, else false
+ */
 static inline bool IsValidAxis(Axis d)
 {
 	return d < AXIS_END;
--- a/src/disaster_cmd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/disaster_cmd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -608,7 +608,7 @@
 		}
 
 		InitializeDisasterVehicle(u, -6 * TILE_SIZE, v->y_pos, 135, DIR_SW, ST_Big_Ufo_Destroyer);
-		u->u.disaster.unk2 = v->index;
+		u->u.disaster.big_ufo_destroyer_target = v->index;
 
 		w = ForceAllocateSpecialVehicle();
 		if (w == NULL) return;
@@ -668,7 +668,7 @@
 	}
 
 	if (v->current_order.dest == 0) {
-		u = GetVehicle(v->u.disaster.unk2);
+		u = GetVehicle(v->u.disaster.big_ufo_destroyer_target);
 		if (delta(v->x_pos, u->x_pos) > TILE_SIZE) return;
 		v->current_order.dest = 1;
 
@@ -987,7 +987,7 @@
 
 				{
 					TileIndex tile = i->xy;
-					TileIndexDiff step = TileOffsByDiagDir(GB(Random(), 0, 2));
+					TileIndexDiff step = TileOffsByDiagDir((DiagDirection)GB(Random(), 0, 2));
 					uint n;
 
 					for (n = 0; n < 30; n++) {
--- a/src/dock_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/dock_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -217,7 +217,7 @@
 };
 
 static const WindowDesc _build_docks_toolbar_desc = {
-	WDP_ALIGN_TBR, 22, 136, 36,
+	WDP_ALIGN_TBR, 22, 136, 36, 136, 36,
 	WC_BUILD_TOOLBAR, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
 	_build_docks_toolb_widgets,
@@ -297,7 +297,7 @@
 };
 
 static const WindowDesc _build_dock_station_desc = {
-	WDP_AUTO, WDP_AUTO, 148, 75,
+	WDP_AUTO, WDP_AUTO, 148, 75, 148, 75,
 	WC_BUILD_STATION, WC_BUILD_TOOLBAR,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_build_dock_station_widgets,
@@ -366,7 +366,7 @@
 };
 
 static const WindowDesc _build_docks_depot_desc = {
-	WDP_AUTO, WDP_AUTO, 204, 86,
+	WDP_AUTO, WDP_AUTO, 204, 86, 204, 86,
 	WC_BUILD_DEPOT, WC_BUILD_TOOLBAR,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_build_docks_depot_widgets,
--- a/src/driver.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/driver.h	Fri Aug 03 18:10:15 2007 +0000
@@ -11,8 +11,8 @@
 #include <string>
 #include <map>
 
-bool GetDriverParamBool(const char* const* parm, const char* name);
-int GetDriverParamInt(const char* const* parm, const char* name, int def);
+bool GetDriverParamBool(const char * const *parm, const char *name);
+int GetDriverParamInt(const char * const *parm, const char *name, int def);
 
 class Driver {
 public:
--- a/src/dummy_land.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/dummy_land.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -21,9 +21,9 @@
 	return 0;
 }
 
-static Slope GetSlopeTileh_Dummy(TileIndex tile, Slope tileh)
+static Foundation GetFoundation_Dummy(TileIndex tile, Slope tileh)
 {
-	return SLOPE_FLAT;
+	return FOUNDATION_NONE;
 }
 
 static CommandCost ClearTile_Dummy(TileIndex tile, byte flags)
@@ -81,5 +81,5 @@
 	ChangeTileOwner_Dummy,    /* change_tile_owner_clear */
 	NULL,                     /* get_produced_cargo_proc */
 	NULL,                     /* vehicle_enter_tile_proc */
-	GetSlopeTileh_Dummy,      /* get_slope_tileh_proc */
+	GetFoundation_Dummy,      /* get_foundation_proc */
 };
--- a/src/economy.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/economy.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -1168,7 +1168,6 @@
 Money GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days, CargoID cargo_type)
 {
 	const CargoSpec *cs = GetCargo(cargo_type);
-	byte f;
 
 	/* Use callback to calculate cargo profit, if available */
 	if (HASBIT(cs->callback_mask, CBM_CARGO_PROFIT_CALC)) {
@@ -1187,28 +1186,39 @@
 		}
 	}
 
-	/* zero the distance if it's the bank and very short transport. */
-	if (_opt.landscape == LT_TEMPERATE && cs->label == 'VALU' && dist < 10)
-		dist = 0;
-
-	f = 255;
-	if (transit_days > cs->transit_days[0]) {
-		transit_days -= cs->transit_days[0];
-		f -= transit_days;
+	/* zero the distance (thus income) if it's the bank and very short transport. */
+	if (_opt.landscape == LT_TEMPERATE && cs->label == 'VALU' && dist < 10) return 0;
 
-		if (transit_days > cs->transit_days[1]) {
-			transit_days -= cs->transit_days[1];
 
-			if (f < transit_days) {
-				f = 0;
-			} else {
-				f -= transit_days;
-			}
-		}
+	static const int MIN_TIME_FACTOR = 31;
+	static const int MAX_TIME_FACTOR = 255;
+
+	const int days1 = cs->transit_days[0];
+	const int days2 = cs->transit_days[1];
+	const int days_over_days1 = transit_days - days1;
+
+	/*
+	 * The time factor is calculated based on the time it took
+	 * (transit_days) compared two cargo-depending values. The
+	 * range is divided into three parts:
+	 *
+	 *  - constant for fast transits
+	 *  - linear decreasing with time with a slope of -1 for medium transports
+	 *  - linear decreasing with time with a slope of -2 for slow transports
+	 *
+	 */
+	int time_factor;
+	if (days_over_days1 <= 0) {
+		time_factor = MAX_TIME_FACTOR;
+	} else if (days_over_days1 <= days2) {
+		time_factor = MAX_TIME_FACTOR - days_over_days1;
+	} else {
+		time_factor = MAX_TIME_FACTOR - 2 * days_over_days1 + days2;
 	}
-	if (f < 31) f = 31;
 
-	return BIGMULSS(dist * f * num_pieces, _cargo_payment_rates[cargo_type], 21);
+	if (time_factor < MIN_TIME_FACTOR) time_factor = MIN_TIME_FACTOR;
+
+	return BIGMULSS(dist * time_factor * num_pieces, _cargo_payment_rates[cargo_type], 21);
 }
 
 static void DeliverGoodsToIndustry(TileIndex xy, CargoID cargo_type, int num_pieces)
--- a/src/economy.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/economy.h	Fri Aug 03 18:10:15 2007 +0000
@@ -61,7 +61,7 @@
 int UpdateCompanyRatingAndValue(Player *p, bool update);
 
 VARDEF Subsidy _subsidies[MAX_PLAYERS];
-Pair SetupSubsidyDecodeParam(const Subsidy* s, bool mode);
+Pair SetupSubsidyDecodeParam(const Subsidy *s, bool mode);
 void DeleteSubsidyWithTown(TownID index);
 void DeleteSubsidyWithIndustry(IndustryID index);
 void DeleteSubsidyWithStation(StationID index);
--- a/src/elrail.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/elrail.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -102,7 +102,7 @@
 				return AxisToTrackBits(DiagDirToAxis(GetBridgeRampDirection(t)));
 			}
 
-		case MP_STREET:
+		case MP_ROAD:
 			if (GetRoadTileType(t) != ROAD_TILE_CROSSING) return TRACK_BIT_NONE;
 			if (GetRailType(t) != RAILTYPE_ELECTRIC) return TRACK_BIT_NONE;
 			return GetCrossingRailBits(t);
@@ -176,7 +176,7 @@
 
 	for (i = DIAGDIR_NE; i < DIAGDIR_END; i++) {
 		TileIndex neighbour = ti->tile + TileOffsByDiagDir(i);
-		uint foundation = 0;
+		Foundation foundation = FOUNDATION_NONE;
 		int k;
 
 		/* Here's one of the main headaches. GetTileSlope does not correct for possibly
@@ -225,9 +225,7 @@
 			foundation = GetBridgeFoundation(tileh[TS_NEIGHBOUR], DiagDirToAxis(GetBridgeRampDirection(neighbour)));
 		}
 
-		if (foundation != 0) {
-			tileh[TS_NEIGHBOUR] = foundation < 15 ? SLOPE_FLAT : _inclined_tileh[foundation - 15];
-		}
+		ApplyFoundationToSlope(foundation, &tileh[TS_NEIGHBOUR]);
 
 		AdjustTileh(neighbour, &tileh[TS_NEIGHBOUR]);
 
@@ -270,15 +268,9 @@
 						continue; /* No neighbour, go looking for a better position */
 					}
 
-					SpriteID img = pylons_normal[temp];
-					SpriteID pal = PAL_NONE;
-					if (HASBIT(_transparent_opt, TO_BUILDINGS)) {
-						SETBIT(img, PALETTE_MODIFIER_TRANSPARENT);
-						pal = PALETTE_TO_TRANSPARENT;
-					}
-
-					AddSortableSpriteToDraw(img, pal, x, y, 1, 1, 10,
-							GetSlopeZ(ti->x + x_pcp_offsets[i], ti->y + y_pcp_offsets[i]));
+					AddSortableSpriteToDraw(pylons_normal[temp], PAL_NONE, x, y, 1, 1, 10,
+							GetSlopeZ(ti->x + x_pcp_offsets[i], ti->y + y_pcp_offsets[i]),
+							HASBIT(_transparent_opt, TO_BUILDINGS));
 					break; /* We already have drawn a pylon, bail out */
 				}
 			}
@@ -315,15 +307,9 @@
 			assert(!IsSteepSlope(tileh[TS_HOME]));
 			sss = &CatenarySpriteData[Wires[tileh_selector][t][PCPconfig]];
 
-			SpriteID img = sss->image;
-			SpriteID pal = PAL_NONE;
-			if (HASBIT(_transparent_opt, TO_BUILDINGS)) {
-				SETBIT(img, PALETTE_MODIFIER_TRANSPARENT);
-				pal = PALETTE_TO_TRANSPARENT;
-			}
-
-			AddSortableSpriteToDraw(img, pal, ti->x + sss->x_offset, ti->y + sss->y_offset,
-				sss->x_size, sss->y_size, sss->z_size, GetSlopeZ(ti->x + min(sss->x_offset, TILE_SIZE - 1), ti->y + min(sss->y_offset, TILE_SIZE - 1)) + sss->z_offset);
+			AddSortableSpriteToDraw(sss->image, PAL_NONE, ti->x + sss->x_offset, ti->y + sss->y_offset,
+				sss->x_size, sss->y_size, sss->z_size, GetSlopeZ(ti->x + min(sss->x_offset, TILE_SIZE - 1), ti->y + min(sss->y_offset, TILE_SIZE - 1)) + sss->z_offset,
+				HASBIT(_transparent_opt, TO_BUILDINGS));
 		}
 	}
 }
@@ -354,41 +340,27 @@
 
 	height = GetBridgeHeight(end);
 
-	SpriteID img = sss->image;
-	SpriteID pal = PAL_NONE;
-	if (HASBIT(_transparent_opt, TO_BUILDINGS)) {
-		SETBIT(img, PALETTE_MODIFIER_TRANSPARENT);
-		pal = PALETTE_TO_TRANSPARENT;
-	}
-
-	AddSortableSpriteToDraw(img, pal, ti->x + sss->x_offset, ti->y + sss->y_offset,
-		sss->x_size, sss->y_size, sss->z_size, height + sss->z_offset
+	AddSortableSpriteToDraw(sss->image, PAL_NONE, ti->x + sss->x_offset, ti->y + sss->y_offset,
+		sss->x_size, sss->y_size, sss->z_size, height + sss->z_offset,
+		HASBIT(_transparent_opt, TO_BUILDINGS)
 	);
 
 	/* Finished with wires, draw pylons */
 	/* every other tile needs a pylon on the northern end */
 	if (num % 2) {
 		if (axis == AXIS_X) {
-			img = pylons_bridge[0 + HASBIT(tlg, 0)];
-			if (HASBIT(_transparent_opt, TO_BUILDINGS)) SETBIT(img, PALETTE_MODIFIER_TRANSPARENT);
-			AddSortableSpriteToDraw(img, pal, ti->x, ti->y + 4 + 8 * HASBIT(tlg, 0), 1, 1, 10, height);
+			AddSortableSpriteToDraw(pylons_bridge[0 + HASBIT(tlg, 0)], PAL_NONE, ti->x, ti->y + 4 + 8 * HASBIT(tlg, 0), 1, 1, 10, height, HASBIT(_transparent_opt, TO_BUILDINGS));
 		} else {
-			img = pylons_bridge[2 + HASBIT(tlg, 1)];
-			if (HASBIT(_transparent_opt, TO_BUILDINGS)) SETBIT(img, PALETTE_MODIFIER_TRANSPARENT);
-			AddSortableSpriteToDraw(img, pal, ti->x + 4 + 8 * HASBIT(tlg, 1), ti->y, 1, 1, 10, height);
+			AddSortableSpriteToDraw(pylons_bridge[2 + HASBIT(tlg, 1)], PAL_NONE, ti->x + 4 + 8 * HASBIT(tlg, 1), ti->y, 1, 1, 10, height, HASBIT(_transparent_opt, TO_BUILDINGS));
 		}
 	}
 
 	/* need a pylon on the southern end of the bridge */
 	if (DistanceMax(ti->tile, start) == length) {
 		if (axis == AXIS_X) {
-			img = pylons_bridge[0 + HASBIT(tlg, 0)];
-			if (HASBIT(_transparent_opt, TO_BUILDINGS)) SETBIT(img, PALETTE_MODIFIER_TRANSPARENT);
-			AddSortableSpriteToDraw(img, pal, ti->x + 16, ti->y + 4 + 8 * HASBIT(tlg, 0), 1, 1, 10, height);
+			AddSortableSpriteToDraw(pylons_bridge[0 + HASBIT(tlg, 0)], PAL_NONE, ti->x + 16, ti->y + 4 + 8 * HASBIT(tlg, 0), 1, 1, 10, height, HASBIT(_transparent_opt, TO_BUILDINGS));
 		} else {
-			img = pylons_bridge[2 + HASBIT(tlg, 1)];
-			if (HASBIT(_transparent_opt, TO_BUILDINGS)) SETBIT(img, PALETTE_MODIFIER_TRANSPARENT);
-			AddSortableSpriteToDraw(img, pal, ti->x + 4 + 8 * HASBIT(tlg, 1), ti->y + 16, 1, 1, 10, height);
+			AddSortableSpriteToDraw(pylons_bridge[2 + HASBIT(tlg, 1)], PAL_NONE, ti->x + 4 + 8 * HASBIT(tlg, 1), ti->y + 16, 1, 1, 10, height, HASBIT(_transparent_opt, TO_BUILDINGS));
 		}
 	}
 }
@@ -410,24 +382,18 @@
 			if (IsRailDepot(ti->tile)) {
 				const SortableSpriteStruct *sss = &CatenarySpriteData_Depot[GetRailDepotDirection(ti->tile)];
 
-				SpriteID img = sss->image;
-				SpriteID pal = PAL_NONE;
-				if (HASBIT(_transparent_opt, TO_BUILDINGS)) {
-					SETBIT(img, PALETTE_MODIFIER_TRANSPARENT);
-					pal = PALETTE_TO_TRANSPARENT;
-				}
-
 				AddSortableSpriteToDraw(
-					img, pal, ti->x + sss->x_offset, ti->y + sss->y_offset,
+					sss->image, PAL_NONE, ti->x + sss->x_offset, ti->y + sss->y_offset,
 					sss->x_size, sss->y_size, sss->z_size,
-					GetTileMaxZ(ti->tile) + sss->z_offset
+					GetTileMaxZ(ti->tile) + sss->z_offset,
+					HASBIT(_transparent_opt, TO_BUILDINGS)
 				);
 				return;
 			}
 			break;
 
 		case MP_TUNNELBRIDGE:
-		case MP_STREET:
+		case MP_ROAD:
 		case MP_STATION:
 			break;
 
--- a/src/endian_check.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/endian_check.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -12,45 +12,41 @@
 #include <stdio.h>
 #include <string.h>
 
-/** Main call of the endian_check program
+/**
+ * Main call of the endian_check program
  * @param argc argument count
  * @param argv arguments themselves
- * @return exit code */
-int main (int argc, char *argv[]) {
-	unsigned char EndianTest[2] = { 1, 0 };
+ * @return exit code
+ */
+int main (int argc, char *argv[])
+{
+	unsigned char endian_test[2] = { 1, 0 };
 	int force_BE = 0, force_LE = 0, force_PREPROCESSOR = 0;
 
-	if (argc > 1 && strcmp(argv[1], "BE") == 0)
-		force_BE = 1;
-	if (argc > 1 && strcmp(argv[1], "LE") == 0)
-		force_LE = 1;
-	if (argc > 1 && strcmp(argv[1], "PREPROCESSOR") == 0)
-		force_PREPROCESSOR = 1;
+	if (argc > 1 && strcmp(argv[1], "BE") == 0) force_BE = 1;
+	if (argc > 1 && strcmp(argv[1], "LE") == 0) force_LE = 1;
+	if (argc > 1 && strcmp(argv[1], "PREPROCESSOR") == 0) force_PREPROCESSOR = 1;
 
 	printf("#ifndef ENDIAN_H\n#define ENDIAN_H\n");
 
 	if (force_LE == 1) {
 		printf("#define TTD_LITTLE_ENDIAN\n");
+	} else if (force_BE == 1) {
+		printf("#define TTD_BIG_ENDIAN\n");
+	} else if (force_PREPROCESSOR == 1) {
+		/* Support for universal binaries on OSX
+		 * Universal binaries supports both PPC and x86
+		 * If a compiler for OSX gets this setting, it will always pick the correct endian and no test is needed
+		 */
+		printf("#ifdef __BIG_ENDIAN__\n");
+		printf("#define TTD_BIG_ENDIAN\n");
+		printf("#else\n");
+		printf("#define TTD_LITTLE_ENDIAN\n");
+		printf("#endif\n");
+	} else if (*(short*)endian_test == 1 ) {
+		printf("#define TTD_LITTLE_ENDIAN\n");
 	} else {
-		if (force_BE == 1) {
-			printf("#define TTD_BIG_ENDIAN\n");
-		} else {
-			if (force_PREPROCESSOR == 1) {
-				/** adding support for universal binaries on OSX
-				 * Universal binaries supports both PPC and x86
-				 * If a compiler for OSX gets this setting, it will always pick the correct endian and no test is needed */
-				printf("#ifdef __BIG_ENDIAN__\n");
-				printf("#define TTD_BIG_ENDIAN\n");
-				printf("#else\n");
-				printf("#define TTD_LITTLE_ENDIAN\n");
-				printf("#endif\n");
-			} else {
-				if ( *(short *) EndianTest == 1 )
-					printf("#define TTD_LITTLE_ENDIAN\n");
-				else
-					printf("#define TTD_BIG_ENDIAN\n");
-			}
-		}
+		printf("#define TTD_BIG_ENDIAN\n");
 	}
 	printf("#endif\n");
 
--- a/src/engine.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/engine.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -23,6 +23,7 @@
 #include "group.h"
 #include "string.h"
 #include "strings.h"
+#include "misc/autoptr.hpp"
 
 EngineInfo _engine_info[TOTAL_NUM_ENGINES];
 RailVehicleInfo _rail_vehicle_info[NUM_TRAIN_ENGINES];
@@ -479,43 +480,7 @@
  * Engine Replacement stuff
  ************************************************************************/
 
-static void EngineRenewPoolNewBlock(uint start_item);
-
-DEFINE_OLD_POOL(EngineRenew, EngineRenew, EngineRenewPoolNewBlock, NULL)
-
-static void EngineRenewPoolNewBlock(uint start_item)
-{
-	EngineRenew *er;
-
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 *  TODO - This is just a temporary stage, this will be removed. */
-	for (er = GetEngineRenew(start_item); er != NULL; er = (er->index + 1U < GetEngineRenewPoolSize()) ? GetEngineRenew(er->index + 1U) : NULL) {
-		er->index = start_item++;
-		er->from = INVALID_ENGINE;
-	}
-}
-
-
-static EngineRenew *AllocateEngineRenew()
-{
-	EngineRenew *er;
-
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 *  TODO - This is just a temporary stage, this will be removed. */
-	for (er = GetEngineRenew(0); er != NULL; er = (er->index + 1U < GetEngineRenewPoolSize()) ? GetEngineRenew(er->index + 1U) : NULL) {
-		if (IsValidEngineRenew(er)) continue;
-
-		er->to = INVALID_ENGINE;
-		er->next = NULL;
-		er->group_id = ALL_GROUP;
-		return er;
-	}
-
-	/* Check if we can add a block to the pool */
-	if (AddBlockToPool(&_EngineRenew_pool)) return AllocateEngineRenew();
-
-	return NULL;
-}
+DEFINE_OLD_POOL_GENERIC(EngineRenew, EngineRenew)
 
 /**
  * Retrieves the EngineRenew that specifies the replacement of the given
@@ -536,9 +501,9 @@
 	EngineRenew *er = (EngineRenew *)(*erl);
 	EngineRenew *next;
 
-	while (er) {
+	while (er != NULL) {
 		next = er->next;
-		DeleteEngineRenew(er);
+		delete er;
 		er = next;
 	}
 	*erl = NULL; // Empty list
@@ -561,17 +526,19 @@
 		return CommandCost();
 	}
 
-	er = AllocateEngineRenew();
+	er = new EngineRenew(old_engine, new_engine);
 	if (er == NULL) return CMD_ERROR;
+	AutoPtrT<EngineRenew> er_auto_delete = er;
+
 
 	if (flags & DC_EXEC) {
-		er->from = old_engine;
-		er->to = new_engine;
 		er->group_id = group;
 
 		/* Insert before the first element */
 		er->next = (EngineRenew *)(*erl);
 		*erl = (EngineRenewList)er;
+
+		er_auto_delete.Detach();
 	}
 
 	return CommandCost();
@@ -593,7 +560,7 @@
 					/* Cut this element out */
 					prev->next = er->next;
 				}
-				DeleteEngineRenew(er);
+				delete er;
 			}
 			return CommandCost();
 		}
@@ -628,12 +595,7 @@
 	int index;
 
 	while ((index = SlIterateArray()) != -1) {
-		EngineRenew *er;
-
-		if (!AddBlockIfNeeded(&_EngineRenew_pool, index))
-			error("EngineRenews: failed loading savegame: too many EngineRenews");
-
-		er = GetEngineRenew(index);
+		EngineRenew *er = new (index) EngineRenew();
 		SlObject(er, _engine_renew_desc);
 
 		/* Advanced vehicle lists, ungrouped vehicles got added */
@@ -704,6 +666,6 @@
 void InitializeEngines()
 {
 	/* Clean the engine renew pool and create 1 block in it */
-	CleanPool(&_EngineRenew_pool);
-	AddBlockToPool(&_EngineRenew_pool);
+	_EngineRenew_pool.CleanPool();
+	_EngineRenew_pool.AddBlockToPool();
 }
--- a/src/engine.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/engine.h	Fri Aug 03 18:10:15 2007 +0000
@@ -45,7 +45,7 @@
 	                    //       kind of visual effect to generate for a vehicle (default, steam, diesel, electric).
 	                    //       Same goes for the callback result, which atm is only used to check if a wagon is powered.
 	byte shorten_factor;   ///< length on main map for this type is 8 - shorten_factor
-	byte tractive_effort; ///< Tractive effort coefficient
+	byte tractive_effort;  ///< Tractive effort coefficient
 	byte user_def_data;    ///< Property 0x25: "User-defined bit mask" Used only for (very few) NewGRF vehicles
 };
 
@@ -262,19 +262,7 @@
  * Engine Replacement stuff
  ************************************************************************/
 
-/**
- * Struct to store engine replacements. DO NOT USE outside of engine.c. Is
- * placed here so the only exception to this rule, the saveload code, can use
- * it.
- */
-struct EngineRenew {
-	EngineRenewID index;
-	EngineID from;
-	EngineID to;
-	EngineRenew *next;
-	GroupID group_id;
-};
-
+struct EngineRenew;
 /**
  * Memory pool for engine renew elements. DO NOT USE outside of engine.c. Is
  * placed here so the only exception to this rule, the saveload code, can use
@@ -283,19 +271,23 @@
 DECLARE_OLD_POOL(EngineRenew, EngineRenew, 3, 8000)
 
 /**
- * Check if a EngineRenew really exists.
+ * Struct to store engine replacements. DO NOT USE outside of engine.c. Is
+ * placed here so the only exception to this rule, the saveload code, can use
+ * it.
  */
-static inline bool IsValidEngineRenew(const EngineRenew *er)
-{
-	return er->from != INVALID_ENGINE;
-}
+struct EngineRenew : PoolItem<EngineRenew, EngineRenewID, &_EngineRenew_pool> {
+	EngineID from;
+	EngineID to;
+	EngineRenew *next;
+	GroupID group_id;
 
-static inline void DeleteEngineRenew(EngineRenew *er)
-{
-	er->from = INVALID_ENGINE;
-}
+	EngineRenew(EngineID from = INVALID_ENGINE, EngineID to = INVALID_ENGINE) : from(from), to(to), next(NULL) {}
+	~EngineRenew() { this->from = INVALID_ENGINE; }
 
-#define FOR_ALL_ENGINE_RENEWS_FROM(er, start) for (er = GetEngineRenew(start); er != NULL; er = (er->index + 1U < GetEngineRenewPoolSize()) ? GetEngineRenew(er->index + 1U) : NULL) if (er->from != INVALID_ENGINE) if (IsValidEngineRenew(er))
+	bool IsValid() const { return this->from != INVALID_ENGINE; }
+};
+
+#define FOR_ALL_ENGINE_RENEWS_FROM(er, start) for (er = GetEngineRenew(start); er != NULL; er = (er->index + 1U < GetEngineRenewPoolSize()) ? GetEngineRenew(er->index + 1U) : NULL) if (er->IsValid())
 #define FOR_ALL_ENGINE_RENEWS(er) FOR_ALL_ENGINE_RENEWS_FROM(er, 0)
 
 
@@ -309,7 +301,7 @@
  * @param  erl The renewlist for a given player.
  * @return The new renewlist for the player.
  */
-void RemoveAllEngineReplacement(EngineRenewList* erl);
+void RemoveAllEngineReplacement(EngineRenewList *erl);
 
 /**
  * Retrieve the engine replacement in a given renewlist for an original engine type.
@@ -328,7 +320,7 @@
  * @param flags The calling command flags.
  * @return 0 on success, CMD_ERROR on failure.
  */
-CommandCost AddEngineReplacement(EngineRenewList* erl, EngineID old_engine, EngineID new_engine, GroupID group, uint32 flags);
+CommandCost AddEngineReplacement(EngineRenewList *erl, EngineID old_engine, EngineID new_engine, GroupID group, uint32 flags);
 
 /**
  * Remove an engine replacement from a given renewlist.
@@ -337,7 +329,7 @@
  * @param flags The calling command flags.
  * @return 0 on success, CMD_ERROR on failure.
  */
-CommandCost RemoveEngineReplacement(EngineRenewList* erl, EngineID engine, GroupID group, uint32 flags);
+CommandCost RemoveEngineReplacement(EngineRenewList *erl, EngineID engine, GroupID group, uint32 flags);
 
 /** When an engine is made buildable or is removed from being buildable, add/remove it from the build/autoreplace lists
  * @param type The type of engine
--- a/src/engine_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/engine_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -104,7 +104,7 @@
 }
 
 static const WindowDesc _engine_preview_desc = {
-	WDP_CENTER, WDP_CENTER, 300, 192,
+	WDP_CENTER, WDP_CENTER, 300, 192, 300, 192,
 	WC_ENGINE_PREVIEW, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_engine_preview_widgets,
--- a/src/fileio.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/fileio.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -66,8 +66,8 @@
 {
 	/* Do we still have the file open, or should we reopen it? */
 	if (_fio.handles[slot] == NULL) {
-		DEBUG(misc, 6, "Restoring file '%s' in slot '%d' from disk", _fio.filename[slot], slot);
-		FioOpenFile(slot, _fio.filename[slot]);
+		DEBUG(misc, 6, "Restoring file '%s' in slot '%d' from disk", _fio.filenames[slot], slot);
+		FioOpenFile(slot, _fio.filenames[slot]);
 	}
 	_fio.usage_count[slot]++;
 }
@@ -165,7 +165,7 @@
 			}
 		}
 		assert(slot != -1);
-		DEBUG(misc, 6, "Closing filehandler '%s' in slot '%d' because of fd-limit", _fio.filename[slot], slot);
+		DEBUG(misc, 6, "Closing filehandler '%s' in slot '%d' because of fd-limit", _fio.filenames[slot], slot);
 		FioCloseFile(slot);
 	}
 }
--- a/src/functions.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/functions.h	Fri Aug 03 18:10:15 2007 +0000
@@ -96,7 +96,7 @@
 /* misc.cpp */
 bool IsCustomName(StringID id);
 void DeleteName(StringID id);
-char *GetName(char *buff, StringID id, const char* last);
+char *GetName(char *buff, StringID id, const char *last);
 
 #define AllocateName(name, skip) RealAllocateName(name, skip, false)
 StringID RealAllocateName(const char *name, byte skip, bool check_double);
@@ -117,7 +117,7 @@
 
 void ResetObjectToPlace();
 
-bool ScrollWindowTo(int x, int y, Window * w, bool instant = false);
+bool ScrollWindowTo(int x, int y, Window *w, bool instant = false);
 
 bool ScrollMainWindowToTile(TileIndex tile, bool instant = false);
 bool ScrollMainWindowTo(int x, int y, bool instant = false);
--- a/src/genworld_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/genworld_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -255,7 +255,7 @@
 		SetWindowWidgetDisabledState(w, GLAND_START_DATE_DOWN, _patches_newgame.starting_year <= MIN_YEAR);
 		SetWindowWidgetDisabledState(w, GLAND_START_DATE_UP,   _patches_newgame.starting_year >= MAX_YEAR);
 		SetWindowWidgetDisabledState(w, GLAND_SNOW_LEVEL_DOWN, _patches_newgame.snow_line_height <= 2 || _opt_newgame.landscape != LT_ARCTIC);
-		SetWindowWidgetDisabledState(w, GLAND_SNOW_LEVEL_UP,   _patches_newgame.snow_line_height >= 13 || _opt_newgame.landscape != LT_ARCTIC);
+		SetWindowWidgetDisabledState(w, GLAND_SNOW_LEVEL_UP,   _patches_newgame.snow_line_height >= MAX_SNOWLINE_HEIGHT || _opt_newgame.landscape != LT_ARCTIC);
 
 		SetWindowWidgetLoweredState(w, GLAND_TEMPERATE, _opt_newgame.landscape == LT_TEMPERATE);
 		SetWindowWidgetLoweredState(w, GLAND_ARCTIC,    _opt_newgame.landscape == LT_ARCTIC);
@@ -402,7 +402,7 @@
 				HandleButtonClick(w, e->we.click.widget);
 				SetWindowDirty(w);
 
-				_patches_newgame.snow_line_height = clamp(_patches_newgame.snow_line_height + e->we.click.widget - GLAND_SNOW_LEVEL_TEXT, 2, 13);
+				_patches_newgame.snow_line_height = clamp(_patches_newgame.snow_line_height + e->we.click.widget - GLAND_SNOW_LEVEL_TEXT, 2, MAX_SNOWLINE_HEIGHT);
 			}
 			_left_button_clicked = false;
 			break;
@@ -498,7 +498,7 @@
 				break;
 			case GLAND_SNOW_LEVEL_TEXT:
 				InvalidateWidget(w, GLAND_SNOW_LEVEL_TEXT);
-				_patches_newgame.snow_line_height = clamp(value, 2, 13);
+				_patches_newgame.snow_line_height = clamp(value, 2, MAX_SNOWLINE_HEIGHT);
 				break;
 			}
 
@@ -510,7 +510,7 @@
 }
 
 static const WindowDesc _generate_landscape_desc = {
-	WDP_CENTER, WDP_CENTER, 338, 268,
+	WDP_CENTER, WDP_CENTER, 338, 268, 338, 268,
 	WC_GENERATE_LANDSCAPE, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_generate_landscape_widgets,
@@ -518,7 +518,7 @@
 };
 
 static const WindowDesc _heightmap_load_desc = {
-	WDP_CENTER, WDP_CENTER, 338, 236,
+	WDP_CENTER, WDP_CENTER, 338, 236, 338, 236,
 	WC_GENERATE_LANDSCAPE, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS,
 	_heightmap_load_widgets,
@@ -611,7 +611,7 @@
 		SetWindowWidgetDisabledState(w, CSCEN_START_DATE_DOWN,       _patches_newgame.starting_year <= MIN_YEAR);
 		SetWindowWidgetDisabledState(w, CSCEN_START_DATE_UP,         _patches_newgame.starting_year >= MAX_YEAR);
 		SetWindowWidgetDisabledState(w, CSCEN_FLAT_LAND_HEIGHT_DOWN, _patches_newgame.se_flat_world_height <= 0);
-		SetWindowWidgetDisabledState(w, CSCEN_FLAT_LAND_HEIGHT_UP,   _patches_newgame.se_flat_world_height >= 15);
+		SetWindowWidgetDisabledState(w, CSCEN_FLAT_LAND_HEIGHT_UP,   _patches_newgame.se_flat_world_height >= MAX_TILE_HEIGHT);
 
 		SetWindowWidgetLoweredState(w, CSCEN_TEMPERATE, _opt_newgame.landscape == LT_TEMPERATE);
 		SetWindowWidgetLoweredState(w, CSCEN_ARCTIC,    _opt_newgame.landscape == LT_ARCTIC);
@@ -672,7 +672,7 @@
 				HandleButtonClick(w, e->we.click.widget);
 				SetWindowDirty(w);
 
-				_patches_newgame.se_flat_world_height = clamp(_patches_newgame.se_flat_world_height + e->we.click.widget - CSCEN_FLAT_LAND_HEIGHT_TEXT, 0, 15);
+				_patches_newgame.se_flat_world_height = clamp(_patches_newgame.se_flat_world_height + e->we.click.widget - CSCEN_FLAT_LAND_HEIGHT_TEXT, 0, MAX_TILE_HEIGHT);
 			}
 			_left_button_clicked = false;
 			break;
@@ -703,7 +703,7 @@
 				break;
 			case CSCEN_FLAT_LAND_HEIGHT_TEXT:
 				InvalidateWidget(w, CSCEN_FLAT_LAND_HEIGHT_TEXT);
-				_patches_newgame.se_flat_world_height = clamp(value, 0, 15);
+				_patches_newgame.se_flat_world_height = clamp(value, 0, MAX_TILE_HEIGHT);
 				break;
 			}
 
@@ -743,7 +743,7 @@
 };
 
 static const WindowDesc _create_scenario_desc = {
-	WDP_CENTER, WDP_CENTER, 338, 170,
+	WDP_CENTER, WDP_CENTER, 338, 170, 338, 170,
 	WC_GENERATE_LANDSCAPE, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS,
 	_create_scenario_widgets,
@@ -823,7 +823,7 @@
 }
 
 static const WindowDesc _show_terrain_progress_desc = {
-	WDP_CENTER, WDP_CENTER, 181, 97,
+	WDP_CENTER, WDP_CENTER, 181, 97, 181, 97,
 	WC_GENERATE_PROGRESS_WINDOW, WC_NONE,
 	WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_show_terrain_progress_widgets,
--- a/src/gfx.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/gfx.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -662,7 +662,7 @@
 
 	DoPaletteAnimations();
 	_pal_first_dirty = 0;
-	_pal_count_dirty = 255;
+	_pal_count_dirty = 256;
 }
 
 #define EXTR(p, q) (((uint16)(_palette_animation_counter * (p)) * (q)) >> 16)
@@ -1147,11 +1147,9 @@
 	SwitchAnimatedCursor();
 }
 
-bool ChangeResInGame(int w, int h)
+bool ChangeResInGame(int width, int height)
 {
-	return
-		(_screen.width == w && _screen.height == h) ||
-		_video_driver->ChangeResolution(w, h);
+	return (_screen.width == width && _screen.height == height) || _video_driver->ChangeResolution(width, height);
 }
 
 void ToggleFullScreen(bool fs)
--- a/src/gfx.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/gfx.h	Fri Aug 03 18:10:15 2007 +0000
@@ -71,7 +71,7 @@
 	WKC_F11         = 43,
 	WKC_F12         = 44,
 
-	/* backquote is the key left of "1"
+	/* Backquote is the key left of "1"
 	 * we only store this key here, no matter what character is really mapped to it
 	 * on a particular keyboard. (US keyboard: ` and ~ ; German keyboard: ^ and °) */
 	WKC_BACKQUOTE   = 45,
@@ -80,6 +80,21 @@
 	/* 0-9 are mapped to 48-57
 	 * A-Z are mapped to 65-90
 	 * a-z are mapped to 97-122 */
+
+	/* Other keys, corresponding to their ascii values */
+	WKC_SLASH       = 47, ///< / Forward slash
+	WKC_SEMICOLON   = 59, ///< ; Semicolon
+	WKC_EQUALS      = 61, ///< = Equals
+	WKC_L_BRACKET   = 91, ///< [ Left square bracket
+	WKC_BACKSLASH   = 92, ///< \ Backslash
+	WKC_R_BRACKET   = 93, ///< ] Right square bracket
+
+	/* Other keys of which their ascii value is already taken
+	 * - use unused ascii value not present on keyboard directly */
+	WKC_SINGLEQUOTE = 58, ///< ' Single quote
+	WKC_COMMA       = 60, ///< , Comma
+	WKC_PERIOD      = 62, ///< . Period
+	WKC_MINUS       = 95, ///< - Minus
 };
 
 enum GameModes {
@@ -95,7 +110,7 @@
 typedef int32 CursorID;
 
 struct Point {
-	int x,y;
+	int x, y;
 };
 
 struct Rect {
--- a/src/graph_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/graph_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -309,7 +309,7 @@
 };
 
 static const WindowDesc _graph_legend_desc = {
-	WDP_AUTO, WDP_AUTO, 250, 114,
+	WDP_AUTO, WDP_AUTO, 250, 114, 250, 114,
 	WC_GRAPH_LEGEND, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_graph_legend_widgets,
@@ -407,7 +407,7 @@
 };
 
 static const WindowDesc _operating_profit_desc = {
-	WDP_AUTO, WDP_AUTO, 576, 174,
+	WDP_AUTO, WDP_AUTO, 576, 174, 576, 174,
 	WC_OPERATING_PROFIT, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_operating_profit_widgets,
@@ -476,7 +476,7 @@
 };
 
 static const WindowDesc _income_graph_desc = {
-	WDP_AUTO, WDP_AUTO, 576, 142,
+	WDP_AUTO, WDP_AUTO, 576, 142, 576, 142,
 	WC_INCOME_GRAPH, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_income_graph_widgets,
@@ -543,7 +543,7 @@
 };
 
 static const WindowDesc _delivered_cargo_graph_desc = {
-	WDP_AUTO, WDP_AUTO, 576, 142,
+	WDP_AUTO, WDP_AUTO, 576, 142, 576, 142,
 	WC_DELIVERED_CARGO, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_delivered_cargo_graph_widgets,
@@ -612,7 +612,7 @@
 };
 
 static const WindowDesc _performance_history_desc = {
-	WDP_AUTO, WDP_AUTO, 576, 238,
+	WDP_AUTO, WDP_AUTO, 576, 238, 576, 238,
 	WC_PERFORMANCE_HISTORY, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_performance_history_widgets,
@@ -679,7 +679,7 @@
 };
 
 static const WindowDesc _company_value_graph_desc = {
-	WDP_AUTO, WDP_AUTO, 576, 238,
+	WDP_AUTO, WDP_AUTO, 576, 238, 576, 238,
 	WC_COMPANY_VALUE, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_company_value_graph_widgets,
@@ -776,7 +776,7 @@
 };
 
 static const WindowDesc _cargo_payment_rates_desc = {
-	WDP_AUTO, WDP_AUTO, 568, 46,
+	WDP_AUTO, WDP_AUTO, 568, 46, 568, 46,
 	WC_PAYMENT_RATES, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_cargo_payment_rates_widgets,
@@ -898,7 +898,7 @@
 };
 
 static const WindowDesc _company_league_desc = {
-	WDP_AUTO, WDP_AUTO, 400, 97,
+	WDP_AUTO, WDP_AUTO, 400, 97, 400, 97,
 	WC_COMPANY_LEAGUE, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
 	_company_league_widgets,
@@ -1137,7 +1137,7 @@
 };
 
 static const WindowDesc _performance_rating_detail_desc = {
-	WDP_AUTO, WDP_AUTO, 299, 228,
+	WDP_AUTO, WDP_AUTO, 299, 228, 299, 228,
 	WC_PERFORMANCE_DETAIL, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_performance_rating_detail_widgets,
--- a/src/group.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/group.h	Fri Aug 03 18:10:15 2007 +0000
@@ -13,40 +13,31 @@
 	INVALID_GROUP = 0xFFFF,
 };
 
-struct Group {
+struct Group;
+DECLARE_OLD_POOL(Group, Group, 5, 2047)
+
+struct Group : PoolItem<Group, GroupID, &_Group_pool> {
 	StringID string_id;                     ///< Group Name
 
 	uint16 num_vehicle;                     ///< Number of vehicles wich belong to the group
 	PlayerID owner;                         ///< Group Owner
-	GroupID index;                          ///< Array index
 	VehicleTypeByte vehicle_type;           ///< Vehicle type of the group
 
 	bool replace_protection;                ///< If set to true, the global autoreplace have no effect on the group
 	uint16 num_engines[TOTAL_NUM_ENGINES];  ///< Caches the number of engines of each type the player owns (no need to save this)
+
+	Group(StringID str = STR_NULL);
+	virtual ~Group();
+
+	void QuickFree();
+
+	bool IsValid() const;
 };
 
-DECLARE_OLD_POOL(Group, Group, 5, 2047)
-
-
-static inline bool IsValidGroup(const Group *g)
-{
-	return g->string_id != STR_NULL;
-}
-
-static inline void DestroyGroup(Group *g)
-{
-	DeleteName(g->string_id);
-}
-
-static inline void DeleteGroup(Group *g)
-{
-	DestroyGroup(g);
-	g->string_id = STR_NULL;
-}
 
 static inline bool IsValidGroupID(GroupID index)
 {
-	return index < GetGroupPoolSize() && IsValidGroup(GetGroup(index));
+	return index < GetGroupPoolSize() && GetGroup(index)->IsValid();
 }
 
 static inline bool IsDefaultGroupID(GroupID index)
@@ -64,7 +55,7 @@
 	return id_g == ALL_GROUP;
 }
 
-#define FOR_ALL_GROUPS_FROM(g, start) for (g = GetGroup(start); g != NULL; g = (g->index + 1U < GetGroupPoolSize()) ? GetGroup(g->index + 1) : NULL) if (IsValidGroup(g))
+#define FOR_ALL_GROUPS_FROM(g, start) for (g = GetGroup(start); g != NULL; g = (g->index + 1U < GetGroupPoolSize()) ? GetGroup(g->index + 1) : NULL) if (g->IsValid())
 #define FOR_ALL_GROUPS(g) FOR_ALL_GROUPS_FROM(g, 0)
 
 /**
--- a/src/group_cmd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/group_cmd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -19,6 +19,7 @@
 #include "window.h"
 #include "vehicle_gui.h"
 #include "strings.h"
+#include "misc/autoptr.hpp"
 
 /**
  * Update the num engines of a groupID. Decrease the old one and increase the new one
@@ -39,41 +40,34 @@
 }
 
 
-/**
- * Called if a new block is added to the group-pool
- */
-static void GroupPoolNewBlock(uint start_item)
+DEFINE_OLD_POOL_GENERIC(Group, Group)
+
+
+Group::Group(StringID str)
 {
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (Group *g = GetGroup(start_item); g != NULL; g = (g->index + 1U < GetGroupPoolSize()) ? GetGroup(g->index + 1) : NULL) g->index = start_item++;
+	this->string_id = str;
 }
 
-DEFINE_OLD_POOL(Group, Group, GroupPoolNewBlock, NULL)
-
-static Group *AllocateGroup(void)
+Group::~Group()
 {
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (Group *g = GetGroup(0); g != NULL; g = (g->index + 1U < GetGroupPoolSize()) ? GetGroup(g->index + 1) : NULL) {
-		if (!IsValidGroup(g)) {
-			const GroupID index = g->index;
+	this->QuickFree();
+	this->string_id = STR_NULL;
+}
 
-			memset(g, 0, sizeof(*g));
-			g->index = index;
+void Group::QuickFree()
+{
+	DeleteName(this->string_id);
+}
 
-			return g;
-		}
-	}
-
-	/* Check if we can add a block to the pool */
-	return (AddBlockToPool(&_Group_pool)) ? AllocateGroup() : NULL;
+bool Group::IsValid() const
+{
+	return this->string_id != STR_NULL;
 }
 
 void InitializeGroup(void)
 {
-	CleanPool(&_Group_pool);
-	AddBlockToPool(&_Group_pool);
+	_Group_pool.CleanPool();
+	_Group_pool.AddBlockToPool();
 }
 
 
@@ -100,16 +94,21 @@
 	VehicleType vt = (VehicleType)p1;
 	if (!IsPlayerBuildableVehicleType(vt)) return CMD_ERROR;
 
-	Group *g = AllocateGroup();
+	AutoPtrT<Group> g_auto_delete;
+
+	Group *g = new Group(STR_EMPTY);
 	if (g == NULL) return CMD_ERROR;
 
+	g_auto_delete = g;
+
 	if (flags & DC_EXEC) {
 		g->owner = _current_player;
-		g->string_id = STR_EMPTY;
 		g->replace_protection = false;
 		g->vehicle_type = vt;
 
 		InvalidateWindowData(GetWCForVT(vt), (vt << 11) | VLW_GROUP_LIST | _current_player);
+
+		g_auto_delete.Detach();
 	}
 
 	return CommandCost();
@@ -153,7 +152,7 @@
 
 		/* Delete the Replace Vehicle Windows */
 		DeleteWindowById(WC_REPLACE_VEHICLE, g->vehicle_type);
-		DeleteGroup(g);
+		delete g;
 
 		InvalidateWindowData(GetWCForVT(vt), (vt << 11) | VLW_GROUP_LIST | _current_player);
 	}
@@ -359,7 +358,7 @@
  */
 void RemoveVehicleFromGroup(const Vehicle *v)
 {
-	if (!IsValidVehicle(v) || !(v->HasFront() && v->IsPrimaryVehicle())) return;
+	if (!v->IsValid() || !(v->HasFront() && v->IsPrimaryVehicle())) return;
 
 	if (!IsDefaultGroupID(v->group_id)) DecreaseGroupNumVehicle(v->group_id);
 }
@@ -375,7 +374,7 @@
 {
 	if (!IsValidGroupID(new_g) && !IsDefaultGroupID(new_g)) return;
 
-	assert(IsValidVehicle(v) && v->type == VEH_TRAIN && IsFrontEngine(v));
+	assert(v->IsValid() && v->type == VEH_TRAIN && IsFrontEngine(v));
 
 	for (Vehicle *u = v; u != NULL; u = u->next) {
 		if (IsEngineCountable(u)) UpdateNumEngineGroup(u->engine_type, u->group_id, new_g);
@@ -397,7 +396,7 @@
  */
 void UpdateTrainGroupID(Vehicle *v)
 {
-	assert(IsValidVehicle(v) && v->type == VEH_TRAIN && (IsFrontEngine(v) || IsFreeWagon(v)));
+	assert(v->IsValid() && v->type == VEH_TRAIN && (IsFrontEngine(v) || IsFreeWagon(v)));
 
 	GroupID new_g = IsFrontEngine(v) ? v->group_id : (GroupID)DEFAULT_GROUP;
 	for (Vehicle *u = v; u != NULL; u = u->next) {
@@ -416,7 +415,7 @@
 	Group *g;
 
 	FOR_ALL_GROUPS(g) {
-		if (p->index == g->owner) DeleteGroup(g);
+		if (p->index == g->owner) delete g;
 	}
 }
 
@@ -447,11 +446,7 @@
 	int index;
 
 	while ((index = SlIterateArray()) != -1) {
-		if (!AddBlockIfNeeded(&_Group_pool, index)) {
-			error("Groups: failed loading savegame: too many groups");
-		}
-
-		Group *g = GetGroup(index);
+		Group *g = new (index) Group();
 		SlObject(g, _group_desc);
 	}
 }
--- a/src/group_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/group_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -139,32 +139,32 @@
 
 static const Widget _group_widgets[] = {
 {   WWT_CLOSEBOX,   RESIZE_NONE,    14,     0,    10,     0,    13, STR_00C5,             STR_018B_CLOSE_WINDOW},
-{    WWT_CAPTION,  RESIZE_RIGHT,    14,    11,   513,     0,    13, 0x0,                  STR_018C_WINDOW_TITLE_DRAG_THIS},
-{  WWT_STICKYBOX,     RESIZE_LR,    14,   514,   525,     0,    13, 0x0,                  STR_STICKY_BUTTON},
+{    WWT_CAPTION,  RESIZE_RIGHT,    14,    11,   447,     0,    13, 0x0,                  STR_018C_WINDOW_TITLE_DRAG_THIS},
+{  WWT_STICKYBOX,     RESIZE_LR,    14,   448,   459,     0,    13, 0x0,                  STR_STICKY_BUTTON},
 {      WWT_PANEL,   RESIZE_NONE,    14,     0,   200,    14,    25, 0x0,                  STR_NULL},
 {      WWT_PANEL,   RESIZE_NONE,    14,     0,   200,    26,    38, 0x0,                  STR_NULL},
 {      WWT_PANEL,   RESIZE_NONE,    14,     0,   200,    39,    52, 0x0,                  STR_NULL},
-{     WWT_MATRIX, RESIZE_BOTTOM,    14,     0,   188,    52,   220, 0x701,                STR_GROUPS_CLICK_ON_GROUP_FOR_TIP},
-{  WWT_SCROLLBAR, RESIZE_BOTTOM,    14,   189,   200,    26,   220, 0x0,                  STR_0190_SCROLL_BAR_SCROLLS_LIST},
+{     WWT_MATRIX, RESIZE_BOTTOM,    14,     0,   188,    52,   168, 0x701,                STR_GROUPS_CLICK_ON_GROUP_FOR_TIP},
+{  WWT_SCROLLBAR, RESIZE_BOTTOM,    14,   189,   200,    26,   168, 0x0,                  STR_0190_SCROLL_BAR_SCROLLS_LIST},
 { WWT_PUSHTXTBTN,   RESIZE_NONE,    14,   201,   281,    14,    25, STR_SORT_BY,          STR_SORT_ORDER_TIP},
 {      WWT_PANEL,   RESIZE_NONE,    14,   282,   435,    14,    25, 0x0,                  STR_SORT_CRITERIA_TIP},
 {    WWT_TEXTBTN,   RESIZE_NONE,    14,   436,   447,    14,    25, STR_0225,             STR_SORT_CRITERIA_TIP},
-{      WWT_PANEL,  RESIZE_RIGHT,    14,   448,   525,    14,    25, 0x0,                  STR_NULL},
-{     WWT_MATRIX,     RESIZE_RB,    14,   201,   513,    26,   233, 0x701,                STR_NULL},
-{ WWT_SCROLL2BAR,    RESIZE_LRB,    14,   514,   525,    26,   233, 0x0,                  STR_0190_SCROLL_BAR_SCROLLS_LIST},
-{ WWT_PUSHIMGBTN,     RESIZE_TB,    14,     0,    23,   221,   245, 0x0,                  STR_GROUP_CREATE_TIP},
-{ WWT_PUSHIMGBTN,     RESIZE_TB,    14,    24,    47,   221,   245, 0x0,                  STR_GROUP_DELETE_TIP},
-{ WWT_PUSHIMGBTN,     RESIZE_TB,    14,    48,    71,   221,   245, 0x0,                  STR_GROUP_RENAME_TIP},
-{      WWT_PANEL,     RESIZE_TB,    14,    72,   164,   221,   245, 0x0,                  STR_NULL},
-{ WWT_PUSHIMGBTN,     RESIZE_TB,    14,   165,   188,   221,   245, 0x0,                  STR_GROUP_REPLACE_PROTECTION_TIP},
-{      WWT_PANEL,     RESIZE_TB,    14,   189,   200,   221,   245, 0x0,                  STR_NULL},
-{ WWT_PUSHTXTBTN,     RESIZE_TB,    14,   201,   306,   234,   245, 0x0,                  STR_AVAILABLE_ENGINES_TIP},
-{    WWT_TEXTBTN,     RESIZE_TB,    14,   307,   411,   234,   245, STR_MANAGE_LIST,      STR_MANAGE_LIST_TIP},
-{    WWT_TEXTBTN,     RESIZE_TB,    14,   412,   423,   234,   245, STR_0225,             STR_MANAGE_LIST_TIP},
-{ WWT_PUSHIMGBTN,     RESIZE_TB,    14,   424,   435,   234,   245, SPR_FLAG_VEH_STOPPED, STR_MASS_STOP_LIST_TIP},
-{ WWT_PUSHIMGBTN,     RESIZE_TB,    14,   436,   447,   234,   245, SPR_FLAG_VEH_RUNNING, STR_MASS_START_LIST_TIP},
-{      WWT_PANEL,    RESIZE_RTB,    14,   448,   513,   234,   245, 0x0,                  STR_NULL},
-{  WWT_RESIZEBOX,   RESIZE_LRTB,    14,   514,   525,   234,   245, 0x0,                  STR_RESIZE_BUTTON},
+{      WWT_PANEL,  RESIZE_RIGHT,    14,   448,   459,    14,    25, 0x0,                  STR_NULL},
+{     WWT_MATRIX,     RESIZE_RB,    14,   201,   447,    26,   181, 0x701,                STR_NULL},
+{ WWT_SCROLL2BAR,    RESIZE_LRB,    14,   448,   459,    26,   181, 0x0,                  STR_0190_SCROLL_BAR_SCROLLS_LIST},
+{ WWT_PUSHIMGBTN,     RESIZE_TB,    14,     0,    23,   169,   193, 0x0,                  STR_GROUP_CREATE_TIP},
+{ WWT_PUSHIMGBTN,     RESIZE_TB,    14,    24,    47,   169,   193, 0x0,                  STR_GROUP_DELETE_TIP},
+{ WWT_PUSHIMGBTN,     RESIZE_TB,    14,    48,    71,   169,   193, 0x0,                  STR_GROUP_RENAME_TIP},
+{      WWT_PANEL,     RESIZE_TB,    14,    72,   164,   169,   193, 0x0,                  STR_NULL},
+{ WWT_PUSHIMGBTN,     RESIZE_TB,    14,   165,   188,   169,   193, 0x0,                  STR_GROUP_REPLACE_PROTECTION_TIP},
+{      WWT_PANEL,     RESIZE_TB,    14,   189,   200,   169,   193, 0x0,                  STR_NULL},
+{ WWT_PUSHTXTBTN,     RESIZE_TB,    14,   201,   306,   182,   193, 0x0,                  STR_AVAILABLE_ENGINES_TIP},
+{    WWT_TEXTBTN,     RESIZE_TB,    14,   307,   411,   182,   193, STR_MANAGE_LIST,      STR_MANAGE_LIST_TIP},
+{    WWT_TEXTBTN,     RESIZE_TB,    14,   412,   423,   182,   193, STR_0225,             STR_MANAGE_LIST_TIP},
+{ WWT_PUSHIMGBTN,     RESIZE_TB,    14,   424,   435,   182,   193, SPR_FLAG_VEH_STOPPED, STR_MASS_STOP_LIST_TIP},
+{ WWT_PUSHIMGBTN,     RESIZE_TB,    14,   436,   447,   182,   193, SPR_FLAG_VEH_RUNNING, STR_MASS_START_LIST_TIP},
+{      WWT_PANEL,    RESIZE_RTB,    14,   448,   447,   182,   193, 0x0,                  STR_NULL},
+{  WWT_RESIZEBOX,   RESIZE_LRTB,    14,   448,   459,   182,   193, 0x0,                  STR_RESIZE_BUTTON},
 {   WIDGETS_END},
 };
 
@@ -176,15 +176,15 @@
 	grouplist_d *gl = &WP(w, groupveh_d).gl;
 
 	w->caption_color = owner;
-	w->hscroll.cap = 10 * 29;
+	w->hscroll.cap = 224;
 	w->resize.step_width = 1;
 
 	switch (gv->vehicle_type) {
 		default: NOT_REACHED();
 		case VEH_TRAIN:
 		case VEH_ROAD:
-			w->vscroll.cap = 13;
-			w->vscroll2.cap = 8;
+			w->vscroll.cap = 9;
+			w->vscroll2.cap = 6;
 			w->resize.step_height = PLY_WND_PRC__SIZE_OF_ROW_SMALL;
 			break;
 		case VEH_SHIP:
@@ -557,7 +557,7 @@
 
 					gv->vehicle_sel = v->index;
 
-					if (IsValidVehicle(v)) {
+					if (v->IsValid()) {
 						SetObjectToPlaceWnd(v->GetImage(DIR_W), GetVehiclePalette(v), 4, w);
 					}
 
@@ -771,7 +771,7 @@
 
 
 static const WindowDesc _group_desc = {
-	WDP_AUTO, WDP_AUTO, 526, 246,
+	WDP_AUTO, WDP_AUTO, 460, 194, 526, 246,
 	WC_TRAINS_LIST, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_group_widgets,
@@ -796,23 +796,4 @@
 	if (w == NULL) return;
 
 	w->window_class = wc;
-
-	switch (vehicle_type) {
-		default: NOT_REACHED();
-		case VEH_ROAD:
-			ResizeWindow(w, -66,   0);
-			/* FALL THROUGH */
-		case VEH_TRAIN:
-			w->resize.height = w->height - (PLY_WND_PRC__SIZE_OF_ROW_SMALL * 4); // Minimum of 4 vehicles
-			break;
-
-		case VEH_SHIP:
-		case VEH_AIRCRAFT:
-			ResizeWindow(w, -66, -52);
-			w->resize.height = w->height;  // Minimum of 4 vehicles
-			break;
-	}
-
-	/* Set the minimum window size to the current window size */
-	w->resize.width = w->width;
 }
--- a/src/industry.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/industry.h	Fri Aug 03 18:10:15 2007 +0000
@@ -86,10 +86,13 @@
 
 DECLARE_ENUM_AS_BIT_SET(IndustyBehaviour);
 
+struct Industry;
+DECLARE_OLD_POOL(Industry, Industry, 3, 8000)
+
 /**
  * Defines the internal data of a functionnal industry
  */
-struct Industry {
+struct Industry : PoolItem<Industry, IndustryID, &_Industry_pool> {
 	TileIndex xy;                       ///< coordinates of the primary tile the industry is built one
 	byte width;
 	byte height;
@@ -105,18 +108,21 @@
 	uint16 last_month_transported[2];   ///< total units transported per cargo in the last full month
 	uint16 counter;                     ///< used for animation and/or production (if available cargo)
 
-	IndustryType type;                  ///< type of industry. see IT_COAL_MINE and others
+	IndustryType type;                  ///< type of industry.
 	OwnerByte owner;                    ///< owner of the industry.  Which SHOULD always be (imho) OWNER_NONE
 	byte random_color;                  ///< randomized colour of the industry, for display purpose
 	Year last_prod_year;                ///< last year of production
 	byte was_cargo_delivered;           ///< flag that indicate this has been the closest industry chosen for cargo delivery by a station. see DeliverGoodsToIndustry
 
-	IndustryID index;                   ///< index of the industry in the pool of industries
-
 	OwnerByte founder;                  ///< Founder of the industry
 	Date construction_date;             ///< Date of the construction of the industry
 	uint8 construction_type;            ///< Way the industry was constructed (@see IndustryConstructionType)
 	Date last_cargo_accepted_at;        ///< Last day cargo was accepted by this industry
+
+	Industry(TileIndex tile = 0) : xy(tile) {}
+	~Industry();
+
+	bool IsValid() const { return this->xy != 0; }
 };
 
 struct IndustryTileTable {
@@ -205,7 +211,7 @@
 
 /* industry_cmd.cpp*/
 const IndustrySpec *GetIndustrySpec(IndustryType thistype);    ///< Array of industries data
-const IndustryTileSpec *GetIndustryTileSpec(IndustryGfx gfx);  ///< Array of industry tiles data
+const IndustryTileSpec *GetIndustryTileSpec(IndustryGfx gfx, bool full_check = true);  ///< Array of industry tiles data
 void ResetIndustries();
 void PlantRandomFarmField(const Industry *i);
 
@@ -216,18 +222,6 @@
 /* smallmap_gui.cpp */
 void BuildIndustriesLegend();
 
-DECLARE_OLD_POOL(Industry, Industry, 3, 8000)
-
-/**
- * Check if an Industry really exists.
- * @param industry to check
- * @return true if position is a valid one
- */
-static inline bool IsValidIndustry(const Industry *industry)
-{
-	return industry->xy != 0;
-}
-
 /**
  * Check if an Industry exists whithin the pool of industries
  * @param index of the desired industry
@@ -235,7 +229,7 @@
  */
 static inline bool IsValidIndustryID(IndustryID index)
 {
-	return index < GetIndustryPoolSize() && IsValidIndustry(GetIndustry(index));
+	return index < GetIndustryPoolSize() && GetIndustry(index)->IsValid();
 }
 
 
@@ -318,60 +312,12 @@
 	return GetIndustry(index);
 }
 
-void DestroyIndustry(Industry *i);
-
-static inline void DeleteIndustry(Industry *i)
-{
-	DestroyIndustry(i);
-	i->xy = 0;
-}
-
-#define FOR_ALL_INDUSTRIES_FROM(i, start) for (i = GetIndustry(start); i != NULL; i = (i->index + 1U < GetIndustryPoolSize()) ? GetIndustry(i->index + 1U) : NULL) if (IsValidIndustry(i))
+#define FOR_ALL_INDUSTRIES_FROM(i, start) for (i = GetIndustry(start); i != NULL; i = (i->index + 1U < GetIndustryPoolSize()) ? GetIndustry(i->index + 1U) : NULL) if (i->IsValid())
 #define FOR_ALL_INDUSTRIES(i) FOR_ALL_INDUSTRIES_FROM(i, 0)
 
 extern const Industry **_industry_sort;
 extern bool _industry_sort_dirty;
 
-enum {
-	IT_COAL_MINE           =   0,
-	IT_POWER_STATION       =   1,
-	IT_SAWMILL             =   2,
-	IT_FOREST              =   3,
-	IT_OIL_REFINERY        =   4,
-	IT_OIL_RIG             =   5,
-	IT_FACTORY             =   6,
-	IT_PRINTING_WORKS      =   7,
-	IT_STEEL_MILL          =   8,
-	IT_FARM                =   9,
-	IT_COPPER_MINE         =  10,
-	IT_OIL_WELL            =  11,
-	IT_BANK_TEMP           =  12,
-	IT_FOOD_PROCESS        =  13,
-	IT_PAPER_MILL          =  14,
-	IT_GOLD_MINE           =  15,
-	IT_BANK_TROPIC_ARCTIC  =  16,
-	IT_DIAMOND_MINE        =  17,
-	IT_IRON_MINE           =  18,
-	IT_FRUIT_PLANTATION    =  19,
-	IT_RUBBER_PLANTATION   =  20,
-	IT_WATER_SUPPLY        =  21,
-	IT_WATER_TOWER         =  22,
-	IT_FACTORY_2           =  23,
-	IT_FARM_2              =  24,
-	IT_LUMBER_MILL         =  25,
-	IT_COTTON_CANDY        =  26,
-	IT_CANDY_FACTORY       =  27,
-	IT_BATTERY_FARM        =  28,
-	IT_COLA_WELLS          =  29,
-	IT_TOY_SHOP            =  30,
-	IT_TOY_FACTORY         =  31,
-	IT_PLASTIC_FOUNTAINS   =  32,
-	IT_FIZZY_DRINK_FACTORY =  33,
-	IT_BUBBLE_GENERATOR    =  34,
-	IT_TOFFEE_QUARRY       =  35,
-	IT_SUGAR_MINE          =  36,
-	IT_END,
-	IT_INVALID             = 255,
-};
+static const uint8 IT_INVALID = 255;
 
 #endif /* INDUSTRY_H */
--- a/src/industry_cmd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/industry_cmd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -35,6 +35,7 @@
 #include "newgrf_industries.h"
 #include "newgrf_industrytiles.h"
 #include "newgrf_callbacks.h"
+#include "misc/autoptr.hpp"
 
 void ShowIndustryViewWindow(int industry);
 void BuildOilRig(TileIndex tile);
@@ -75,19 +76,7 @@
 	_industry_specs[type].appear_creation[_opt.landscape] = 0;
 }
 
-/**
- * Called if a new block is added to the industry-pool
- */
-static void IndustryPoolNewBlock(uint start_item)
-{
-	Industry *i;
-
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (i = GetIndustry(start_item); i != NULL; i = (i->index + 1U < GetIndustryPoolSize()) ? GetIndustry(i->index + 1U) : NULL) i->index = start_item++;
-}
-
-DEFINE_OLD_POOL(Industry, Industry, IndustryPoolNewBlock, NULL)
+DEFINE_OLD_POOL_GENERIC(Industry, Industry)
 
 /**
  * Retrieve the type for this industry.  Although it is accessed by a tile,
@@ -102,7 +91,7 @@
 	assert(IsTileType(tile, MP_INDUSTRY));
 
 	const Industry *ind = GetIndustryByTile(tile);
-	return IsValidIndustry(ind) ? ind->type : (IndustryType)IT_INVALID;
+	return ind->IsValid() ? ind->type : (IndustryType)IT_INVALID;
 }
 
 /**
@@ -124,44 +113,58 @@
  * This will ensure at once : proper access and
  * not allowing modifications of it.
  * @param gfx of industrytile (which is the index in _industry_tile_specs)
+ * @param full_check (default to true) verify if an override is available.
+ *  If so, use it instead of the gfx provided.
  * @pre gfx < INVALID_INDUSTRYTILE
  * @return a pointer to the corresponding industrytile spec
  **/
-const IndustryTileSpec *GetIndustryTileSpec(IndustryGfx gfx)
+const IndustryTileSpec *GetIndustryTileSpec(IndustryGfx gfx, bool full_check)
 {
 	assert(gfx < INVALID_INDUSTRYTILE);
-	return &_industry_tile_specs[gfx];
+	const IndustryTileSpec *its = &_industry_tile_specs[gfx];
+	if (full_check && its->grf_prop.override != INVALID_INDUSTRYTILE) {
+		its = &_industry_tile_specs[its->grf_prop.override];
+	}
+	return its;
 }
 
-void DestroyIndustry(Industry *i)
+Industry::~Industry()
 {
-	BEGIN_TILE_LOOP(tile_cur, i->width, i->height, i->xy);
+	/* Industry can also be destroyed when not fully initialized.
+	 * This means that we do not have to clear tiles either. */
+	if (this->width == 0) {
+		this->xy = 0;
+		return;
+	}
+
+	BEGIN_TILE_LOOP(tile_cur, this->width, this->height, this->xy);
 		if (IsTileType(tile_cur, MP_INDUSTRY)) {
-			if (GetIndustryIndex(tile_cur) == i->index) {
+			if (GetIndustryIndex(tile_cur) == this->index) {
 				DoClearSquare(tile_cur);
 			}
 		} else if (IsTileType(tile_cur, MP_STATION) && IsOilRig(tile_cur)) {
 			DeleteOilRig(tile_cur);
 		}
-	END_TILE_LOOP(tile_cur, i->width, i->height, i->xy);
+	END_TILE_LOOP(tile_cur, this->width, this->height, this->xy);
 
-	if (GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_PLANT_FIELDS) {
+	if (GetIndustrySpec(this->type)->behaviour & INDUSTRYBEH_PLANT_FIELDS) {
 		/* Remove the farmland and convert it to regular tiles over time. */
-		BEGIN_TILE_LOOP(tile_cur, 42, 42, i->xy - TileDiffXY(21, 21)) {
+		BEGIN_TILE_LOOP(tile_cur, 42, 42, this->xy - TileDiffXY(21, 21)) {
 			tile_cur = TILE_MASK(tile_cur);
 			if (IsTileType(tile_cur, MP_CLEAR) && IsClearGround(tile_cur, CLEAR_FIELDS) &&
-					GetIndustryIndexOfField(tile_cur) == i->index) {
+					GetIndustryIndexOfField(tile_cur) == this->index) {
 				SetIndustryIndexOfField(tile_cur, INVALID_INDUSTRY);
 			}
-		} END_TILE_LOOP(tile_cur, 42, 42, i->xy - TileDiff(21, 21))
+		} END_TILE_LOOP(tile_cur, 42, 42, this->xy - TileDiff(21, 21))
 	}
 
 	_industry_sort_dirty = true;
-	DecIndustryTypeCount(i->type);
+	DecIndustryTypeCount(this->type);
 
-	DeleteSubsidyWithIndustry(i->index);
-	DeleteWindowById(WC_INDUSTRY_VIEW, i->index);
+	DeleteSubsidyWithIndustry(this->index);
+	DeleteWindowById(WC_INDUSTRY_VIEW, this->index);
 	InvalidateWindow(WC_INDUSTRY_DIRECTORY, 0);
+	this->xy = 0;
 }
 
 static void IndustryDrawSugarMine(const TileInfo *ti)
@@ -255,7 +258,6 @@
 	Industry *ind = GetIndustryByTile(ti->tile);
 	const IndustryTileSpec *indts = GetIndustryTileSpec(gfx);
 	const DrawBuildingsTileStruct *dits;
-	byte z;
 	SpriteID image;
 	SpriteID pal;
 
@@ -287,34 +289,23 @@
 		pal = dits->ground.pal;
 	}
 
-	z = ti->z;
-	/* Add bricks below the industry? */
-	if (ti->tileh != SLOPE_FLAT) {
-		DrawFoundation(ti, ti->tileh);
-		z += TILE_HEIGHT;
-	}
+	/* DrawFoundation() modifes ti->z and ti->tileh */
+	if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
 
 	DrawGroundSprite(image, pal);
 
 	/* Add industry on top of the ground? */
 	image = dits->building.sprite;
 	if (image != 0) {
-		if (HASBIT(_transparent_opt, TO_INDUSTRIES)) {
-			SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
-			pal = PALETTE_TO_TRANSPARENT;
-		} else if (HASBIT(image, PALETTE_MODIFIER_COLOR) && dits->building.pal == PAL_NONE) {
-			pal = GENERAL_SPRITE_COLOR(ind->random_color);
-		} else {
-			pal = dits->building.pal;
-		}
-
-		AddSortableSpriteToDraw(image, pal,
+		AddSortableSpriteToDraw(image,
+			(HASBIT(image, PALETTE_MODIFIER_COLOR) && dits->building.pal == PAL_NONE) ? GENERAL_SPRITE_COLOR(ind->random_color) : dits->building.pal,
 			ti->x + dits->subtile_x,
 			ti->y + dits->subtile_y,
 			dits->width  + 1,
 			dits->height + 1,
 			dits->dz,
-			z);
+			ti->z,
+			HASBIT(_transparent_opt, TO_INDUSTRIES));
 
 		if (HASBIT(_transparent_opt, TO_INDUSTRIES)) return;
 	}
@@ -330,9 +321,9 @@
 	return GetTileMaxZ(tile);
 }
 
-static Slope GetSlopeTileh_Industry(TileIndex tile, Slope tileh)
+static Foundation GetFoundation_Industry(TileIndex tile, Slope tileh)
 {
-	return SLOPE_FLAT;
+	return FlatteningFoundation(tileh);
 }
 
 static void GetAcceptedCargo_Industry(TileIndex tile, AcceptedCargo ac)
@@ -399,7 +390,7 @@
 		return_cmd_error(STR_4800_IN_THE_WAY);
 	}
 
-	if (flags & DC_EXEC) DeleteIndustry(i);
+	if (flags & DC_EXEC) delete i;
 	return CommandCost();
 }
 
@@ -703,7 +694,7 @@
 		EV_BUBBLE
 	);
 
-	if (v != NULL) v->u.special.unk2 = dir;
+	if (v != NULL) v->u.special.animation_substate = dir;
 }
 
 static void TileLoop_Industry(TileIndex tile)
@@ -1403,27 +1394,6 @@
 	return true;
 }
 
-static Industry *AllocateIndustry()
-{
-	Industry *i;
-
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (i = GetIndustry(0); i != NULL; i = (i->index + 1U < GetIndustryPoolSize()) ? GetIndustry(i->index + 1U) : NULL) {
-		IndustryID index = i->index;
-
-		if (IsValidIndustry(i)) continue;
-
-		memset(i, 0, sizeof(*i));
-		i->index = index;
-
-		return i;
-	}
-
-	/* Check if we can add a block to the pool */
-	return AddBlockToPool(&_Industry_pool) ? AllocateIndustry() : NULL;
-}
-
 static void DoCreateNewIndustry(Industry *i, TileIndex tile, int type, const IndustryTileTable *it, const Town *t, Owner owner)
 {
 	const IndustrySpec *indspec = GetIndustrySpec(type);
@@ -1536,12 +1506,14 @@
 	if (!CheckIfIndustryIsAllowed(tile, type, t)) return NULL;
 	if (!CheckSuitableIndustryPos(tile)) return NULL;
 
-	Industry *i = AllocateIndustry();
+	Industry *i = new Industry(tile);
 	if (i == NULL) return NULL;
+	AutoPtrT<Industry> i_auto_delete = i;
 
 	if (flags & DC_EXEC) {
 		if (!custom_shape_check) CheckIfCanLevelIndustryPlatform(tile, DC_EXEC, it, type);
 		DoCreateNewIndustry(i, tile, type, it, t, OWNER_NONE);
+		i_auto_delete.Detach();
 	}
 
 	return i;
@@ -1618,7 +1590,12 @@
 	return CreateNewIndustryHelper(tile, type, DC_EXEC, indspec, RandomRange(indspec->num_table));
 }
 
-static const byte _numof_industry_table[5][11] = {
+enum {
+	NB_NUMOFINDUSTRY = 11,
+	NB_DIFFICULTY_LEVEL = 5,
+};
+
+static const byte _numof_industry_table[NB_DIFFICULTY_LEVEL][NB_NUMOFINDUSTRY] = {
 	/* difficulty settings for number of industries */
 	{0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0},   //none
 	{0, 1, 1, 1, 1, 1, 1, 1,  1,  1,  1},   //very low
@@ -1633,7 +1610,9 @@
  * @param amount of industries that need to be built */
 static void PlaceInitialIndustry(IndustryType type, int amount)
 {
-	int num = _numof_industry_table[_opt.diff.number_industries][amount];
+	/* We need to bypass the amount given in parameter if it exceeds the maximum dimension of the
+	 * _numof_industry_table.  newgrf can specify a big amount */
+	int num = (amount > NB_NUMOFINDUSTRY) ? amount : _numof_industry_table[_opt.diff.number_industries][amount];
 	const IndustrySpec *ind_spc = GetIndustrySpec(type);
 
 	/* These are always placed next to the coastline, so we scale by the perimeter instead. */
@@ -1669,7 +1648,7 @@
 
 	/* Find the total amount of industries */
 	if (_opt.diff.number_industries > 0) {
-		for (it = IT_COAL_MINE; it < NUM_INDUSTRYTYPES; it++) {
+		for (it = 0; it < NUM_INDUSTRYTYPES; it++) {
 
 			ind_spc = GetIndustrySpec(it);
 
@@ -1682,7 +1661,7 @@
 				/* once the chance of appearance is determind, it have to be scaled by
 				 * the difficulty level. The "chance" in question is more an index into
 				 * the _numof_industry_table,in fact */
-				int num = (chance < 11) ? chance : _numof_industry_table[_opt.diff.number_industries][chance];
+				int num = (chance > NB_NUMOFINDUSTRY) ? chance : _numof_industry_table[_opt.diff.number_industries][chance];
 
 				/* These are always placed next to the coastline, so we scale by the perimeter instead. */
 				num = (ind_spc->check_proc == CHECK_REFINERY || ind_spc->check_proc == CHECK_OIL_RIG) ? ScaleByMapSize1D(num) : ScaleByMapSize(num);
@@ -1694,7 +1673,7 @@
 	SetGeneratingWorldProgress(GWP_INDUSTRY, i);
 
 	if (_opt.diff.number_industries > 0) {
-		for (it = IT_COAL_MINE; it < NUM_INDUSTRYTYPES; it++) {
+		for (it = 0; it < NUM_INDUSTRYTYPES; it++) {
 			/* Once the number of industries has been determined, let's really create them.
 			 * The test for chance allows us to try create industries that are available only
 			 * for this landscape.
@@ -1807,7 +1786,7 @@
 		InvalidateWindow(WC_INDUSTRY_VIEW, i->index);
 
 	if (i->prod_level == 0) {
-		DeleteIndustry(i);
+		delete i;
 	} else if (_patches.smooth_economy) {
 		ExtChangeIndustryProduction(i);
 	}
@@ -2002,7 +1981,7 @@
 	ChangeTileOwner_Industry,    /* change_tile_owner_proc */
 	GetProducedCargo_Industry,   /* get_produced_cargo_proc */
 	NULL,                        /* vehicle_enter_tile_proc */
-	GetSlopeTileh_Industry,      /* get_slope_tileh_proc */
+	GetFoundation_Industry,      /* get_foundation_proc */
 };
 
 static const SaveLoad _industry_desc[] = {
@@ -2092,12 +2071,7 @@
 	ResetIndustryCounts();
 
 	while ((index = SlIterateArray()) != -1) {
-		Industry *i;
-
-		if (!AddBlockIfNeeded(&_Industry_pool, index))
-			error("Industries: failed loading savegame: too many industries");
-
-		i = GetIndustry(index);
+		Industry *i = new (index) Industry();
 		SlObject(i, _industry_desc);
 		IncIndustryTypeCount(i->type);
 	}
--- a/src/industry_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/industry_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -114,7 +114,7 @@
 
 			/* We'll perform two distinct loops, one for secondary industries, and the other one for
 			 * primary ones. Each loop will fill the _fund_gui structure. */
-			for (ind = IT_COAL_MINE; ind < NUM_INDUSTRYTYPES; ind++) {
+			for (ind = 0; ind < NUM_INDUSTRYTYPES; ind++) {
 				indsp = GetIndustrySpec(ind);
 				if (indsp->enabled && (!indsp->IsRawIndustry() || _game_mode == GM_EDITOR)) {
 					_fund_gui.index[_fund_gui.count] = ind;
@@ -124,7 +124,7 @@
 			}
 
 			if (_patches.raw_industry_construction != 0 && _game_mode != GM_EDITOR) {
-				for (ind = IT_COAL_MINE; ind < NUM_INDUSTRYTYPES; ind++) {
+				for (ind = 0; ind < NUM_INDUSTRYTYPES; ind++) {
 					indsp = GetIndustrySpec(ind);
 					if (indsp->enabled && indsp->IsRawIndustry()) {
 						_fund_gui.index[_fund_gui.count] = ind;
@@ -363,7 +363,7 @@
 };
 
 static const WindowDesc _build_industry_dynamic_desc = {
-	WDP_AUTO, WDP_AUTO, 170, 212,
+	WDP_AUTO, WDP_AUTO, 170, 212, 170, 212,
 	WC_BUILD_INDUSTRY, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_RESIZABLE,
 	_build_dynamic_industry_widgets,
@@ -598,7 +598,7 @@
 };
 
 static const WindowDesc _industry_view_desc = {
-	WDP_AUTO, WDP_AUTO, 260, 160,
+	WDP_AUTO, WDP_AUTO, 260, 160, 260, 160,
 	WC_INDUSTRY_VIEW, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON,
 	_industry_view_widgets,
@@ -855,7 +855,7 @@
 
 /* Industry List */
 static const WindowDesc _industry_directory_desc = {
-	WDP_AUTO, WDP_AUTO, 508, 190,
+	WDP_AUTO, WDP_AUTO, 508, 190, 508, 190,
 	WC_INDUSTRY_DIRECTORY, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_industry_directory_widgets,
--- a/src/industry_map.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/industry_map.h	Fri Aug 03 18:10:15 2007 +0000
@@ -68,7 +68,7 @@
  * @pre IsTileType(t, MP_INDUSTRY)
  * @return the industry
  */
-static inline Industry* GetIndustryByTile(TileIndex t)
+static inline Industry *GetIndustryByTile(TileIndex t)
 {
 	return GetIndustry(GetIndustryIndex(t));
 }
--- a/src/intro_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/intro_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -99,7 +99,7 @@
 }
 
 static const WindowDesc _select_game_desc = {
-	WDP_CENTER, WDP_CENTER, 336, 195,
+	WDP_CENTER, WDP_CENTER, 336, 195, 336, 195,
 	WC_SELECT_GAME, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_select_game_widgets,
--- a/src/landscape.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/landscape.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -56,13 +56,51 @@
 	0, 0, 0, 0, 0, 0, 0, 16, 0, 0,  0, 17,  0, 15, 18, 0,
 };
 
-const Slope _inclined_tileh[] = {
-	SLOPE_SW,  SLOPE_NW,  SLOPE_SW,  SLOPE_SE, SLOPE_NE, SLOPE_SE, SLOPE_NE, SLOPE_NW,
-	SLOPE_E,   SLOPE_N,   SLOPE_W,   SLOPE_S,
-	SLOPE_NWS, SLOPE_WSE, SLOPE_SEN, SLOPE_ENW
-};
+SnowLine *_snow_line = NULL;
 
-SnowLine *_snow_line = NULL;
+/**
+ * Applys a foundation to a slope.
+ *
+ * @pre      Foundation and slope must be valid combined.
+ * @param f  The #Foundation.
+ * @param s  The #Slope to modify.
+ * @return   Increment to the tile Z coordinate.
+ */
+uint ApplyFoundationToSlope(Foundation f, Slope *s)
+{
+
+	if (!IsFoundation(f)) return 0;
+
+	if (IsLeveledFoundation(f)) {
+		*s = SLOPE_FLAT;
+		return TILE_HEIGHT;
+	}
+
+	uint dz = IsSteepSlope(*s) ? TILE_HEIGHT : 0;
+	byte highest_corner = GetHighestSlopeCorner(*s);
+
+	switch (f) {
+		case FOUNDATION_INCLINED_X:
+			*s = (highest_corner <= 1 ? SLOPE_SW : SLOPE_NE);
+			break;
+
+		case FOUNDATION_INCLINED_Y:
+			*s = (((highest_corner == 1) || (highest_corner == 2)) ? SLOPE_SE : SLOPE_NW);
+			break;
+
+		case FOUNDATION_STEEP_LOWER:
+			*s = (Slope) (1 << highest_corner);
+			break;
+
+		case FOUNDATION_STEEP_HIGHER:
+			*s = (Slope) (*s & ~SLOPE_STEEP);
+			break;
+
+		default: NOT_REACHED();
+	}
+	return dz;
+}
+
 
 uint GetPartialZ(int x, int y, Slope corners)
 {
@@ -152,7 +190,7 @@
 		break;
 
 	case SLOPE_STEEP_E:
-		z = 1 + (((x ^ 0xF) + (y ^ 0xF)) >> 1);
+		z = 1 + (((x ^ 0xF) + y) >> 1);
 		break;
 
 		default: break;
@@ -172,11 +210,9 @@
 static Slope GetFoundationSlope(TileIndex tile, uint* z)
 {
 	Slope tileh = GetTileSlope(tile, z);
-	Slope slope = _tile_type_procs[GetTileType(tile)]->get_slope_tileh_proc(tile, tileh);
-
-	/* Flatter slope -> higher base height */
-	if (slope < tileh) *z += TILE_HEIGHT;
-	return slope;
+	Foundation f = _tile_type_procs[GetTileType(tile)]->get_foundation_proc(tile, tileh);
+	*z += ApplyFoundationToSlope(f, &tileh);
+	return tileh;
 }
 
 
@@ -212,34 +248,43 @@
 }
 
 
-void DrawFoundation(TileInfo *ti, uint f)
+void DrawFoundation(TileInfo *ti, Foundation f)
 {
-	SpriteID sprite_base = SPR_SLOPES_BASE - 15;
-	Slope slope;
+	if (!IsFoundation(f)) return;
+
+	SpriteID sprite_base = SPR_SLOPES_VIRTUAL_BASE;
 	uint z;
+	Slope slope = GetFoundationSlope(ti->tile, &z);
 
-	slope = GetFoundationSlope(ti->tile, &z);
-	if (!HasFoundationNW(ti->tile, slope, z)) sprite_base += 22;
-	if (!HasFoundationNE(ti->tile, slope, z)) sprite_base += 44;
+	if (!HasFoundationNW(ti->tile, slope, z)) sprite_base += SPR_SLOPES_NO_FOUNDATION_NW_OFFSET;
+	if (!HasFoundationNE(ti->tile, slope, z)) sprite_base += SPR_SLOPES_NO_FOUNDATION_NE_OFFSET;
 
 	if (IsSteepSlope(ti->tileh)) {
 		SpriteID lower_base;
 
-		/* Lower part of foundation */
+		/* Lower part of foundation
+		 * Use the original slope sprites if NW and NE borders should be visible
+		 */
 		lower_base = sprite_base;
-		if (lower_base == SPR_SLOPES_BASE - 15) lower_base = SPR_FOUNDATION_BASE;
+		if (lower_base == SPR_SLOPES_VIRTUAL_BASE) lower_base = SPR_FOUNDATION_BASE;
 		AddSortableSpriteToDraw(
 			lower_base + (ti->tileh & ~SLOPE_STEEP), PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z
 		);
-		ti->z += TILE_HEIGHT;
-		ti->tileh = _inclined_tileh[f - 15];
-		if (f < 15 + 8) {
-			/* inclined */
-			AddSortableSpriteToDraw(sprite_base + f, PAL_NONE, ti->x, ti->y, 16, 16, 1, ti->z);
+
+		byte highest_corner = GetHighestSlopeCorner(ti->tileh);
+		ti->z += ApplyFoundationToSlope(f, &ti->tileh);
+
+		if (IsInclinedFoundation(f)) {
+			/* inclined foundation */
+			byte inclined = highest_corner * 2 + (f == FOUNDATION_INCLINED_Y ? 1 : 0);
+
+			AddSortableSpriteToDraw(sprite_base + SPR_SLOPES_INCLINED_OFFSET + inclined, PAL_NONE, ti->x, ti->y, 16, 16, 1, ti->z);
 			OffsetGroundSprite(31, 9);
-		} else if (f >= 15 + 8 + 4) {
-			/* three corners raised */
-			SpriteID upper = sprite_base + 15 + (f - 15 - 8 - 4) * 2;
+		} else if (f >= FOUNDATION_STEEP_HIGHER) {
+			/* three corners raised:
+			 * Draw inclined foundations for both axes, that results in the needed image.
+			 */
+			SpriteID upper = sprite_base + SPR_SLOPES_INCLINED_OFFSET + highest_corner * 2;
 
 			AddSortableSpriteToDraw(upper, PAL_NONE, ti->x, ti->y, 16, 16, 1, ti->z);
 			AddChildSpriteScreen(upper + 1, PAL_NONE, 31, 9);
@@ -249,21 +294,22 @@
 			OffsetGroundSprite(31, 1);
 		}
 	} else {
-		if (f < 15) {
+		if (IsLeveledFoundation(f)) {
 			/* leveled foundation
-			 * Use the original slope sprites if NW and NE borders should be visible */
-			if (sprite_base == SPR_SLOPES_BASE - 15) sprite_base = SPR_FOUNDATION_BASE;
+			 * Use the original slope sprites if NW and NE borders should be visible
+			 */
+			if (sprite_base == SPR_SLOPES_VIRTUAL_BASE) sprite_base = SPR_FOUNDATION_BASE;
 
-			AddSortableSpriteToDraw(sprite_base + f, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
-			ti->z += TILE_HEIGHT;
-			ti->tileh = SLOPE_FLAT;
+			AddSortableSpriteToDraw(sprite_base + ti->tileh, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
 			OffsetGroundSprite(31, 1);
 		} else {
 			/* inclined foundation */
-			AddSortableSpriteToDraw(sprite_base + f, PAL_NONE, ti->x, ti->y, 16, 16, 1, ti->z);
-			ti->tileh = _inclined_tileh[f - 15];
+			byte inclined = GetHighestSlopeCorner(ti->tileh) * 2 + (f == FOUNDATION_INCLINED_Y ? 1 : 0);
+
+			AddSortableSpriteToDraw(sprite_base + SPR_SLOPES_INCLINED_OFFSET + inclined, PAL_NONE, ti->x, ti->y, 16, 16, 1, ti->z);
 			OffsetGroundSprite(31, 9);
 		}
+		ti->z += ApplyFoundationToSlope(f, &ti->tileh);
 	}
 }
 
--- a/src/landscape.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/landscape.h	Fri Aug 03 18:10:15 2007 +0000
@@ -39,7 +39,8 @@
 	return RemapCoords(x, y, GetSlopeZ(x, y));
 }
 
-void DrawFoundation(TileInfo *ti, uint f);
+uint ApplyFoundationToSlope(Foundation f, Slope *s);
+void DrawFoundation(TileInfo *ti, Foundation f);
 
 void DoClearSquare(TileIndex tile);
 void RunTileLoop();
--- a/src/lang/catalan.txt	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/lang/catalan.txt	Fri Aug 03 18:10:15 2007 +0000
@@ -603,7 +603,7 @@
 STR_MESSAGES_ALL                                                :{YELLOW}Adjust per tots els tipus de missatge (actiu/inactiu/resum)
 STR_MESSAGE_SOUND                                               :{YELLOW}Emetre so per als nous missatges resumits
 STR_0210_TOO_FAR_FROM_PREVIOUS_DESTINATIO                       :{WHITE}...massa lluny del destí previ
-STR_0211_TOP_COMPANIES_WHO_REACHED                              :{BIGFONT}{BLACK}Principals Empreses en asolir el Nivell {NUM}{}({STRING} )
+STR_0211_TOP_COMPANIES_WHO_REACHED                              :{BIGFONT}{BLACK}Principals empreses en aconseguir el Nivell {NUM}{}({STRING} )
 STR_TOP_COMPANIES_NETWORK_GAME                                  :{BIGFONT}{BLACK}Taula de Lliga d'Empreses a {NUM}
 STR_0212                                                        :{BIGFONT}{COMMA}.
 STR_0213_BUSINESSMAN                                            :Empresari
@@ -2372,29 +2372,29 @@
 STR_8019_T_I_M_ELECTRIC                                         :'T.I.M.' (Elèctric)
 STR_801A_ASIASTAR_ELECTRIC                                      :'AsiaStar' (Elèctric)
 STR_801B_PASSENGER_CAR                                          :Vagó per Passatgers
-STR_801C_MAIL_VAN                                               :Furgó per Correu
+STR_801C_MAIL_VAN                                               :Vagó per Correu
 STR_801D_COAL_CAR                                               :Vagó per Carbó
 STR_801E_OIL_TANKER                                             :Tanc de Petroli
-STR_801F_LIVESTOCK_VAN                                          :Furgó per Bestiar
-STR_8020_GOODS_VAN                                              :Furgó de Mercaderies
-STR_8021_GRAIN_HOPPER                                           :Furgó per Gra
+STR_801F_LIVESTOCK_VAN                                          :Vagó per Bestiar
+STR_8020_GOODS_VAN                                              :Vagó de Mercaderies
+STR_8021_GRAIN_HOPPER                                           :Vagó per Gra
 STR_8022_WOOD_TRUCK                                             :Vagó per Fusta
 STR_8023_IRON_ORE_HOPPER                                        :Vagó per Mineral de Ferro
 STR_8024_STEEL_TRUCK                                            :Vagó per Acer
-STR_8025_ARMORED_VAN                                            :Furgó Blindat
-STR_8026_FOOD_VAN                                               :Furgó per Queviures
+STR_8025_ARMORED_VAN                                            :Vagó Blindat
+STR_8026_FOOD_VAN                                               :Vagó per Queviures
 STR_8027_PAPER_TRUCK                                            :Vagó per Paper
-STR_8028_COPPER_ORE_HOPPER                                      :Furgó per Mineral de Coure
+STR_8028_COPPER_ORE_HOPPER                                      :Vagó per Mineral de Coure
 STR_8029_WATER_TANKER                                           :Tanc d'Aigua
 STR_802A_FRUIT_TRUCK                                            :Vagó per Fruita
 STR_802B_RUBBER_TRUCK                                           :Vagó per Cautxú
 STR_802C_SUGAR_TRUCK                                            :Vagó per Sucre
-STR_802D_COTTON_CANDY_HOPPER                                    :Furgó per Cotó de Sucre
-STR_802E_TOFFEE_HOPPER                                          :Furgó per Caramels
-STR_802F_BUBBLE_VAN                                             :Furgó per Bombolles
+STR_802D_COTTON_CANDY_HOPPER                                    :Vagó per Cotó de Sucre
+STR_802E_TOFFEE_HOPPER                                          :Vagó per Caramels
+STR_802F_BUBBLE_VAN                                             :Vagó per Bombolles
 STR_8030_COLA_TANKER                                            :Tanc per Refresc
-STR_8031_CANDY_VAN                                              :Furgó per Dolços
-STR_8032_TOY_VAN                                                :Furgó per Joguines
+STR_8031_CANDY_VAN                                              :Vagó per Dolços
+STR_8032_TOY_VAN                                                :Vagó per Joguines
 STR_8033_BATTERY_TRUCK                                          :Vagó per Piles
 STR_8034_FIZZY_DRINK_TRUCK                                      :Vagó per Begudes Gasoses
 STR_8035_PLASTIC_TRUCK                                          :Vagó per Plàstic
@@ -2402,29 +2402,29 @@
 STR_8037_MILLENNIUM_Z1_ELECTRIC                                 :'Millennium Z1' (Elèctric)
 STR_8038_WIZZOWOW_Z99                                           :Wizzowow Z99
 STR_8039_PASSENGER_CAR                                          :Vagó per Passatgers
-STR_803A_MAIL_VAN                                               :Furgó per Correu
+STR_803A_MAIL_VAN                                               :Vagó per Correu
 STR_803B_COAL_CAR                                               :Vagó per Carbó
 STR_803C_OIL_TANKER                                             :Tanc de Petroli
-STR_803D_LIVESTOCK_VAN                                          :Furgó per Bestiar
-STR_803E_GOODS_VAN                                              :Furgó de Mercaderies
-STR_803F_GRAIN_HOPPER                                           :Furgó per Gra
+STR_803D_LIVESTOCK_VAN                                          :Vagó per Bestiar
+STR_803E_GOODS_VAN                                              :Vagó de Mercaderies
+STR_803F_GRAIN_HOPPER                                           :Vagó per Gra
 STR_8040_WOOD_TRUCK                                             :Vagó per Fusta
 STR_8041_IRON_ORE_HOPPER                                        :Vagó per Mineral de Ferro
 STR_8042_STEEL_TRUCK                                            :Vagó per Acer
-STR_8043_ARMORED_VAN                                            :Furgó Blindat
-STR_8044_FOOD_VAN                                               :Furgó per Queviures
+STR_8043_ARMORED_VAN                                            :Vagó Blindat
+STR_8044_FOOD_VAN                                               :Vagó per Queviures
 STR_8045_PAPER_TRUCK                                            :Vagó per Paper
-STR_8046_COPPER_ORE_HOPPER                                      :Furgó per Mineral de Coure
+STR_8046_COPPER_ORE_HOPPER                                      :Vagó per Mineral de Coure
 STR_8047_WATER_TANKER                                           :Tanc d'Aigua
 STR_8048_FRUIT_TRUCK                                            :Vagó per Fruita
 STR_8049_RUBBER_TRUCK                                           :Vagó per Cautxú
 STR_804A_SUGAR_TRUCK                                            :Vagó per Sucre
-STR_804B_COTTON_CANDY_HOPPER                                    :Furgó per Cotó de Sucre
-STR_804C_TOFFEE_HOPPER                                          :Furgó per Caramels
-STR_804D_BUBBLE_VAN                                             :Furgó per Bombolles
+STR_804B_COTTON_CANDY_HOPPER                                    :Vagó per Cotó de Sucre
+STR_804C_TOFFEE_HOPPER                                          :Vagó per Caramels
+STR_804D_BUBBLE_VAN                                             :Vagó per Bombolles
 STR_804E_COLA_TANKER                                            :Tanc per Refresc
-STR_804F_CANDY_VAN                                              :Furgó per Dolços
-STR_8050_TOY_VAN                                                :Furgó per Joguines
+STR_804F_CANDY_VAN                                              :Vagó per Dolços
+STR_8050_TOY_VAN                                                :Vagó per Joguines
 STR_8051_BATTERY_TRUCK                                          :Vagó per Piles
 STR_8052_FIZZY_DRINK_TRUCK                                      :Vagó per Begudes Gasoses
 STR_8053_PLASTIC_TRUCK                                          :Vagó per Plàstic
@@ -2434,29 +2434,29 @@
 STR_8057_LEV4_CHIMAERA_ELECTRIC                                 :Lev4 'Quimera' (Elèctric)
 STR_8058_WIZZOWOW_ROCKETEER                                     :Wizzowow Rocketeer
 STR_8059_PASSENGER_CAR                                          :Vagó per Passatgers
-STR_805A_MAIL_VAN                                               :Furgó per Correu
+STR_805A_MAIL_VAN                                               :Vagó per Correu
 STR_805B_COAL_CAR                                               :Vagó per Carbó
 STR_805C_OIL_TANKER                                             :Tanc de Petroli
-STR_805D_LIVESTOCK_VAN                                          :Furgó per Bestiar
-STR_805E_GOODS_VAN                                              :Furgó de Mercaderies
-STR_805F_GRAIN_HOPPER                                           :Furgó per Gra
+STR_805D_LIVESTOCK_VAN                                          :Vagó per Bestiar
+STR_805E_GOODS_VAN                                              :Vagó de Mercaderies
+STR_805F_GRAIN_HOPPER                                           :Vagó per Gra
 STR_8060_WOOD_TRUCK                                             :Vagó per Fusta
 STR_8061_IRON_ORE_HOPPER                                        :Vagó per Mineral de Ferro
 STR_8062_STEEL_TRUCK                                            :Vagó per Acer
-STR_8063_ARMORED_VAN                                            :Furgó Blindat
-STR_8064_FOOD_VAN                                               :Furgó per Queviures
+STR_8063_ARMORED_VAN                                            :Vagó Blindat
+STR_8064_FOOD_VAN                                               :Vagó per Queviures
 STR_8065_PAPER_TRUCK                                            :Vagó per Paper
-STR_8066_COPPER_ORE_HOPPER                                      :Furgó per Mineral de Coure
+STR_8066_COPPER_ORE_HOPPER                                      :Vagó per Mineral de Coure
 STR_8067_WATER_TANKER                                           :Tanc d'Aigua
 STR_8068_FRUIT_TRUCK                                            :Vagó per Fruita
 STR_8069_RUBBER_TRUCK                                           :Vagó per Cautxú
 STR_806A_SUGAR_TRUCK                                            :Vagó per Sucre
-STR_806B_COTTON_CANDY_HOPPER                                    :Furgó per Cotó de Sucre
-STR_806C_TOFFEE_HOPPER                                          :Furgó per Caramels
-STR_806D_BUBBLE_VAN                                             :Furgó per Bombolles
+STR_806B_COTTON_CANDY_HOPPER                                    :Vagó per Cotó de Sucre
+STR_806C_TOFFEE_HOPPER                                          :Vagó per Caramels
+STR_806D_BUBBLE_VAN                                             :Vagó per Bombolles
 STR_806E_COLA_TANKER                                            :Tanc per Refresc
-STR_806F_CANDY_VAN                                              :Furgó per Dolços
-STR_8070_TOY_VAN                                                :Furgó per Joguines
+STR_806F_CANDY_VAN                                              :Vagó per Dolços
+STR_8070_TOY_VAN                                                :Vagó per Joguines
 STR_8071_BATTERY_TRUCK                                          :Vagó per Piles
 STR_8072_FIZZY_DRINK_TRUCK                                      :Vagó per Begudes Gasoses
 STR_8073_PLASTIC_TRUCK                                          :Vagó per Plàstic
@@ -2479,9 +2479,9 @@
 STR_8084_WITCOMBE_OIL_TANKER                                    :Cuba de Petroli Witcombe
 STR_8085_FOSTER_OIL_TANKER                                      :Cuba de Petroli Foster
 STR_8086_PERRY_OIL_TANKER                                       :Cuba de Petroli Perry
-STR_8087_TALBOTT_LIVESTOCK_VAN                                  :Furgó de Bestiar Talbott
-STR_8088_UHL_LIVESTOCK_VAN                                      :Furgó de Bestiar Uhl
-STR_8089_FOSTER_LIVESTOCK_VAN                                   :Furgó de Bestiar Foster
+STR_8087_TALBOTT_LIVESTOCK_VAN                                  :Camió de Bestiar Talbott
+STR_8088_UHL_LIVESTOCK_VAN                                      :Vagó de Bestiar Uhl
+STR_8089_FOSTER_LIVESTOCK_VAN                                   :Camió de Bestiar Foster
 STR_808A_BALOGH_GOODS_TRUCK                                     :Camió de Mercaderies
 STR_808B_CRAIGHEAD_GOODS_TRUCK                                  :Camió de Mercaderies
 STR_808C_GOSS_GOODS_TRUCK                                       :Camió de Mercaderies Goss
@@ -2710,13 +2710,13 @@
 STR_883B_CAN_T_STOP_START_TRAIN                                 :{WHITE}No es pot parar/arrencar el tren...
 STR_883C_SERVICING_INTERVAL_DAYS                                :{BLACK}Interval de manteniment: {LTBLUE}{COMMA}dies{BLACK}   Darrer manteniment: {LTBLUE}{DATE_LONG}
 STR_SERVICING_INTERVAL_PERCENT                                  :{BLACK}Interval de manteniment: {LTBLUE}{COMMA}%{BLACK}   Darrer manteniment: {LTBLUE}{DATE_LONG}
-STR_883D_TRAINS_CLICK_ON_TRAIN_FOR                              :{BLACK}Trens - clica al tren per informació
+STR_883D_TRAINS_CLICK_ON_TRAIN_FOR                              :{BLACK}Trens - clica al tren per més informació
 STR_883E_BUILD_NEW_TRAINS_REQUIRES                              :{BLACK}Construeix nous trens (es necessita cotxera)
 STR_883F_TRAINS_CLICK_ON_TRAIN_FOR                              :{BLACK}Trens - clica al tren per info., arrossega el vehicle per afegir/treure del tren
 STR_8840_BUILD_NEW_TRAIN_VEHICLE                                :{BLACK}Construeix un nou element de tren
 STR_8841_DRAG_TRAIN_VEHICLE_TO_HERE                             :{BLACK}Arrossega l'element de tren fins aquí per vendre'l
 STR_8842_CENTER_MAIN_VIEW_ON_TRAIN                              :{BLACK}Centra la vista de la pantalla principal en la situació de la cotxera
-STR_8843_TRAIN_VEHICLE_SELECTION                                :{BLACK}Llista de selecció d'elements de tren - clica a l'element per informació
+STR_8843_TRAIN_VEHICLE_SELECTION                                :{BLACK}Llista de selecció d'elements de tren - clica a l'element per més informació
 STR_8844_BUILD_THE_HIGHLIGHTED_TRAIN                            :{BLACK}Construeix l'element de tren seleccionat
 STR_8845_RENAME_TRAIN_VEHICLE_TYPE                              :{BLACK}Reanomena el tipus d'element del tren
 STR_8846_CURRENT_TRAIN_ACTION_CLICK                             :{BLACK}Acció sobre el tren actual - clica aquí per parar/arrencar el tren
@@ -2815,7 +2815,7 @@
 STR_HEADING_FOR_ROAD_DEPOT_SERVICE_VEL                          :{LTBLUE}Revisió a la cotxera de {TOWN}, {VELOCITY}
 STR_9018_CAN_T_SEND_VEHICLE_TO_DEPOT                            :{WHITE}No es pot enviar el vehicle a cotxera...
 STR_9019_UNABLE_TO_FIND_LOCAL_DEPOT                             :{WHITE}Impossible trobar la cotxera local
-STR_901A_ROAD_VEHICLES_CLICK_ON                                 :{BLACK}Automòbils - clica en un vehicle per informació
+STR_901A_ROAD_VEHICLES_CLICK_ON                                 :{BLACK}Automòbils - clica en un vehicle per més informació
 STR_901B_BUILD_NEW_ROAD_VEHICLES                                :{BLACK}Construeix nous automòbils (necessita una cotxera)
 STR_901C_CURRENT_VEHICLE_ACTION                                 :{BLACK}Acció sobre el vehicle actual - clica aquí per parar/arrencar el vehicle
 STR_901D_SHOW_VEHICLE_S_ORDERS                                  :{BLACK}Mostra les ordres dels vehicles
@@ -2823,11 +2823,11 @@
 STR_901F_SEND_VEHICLE_TO_DEPOT                                  :{BLACK}Envia el vehicle a cotxera
 STR_9020_FORCE_VEHICLE_TO_TURN_AROUND                           :{BLACK}Obliga al vehicle a tornar
 STR_9021_SHOW_ROAD_VEHICLE_DETAILS                              :{BLACK}Mostra els detalls del vehicle
-STR_9022_VEHICLES_CLICK_ON_VEHICLE                              :{BLACK}Vehicles - clica en un vehicle per informació
+STR_9022_VEHICLES_CLICK_ON_VEHICLE                              :{BLACK}Vehicles - clica en un vehicle per més informació
 STR_9023_BUILD_NEW_ROAD_VEHICLE                                 :{BLACK}Construeix un nou automòbil
 STR_9024_DRAG_ROAD_VEHICLE_TO_HERE                              :{BLACK}Arrossega el vehicle fins aquí per vendre'l
 STR_9025_CENTER_MAIN_VIEW_ON_ROAD                               :{BLACK}Centra la pantalla principal en la situació de la cotxera
-STR_9026_ROAD_VEHICLE_SELECTION                                 :{BLACK}Llista de selecció de Vehicles - clica en un vehicle per informació
+STR_9026_ROAD_VEHICLE_SELECTION                                 :{BLACK}Llista de selecció de Vehicles - clica en un vehicle per més informació
 STR_9027_BUILD_THE_HIGHLIGHTED_ROAD                             :{BLACK}Construeix l'automòbil seleccionat
 STR_902A_COST_SPEED_RUNNING_COST                                :{BLACK}Cost: {CURRENCY}{}Velocitat: {VELOCITY}{}Cost de circulació: {CURRENCY}/any{}Capacitat: {CARGO}
 STR_ARTICULATED_RV_CAPACITY                                     :{BLACK}Capacitat: {LTBLUE}
@@ -2891,13 +2891,13 @@
 STR_981C_SHIP_IS_WAITING_IN_DEPOT                               :{WHITE}Vaixell {COMMA} esperant en drassana
 STR_981D_BUILD_SHIP_DOCK                                        :{BLACK}Construeix un port
 STR_981E_BUILD_SHIP_DEPOT_FOR_BUILDING                          :{BLACK}Construeix una drassana (per construir i revisar vaixells)
-STR_981F_SHIPS_CLICK_ON_SHIP_FOR                                :{BLACK}Vaixells - clica en un vaixell per informació
+STR_981F_SHIPS_CLICK_ON_SHIP_FOR                                :{BLACK}Vaixells - clica en un vaixell per més informació
 STR_9820_BUILD_NEW_SHIP                                         :{BLACK}Construeix un nou vaixell
 STR_9821_DRAG_SHIP_TO_HERE_TO_SELL                              :{BLACK}Arrossega el vaixell fins aquí per vendre'l
 STR_9822_CENTER_MAIN_VIEW_ON_SHIP                               :{BLACK}Centra la pantalla principal en la situació de la drassana
-STR_9823_SHIPS_CLICK_ON_SHIP_FOR                                :{BLACK}Vaixells - clica en un vaixell per informació
+STR_9823_SHIPS_CLICK_ON_SHIP_FOR                                :{BLACK}Vaixells - clica en un vaixell per més informació
 STR_9824_BUILD_NEW_SHIPS_REQUIRES                               :{BLACK}Construeix nous vaixells (necessites una drassana)
-STR_9825_SHIP_SELECTION_LIST_CLICK                              :{BLACK}LLista de selecció de Vaixells - clica en un vaixell per informació
+STR_9825_SHIP_SELECTION_LIST_CLICK                              :{BLACK}Llista de selecció de Vaixells - clica en un vaixell per més informació
 STR_9826_BUILD_THE_HIGHLIGHTED_SHIP                             :{BLACK}Construeix el vaixell seleccionat
 STR_9827_CURRENT_SHIP_ACTION_CLICK                              :{BLACK}Accions sobre el vaixell actual - clica aquí per parar/arrencar el vaixell
 STR_9828_SHOW_SHIP_S_ORDERS                                     :{BLACK}Mostra les ordres del vaixell
@@ -2963,13 +2963,13 @@
 STR_A01C_CAN_T_SELL_AIRCRAFT                                    :{WHITE}No es pot vendre l'avió...
 STR_A01D_AIRPORT_CONSTRUCTION                                   :Construcció d'Aeroport
 STR_A01E_BUILD_AIRPORT                                          :{BLACK}Construeix un aeroport
-STR_A01F_AIRCRAFT_CLICK_ON_AIRCRAFT                             :{BLACK}Avió - clica sobre l'avió per informació
+STR_A01F_AIRCRAFT_CLICK_ON_AIRCRAFT                             :{BLACK}Avió - clica sobre l'avió per més informació
 STR_A020_BUILD_NEW_AIRCRAFT_REQUIRES                            :{BLACK}Construeix nous avions (necessites un aeroport amb hangar)
-STR_A021_AIRCRAFT_CLICK_ON_AIRCRAFT                             :{BLACK}Avió - clica sobre l'avió per informació
+STR_A021_AIRCRAFT_CLICK_ON_AIRCRAFT                             :{BLACK}Avió - clica sobre l'avió per més informació
 STR_A022_BUILD_NEW_AIRCRAFT                                     :{BLACK}Construeix nous avions
 STR_A023_DRAG_AIRCRAFT_TO_HERE_TO                               :{BLACK}Arrossega l'avió fins aquí per vendre'l
 STR_A024_CENTER_MAIN_VIEW_ON_HANGAR                             :{BLACK}Centra la pantalla principal en la situació de l'hangar
-STR_A025_AIRCRAFT_SELECTION_LIST                                :{BLACK}Llista de selecció d'Avions - clica sobre l'avió per informació
+STR_A025_AIRCRAFT_SELECTION_LIST                                :{BLACK}Llista de selecció d'Avions - clica sobre l'avió per més informació
 STR_A026_BUILD_THE_HIGHLIGHTED_AIRCRAFT                         :{BLACK}Construeix l'avió seleccionat
 STR_A027_CURRENT_AIRCRAFT_ACTION                                :{BLACK}Accions sobre l'avió actual - clica aquí per parar/arrencar l'avió
 STR_A028_SHOW_AIRCRAFT_S_ORDERS                                 :{BLACK}Mostra les ordres de l'avió
--- a/src/lang/croatian.txt	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/lang/croatian.txt	Fri Aug 03 18:10:15 2007 +0000
@@ -25,90 +25,48 @@
 STR_000E                                                        :
 STR_000F_PASSENGERS                                             :putnici
 STR_0010_COAL                                                   :ugljen
-STR_0010_COAL.gen                                               :ugljena
 STR_0011_MAIL                                                   :pošta
-STR_0011_MAIL.gen                                               :pošte
 STR_0012_OIL                                                    :nafta
-STR_0012_OIL.gen                                                :nafte
 STR_0013_LIVESTOCK                                              :domaće životinje
-STR_0013_LIVESTOCK.gen                                          :domaćih životinja
 STR_0014_GOODS                                                  :robe
-STR_0014_GOODS.gen                                              :roba
 STR_0015_GRAIN                                                  :žito
-STR_0015_GRAIN.gen                                              :žita
 STR_0016_WOOD                                                   :drvo
-STR_0016_WOOD.gen                                               :drva
 STR_0017_IRON_ORE                                               :željezo
-STR_0017_IRON_ORE.gen                                           :željeza
 STR_0018_STEEL                                                  :čelik
-STR_0018_STEEL.gen                                              :čelika
 STR_0019_VALUABLES                                              :dragocjenosti
-STR_0019_VALUABLES.gen                                          :dragocjenosti
 STR_001A_COPPER_ORE                                             :bakar
-STR_001A_COPPER_ORE.gen                                         :bakra
 STR_001B_MAIZE                                                  :kukuruz
-STR_001B_MAIZE.gen                                              :kukuruza
 STR_001C_FRUIT                                                  :voće
-STR_001C_FRUIT.gen                                              :voća
 STR_001D_DIAMONDS                                               :dijamanti
-STR_001D_DIAMONDS.gen                                           :dijamanata
 STR_001E_FOOD                                                   :hrana
-STR_001E_FOOD.gen                                               :hrane
 STR_001F_PAPER                                                  :papir
-STR_001F_PAPER.gen                                              :papira
 STR_0020_GOLD                                                   :zlato
-STR_0020_GOLD.gen                                               :zlata
 STR_0021_WATER                                                  :voda
-STR_0021_WATER.gen                                              :vode
 STR_0022_WHEAT                                                  :pšenica
-STR_0022_WHEAT.gen                                              :pšenice
 STR_0023_RUBBER                                                 :guma
-STR_0023_RUBBER.gen                                             :gume
 STR_0024_SUGAR                                                  :šećer
-STR_0024_SUGAR.gen                                              :šećera
 STR_0025_TOYS                                                   :igrače
-STR_0025_TOYS.gen                                               :igračaka
 STR_0026_CANDY                                                  :slatkiši
-STR_0026_CANDY.gen                                              :slatkiša
 STR_0027_COLA                                                   :cola
-STR_0027_COLA.gen                                               :cole
 STR_0028_COTTON_CANDY                                           :šećerna vuna
-STR_0028_COTTON_CANDY.gen                                       :šećerne vune
 STR_0029_BUBBLES                                                :baloni
-STR_0029_BUBBLES.gen                                            :balona
 STR_002A_TOFFEE                                                 :mliječne karamele
-STR_002A_TOFFEE.gen                                             :mliječnih karamela
 STR_002B_BATTERIES                                              :baterije
-STR_002B_BATTERIES.gen                                          :baterija
 STR_002C_PLASTIC                                                :plastika
-STR_002C_PLASTIC.gen                                            :plastike
 STR_002D_FIZZY_DRINKS                                           :gazirana pića
-STR_002D_FIZZY_DRINKS.gen                                       :gaziranih pića
 STR_002E                                                        :
 STR_002F_PASSENGER                                              :putnik
-STR_002F_PASSENGER.gen                                          :putnika
 STR_0030_COAL                                                   :ugljen
-STR_0030_COAL.gen                                               :ugljena
 STR_0031_MAIL                                                   :pošta
-STR_0031_MAIL.gen                                               :pošte
 STR_0032_OIL                                                    :nafta
-STR_0032_OIL.gen                                                :nafte
 STR_0033_LIVESTOCK                                              :domaće životinje
-STR_0033_LIVESTOCK.gen                                          :domaćih životinja
 STR_0034_GOODS                                                  :robe
-STR_0034_GOODS.gen                                              :roba
 STR_0035_GRAIN                                                  :žito
-STR_0035_GRAIN.gen                                              :žita
 STR_0036_WOOD                                                   :drvo
-STR_0036_WOOD.gen                                               :drva
 STR_0037_IRON_ORE                                               :željezo
-STR_0037_IRON_ORE.gen                                           :željeza
 STR_0038_STEEL                                                  :čelik
-STR_0038_STEEL.gen                                              :čelika
 STR_0039_VALUABLES                                              :dragocjenosti
-STR_0039_VALUABLES.gen                                          :dragocjenosti
 STR_003A_COPPER_ORE                                             :bakar
-STR_003A_COPPER_ORE.gen                                         :bakra
 STR_003B_MAIZE                                                  :Kukuruz
 STR_003C_FRUIT                                                  :Voće
 STR_003D_DIAMOND                                                :Dijamant
@@ -1264,8 +1222,6 @@
 STR_WAYPOINTNAME_CITY                                           : Čvorište{TOWN}
 STR_WAYPOINTNAME_CITY_SERIAL                                    :Čvorište {TOWN} #{COMMA}
 STR_LANDINFO_WAYPOINT                                           :Čvorište
-STR_LANDINFO_WAYPOINT.gen                                       :čvorišta
-STR_LANDINFO_WAYPOINT.dat                                       :čvorištu
 
 STR_WAYPOINT                                                    :{WHITE}Čvorište
 STR_WAYPOINT_GRAPHICS_TIP                                       :{BLACK}Odaberi vrstu čvorišta
@@ -2124,7 +2080,7 @@
 STR_SV_STNAME_HALT                                              :{STRING} Zaustavi
 STR_SV_STNAME_VALLEY                                            :{STRING} Dolina
 STR_SV_STNAME_HEIGHTS                                           :{STRING} Visine
-STR_SV_STNAME_WOODS                                             :{STRING} Šume
+STR_SV_STNAME_WOODS                                             :{STRING} šume
 STR_SV_STNAME_LAKESIDE                                          :{STRING} Jezero
 STR_SV_STNAME_EXCHANGE                                          :{STRING} Burza
 STR_SV_STNAME_AIRPORT                                           :{STRING} Zračna luka
@@ -2424,7 +2380,7 @@
 STR_801F_LIVESTOCK_VAN                                          :Kamion za stoku
 STR_8020_GOODS_VAN                                              :Kamion za robu
 STR_8021_GRAIN_HOPPER                                           :Tegljač žita
-STR_8022_WOOD_TRUCK                                             :Kamion za drvo
+STR_8022_WOOD_TRUCK                                             :Kamion za drva
 STR_8023_IRON_ORE_HOPPER                                        :Tegljač željeza
 STR_8024_STEEL_TRUCK                                            :Kamion za čelik
 STR_8025_ARMORED_VAN                                            :Oklopljeni kombi
@@ -2454,7 +2410,7 @@
 STR_803D_LIVESTOCK_VAN                                          :Kamion za stoku
 STR_803E_GOODS_VAN                                              :Kamion za robu
 STR_803F_GRAIN_HOPPER                                           :Tegljač žita
-STR_8040_WOOD_TRUCK                                             :Kamion za drvo
+STR_8040_WOOD_TRUCK                                             :Kamion za drva
 STR_8041_IRON_ORE_HOPPER                                        :Tegljač željeza
 STR_8042_STEEL_TRUCK                                            :Kamion za željezo
 STR_8043_ARMORED_VAN                                            :Oklopno vozilo
@@ -2534,9 +2490,9 @@
 STR_808D_HEREFORD_GRAIN_TRUCK                                   :Hereford Kamion za žitarice
 STR_808E_THOMAS_GRAIN_TRUCK                                     :Thomas Kamion za žitarice
 STR_808F_GOSS_GRAIN_TRUCK                                       :Goss Kamion za žitarice
-STR_8090_WITCOMBE_WOOD_TRUCK                                    :Witcombe Kamion za drvo
-STR_8091_FOSTER_WOOD_TRUCK                                      :Foster Kamion za drvo
-STR_8092_MORELAND_WOOD_TRUCK                                    :Moreland Kamion za Drvo
+STR_8090_WITCOMBE_WOOD_TRUCK                                    :Witcombe Kamion za drva
+STR_8091_FOSTER_WOOD_TRUCK                                      :Foster Kamion za drva
+STR_8092_MORELAND_WOOD_TRUCK                                    :Moreland Kamion za drva
 STR_8093_MPS_IRON_ORE_TRUCK                                     :MPS Kamion za željeznu rudu
 STR_8094_UHL_IRON_ORE_TRUCK                                     :Uhl Kamion za željezu rudu
 STR_8095_CHIPPY_IRON_ORE_TRUCK                                  :Chippy Kamion za željeznu rudu
--- a/src/lang/german.txt	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/lang/german.txt	Fri Aug 03 18:10:15 2007 +0000
@@ -1231,11 +1231,11 @@
 STR_EDIT_WAYPOINT_NAME                                          :{WHITE}Wegpunktename ändern
 
 STR_CANT_CHANGE_WAYPOINT_NAME                                   :{WHITE}Kann Wegpunktname nicht ändern...
-STR_CONVERT_RAIL_TO_WAYPOINT_TIP                                :{BLACK}Ändere Schiene in einen Wegpunkt
+STR_CONVERT_RAIL_TO_WAYPOINT_TIP                                :{BLACK}Ändere Gleis in einen Wegpunkt
 STR_CANT_BUILD_TRAIN_WAYPOINT                                   :{WHITE}Kann Wegpunkt hier nicht bauen...
 STR_CANT_REMOVE_TRAIN_WAYPOINT                                  :{WHITE}Kann Wegpunkt hier nicht entfernen...
 
-STR_BUILD_AUTORAIL_TIP                                          :{BLACK}Bauen von Schienen unter Verwendung des Autoschienenmodus
+STR_BUILD_AUTORAIL_TIP                                          :{BLACK}Bauen von Gleisen unter Verwendung des Automatikmodus
 
 STR_NO_TOWN_IN_SCENARIO                                         :{WHITE}...in diesem Szenario gibt es keine Stadt
 
@@ -3158,7 +3158,7 @@
 STR_REPLACE_HELP_RIGHT_ARRAY                                    :{BLACK}Wähle den Fahrzeugtyp, der anstelle des links gewählten Fahrzeugs verwendet werden soll
 STR_REPLACE_HELP_STOP_BUTTON                                    :{BLACK}Drücke diesen Button, wenn das Fahrzeug auf der linken Seite nicht ersetzt werden soll
 STR_REPLACE_HELP_START_BUTTON                                   :{BLACK}Drücke diesen Button, wenn das Fahrzeug auf der linken Seite durch das auf der rechten Seite gewählte ersetzt werden soll
-STR_REPLACE_HELP_RAILTYPE                                       :{BLACK}Wähle einen Schienentyp für den Loks ersetzt werden sollen
+STR_REPLACE_HELP_RAILTYPE                                       :{BLACK}Wähle einen Gleistyp für den Loks ersetzt werden sollen
 STR_REPLACE_HELP_REPLACE_INFO_TAB                               :{BLACK}Hier wird angezeigt, gegen welches Fahrzeug das auf der linken Seite gewählte ersetzt wird
 STR_REPLACE_HELP                                                :{BLACK}Dieses Feature ermöglicht es, einen Fahrzeugtyp auszuwählen und ihn durch einen anderen ersetzen zu lassen. Dies geschieht automatisch, wenn das Fahrzeug regulär das Depot besucht.
 STR_REPLACE_REMOVE_WAGON                                        :{BLACK}Waggon-Entfernung: {ORANGE}{SKIP}{STRING}
--- a/src/lang/polish.txt	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/lang/polish.txt	Fri Aug 03 18:10:15 2007 +0000
@@ -2099,6 +2099,9 @@
 STR_4829_REQUIRES                                               :{BLACK}Wymaga: {YELLOW}{STRING}, {STRING}, {STRING}
 ############ range for requires ends
 
+############ range for produces starts
+############ range for produces ends
+
 STR_482A_PRODUCTION_LAST_MONTH                                  :{BLACK}Wyprodukowano w ostatnim miesiącu:
 STR_482B_TRANSPORTED                                            :{YELLOW}{CARGO}{BLACK} ({COMMA}% przetransportowano)
 STR_482C_CENTER_THE_MAIN_VIEW_ON                                :{BLACK}Centruj główny widok na przedsiębiorstwie
@@ -3451,6 +3454,10 @@
 STR_GROUP_ALL_ROADS                                             :Wszystkie samochody
 STR_GROUP_ALL_SHIPS                                             :Wszystkie statki
 STR_GROUP_ALL_AIRCRAFTS                                         :Wszystkie samoloty
+STR_GROUP_DEFAULT_TRAINS                                        :Pociągi bez grupy
+STR_GROUP_DEFAULT_ROADS                                         :Samochody bez grupy
+STR_GROUP_DEFAULT_SHIPS                                         :Statki bez grupy
+STR_GROUP_DEFAULT_AIRCRAFTS                                     :Samoloty bez grupy
 STR_GROUP_TINY_NUM                                              :{TINYFONT}{COMMA}
 STR_GROUP_ADD_SHARED_VEHICLE                                    :Dodaj poj. współdzielące
 STR_GROUP_REMOVE_ALL_VEHICLES                                   :Usuń wszystkie pojazdy
@@ -3494,3 +3501,5 @@
 STR_PREVIOUS_SIGN_TOOLTIP                                       :{BLACK}Idź do poprzedniej tablicy
 
 ########
+
+STR_INDUSTRY_SELECTION_HINT                                     :{BLACK}Wybierz przedsiębiorstwo z listy
--- a/src/macros.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/macros.h	Fri Aug 03 18:10:15 2007 +0000
@@ -5,11 +5,57 @@
 #ifndef MACROS_H
 #define MACROS_H
 
-/* Fetch n bits starting at bit s from x */
+/**
+ * Fetch n bits from x, started at bit s.
+ *
+ * This macro can be used to fetch n bits from the value x. The
+ * s value set the startposition to read. The startposition is
+ * count from the LSB and starts at 0. The result starts at a
+ * LSB, as this isn't just an and-bitmask but also some
+ * bit-shifting operations. GB(0xFF, 2, 1) will so
+ * return 0x01 (0000 0001) instead of
+ * 0x04 (0000 0100).
+ *
+ * @param x The value to read some bits.
+ * @param s The startposition to read some bits.
+ * @param n The number of bits to read.
+ * @return The selected bits, aligned to a LSB.
+ */
 #define GB(x, s, n) (((x) >> (s)) & ((1U << (n)) - 1))
-/* Set n bits starting at bit s in x to d */
+
+/** Set n bits from x starting at bit s to d
+ *
+ * This macro sets n bits from x which started as bit s to the value of
+ * d. The parameters x, s and n works the same as the parameters of
+ * #GB. The result is saved in x again. Unused bits in the window
+ * provided by n are set to 0 if the value of b isn't "big" enough.
+ * This is not a bug, its a feature.
+ *
+ * @note Parameter x must be a variable as the result is saved there.
+ * @note To avoid unexpecting results the value of b should not use more
+ *       space as the provided space of n bits (log2)
+ * @param x The variable to change some bits
+ * @param s The startposition for the new bits
+ * @param n The size/window for the new bits
+ * @param d The actually new bits to save in the defined position.
+ * @return The new value of x
+ */
 #define SB(x, s, n, d) ((x) = ((x) & ~(((1U << (n)) - 1) << (s))) | ((d) << (s)))
-/* Add i to the n bits starting at bit s in x */
+
+/** Add i to n bits of x starting at bit s.
+ *
+ * This add the value of i on n bits of x starting at bit s. The parameters x,
+ * s, i are similar to #GB besides x must be a variable as the result are
+ * saved there. An overflow does not affect the following bits of the given
+ * bit window and is simply ignored.
+ *
+ * @note Parameter x must be a variable as the result is saved there.
+ * @param x The variable to add some bits at some position
+ * @param s The startposition of the addition
+ * @param n The size/window for the addition
+ * @param i The value to add at the given startposition in the given window.
+ * @return The new value of x
+ */
 #define AB(x, s, n, i) ((x) = ((x) & ~(((1U << (n)) - 1) << (s))) | (((x) + ((i) << (s))) & (((1U << (n)) - 1) << (s))))
 
 #ifdef min
@@ -20,23 +66,76 @@
 #undef max
 #endif
 
+/**
+ * Returns the maximum of two values.
+ *
+ * This function returns the greater value of two given values.
+ * If they are equal the value of a is returned.
+ *
+ * @param a The first value
+ * @param b The second value
+ * @return The greater value or a if equals
+ */
 template <typename T>
 static inline T max(T a, T b)
 {
 	return a >= b ? a : b;
 }
 
+/**
+ * Returns the minimum of two values.
+ *
+ * This function returns the smaller value of two given values.
+ * If they are equal the value of b is returned.
+ *
+ * @param a The first value
+ * @param b The second value
+ * @return The smaller value or b if equals
+ */
 template <typename T>
 static inline T min(T a, T b)
 {
 	return a < b ? a : b;
 }
 
+/**
+ * Returns the minimum of two integer.
+ *
+ * This function returns the smaller value of two given integers.
+ *
+ * @param a The first integer
+ * @param b The second integer
+ * @return The smaller value
+ */
 static inline int min(int a, int b) { if (a <= b) return a; return b; }
 
+/**
+ * Returns the minimum of two unsigned integers.
+ *
+ * This function returns the smaller value of two given unsigned integers.
+ *
+ * @param a The first unsigned integer
+ * @param b The second unsigned integer
+ * @return The smaller value
+ */
 static inline uint minu(uint a, uint b) { if (a <= b) return a; return b; }
 
-
+/**
+ * Clamp an integer between an interval.
+ *
+ * This function returns a value which is between the given interval of
+ * min and max. If the given value is in this interval the value itself
+ * is returned otherwise the border of the interval is returned, according
+ * which side of the interval was 'left'.
+ *
+ * @note The min value must be less or equal of max or you get some
+ *       unexpected results.
+ * @param a The value to clamp/truncate.
+ * @param min The minimum of the interval.
+ * @param max the maximum of the interval.
+ * @returns A value between min and max which is closest to a.
+ * @see clampu(uint, uint, uint)
+ */
 static inline int clamp(int a, int min, int max)
 {
 	if (a <= min) return min;
@@ -44,6 +143,22 @@
 	return a;
 }
 
+/**
+ * Clamp an unsigned integer between an interval.
+ *
+ * This function returns a value which is between the given interval of
+ * min and max. If the given value is in this interval the value itself
+ * is returned otherwise the border of the interval is returned, according
+ * which side of the interval was 'left'.
+ *
+ * @note The min value must be less or equal of max or you get some
+ *       unexpected results.
+ * @param a The value to clamp/truncate.
+ * @param min The minimum of the interval.
+ * @param max the maximum of the interval.
+ * @returns A value between min and max which is closest to a.
+ * @see clamp(int, int, int)
+ */
 static inline uint clampu(uint a, uint min, uint max)
 {
 	if (a <= min) return min;
@@ -51,7 +166,20 @@
 	return a;
 }
 
-/* Gracefully reduce a signed 64-bit int to signed 32-bit -- no bogusly truncating the sign bit */
+/**
+ * Reduce a signed 64-bit int to a signed 32-bit one
+ *
+ * This function clamps a 64-bit integer to a 32-bit integer.
+ * If the 64-bit value is smaller than the smallest 32-bit integer
+ * value 0x80000000 this value is returned (the left one bit is the sign bit).
+ * If the 64-bit value is greater than the greatest 32-bit integer value 0x7FFFFFFF
+ * this value is returned. In all other cases the 64-bit value 'fits' in a
+ * 32-bits integer field and so the value is casted to int32 and returned.
+ *
+ * @param a The 64-bit value to clamps
+ * @return The 64-bit value reduced to a 32-bit value
+ * @see clamp(int, int, int)
+ */
 static inline int32 ClampToI32(int64 a)
 {
 	if (a <= (int32)0x80000000) return 0x80000000;
@@ -59,36 +187,114 @@
 	return (int32)a;
 }
 
+/**
+ * Multiply two integer values and shift the results to right.
+ *
+ * This function multiplies two integer values. The result is
+ * shifted by the amount of shift to right.
+ *
+ * @param a The first integer
+ * @param b The second integer
+ * @param shift The amount to shift the value to right.
+ * @return The shifted result
+ */
 static inline int32 BIGMULSS(int32 a, int32 b, int shift)
 {
 	return (int32)((int64)a * (int64)b >> shift);
 }
 
+/**
+ * Multiply two unsigned integers and shift the results to right.
+ *
+ * This function multiplies two unsigned integers. The result is
+ * shifted by the amount of shift to right.
+ *
+ * @param a The first unsigned integer
+ * @param b The second unsigned integer
+ * @param shift The amount to shift the value to right.
+ * @return The shifted result
+ */
 static inline uint32 BIGMULUS(uint32 a, uint32 b, int shift)
 {
 	return (uint32)((uint64)a * (uint64)b >> shift);
 }
 
 
+/**
+ * Checks if a value is between a window started at some base point.
+ *
+ * This macro checks if the value x is between the value of base
+ * and base+size. If x equals base this returns true. If x equals
+ * base+size this returns false.
+ *
+ * @param x The value to check
+ * @param base The base value of the interval
+ * @param size The size of the interval
+ * @return True if the value is in the interval, false else.
+ */
 /* OPT: optimized into an unsigned comparison */
 //#define IS_INSIDE_1D(x, base, size) ((x) >= (base) && (x) < (base) + (size))
 #define IS_INSIDE_1D(x, base, size) ( (uint)((x) - (base)) < ((uint)(size)) )
 
+/**
+ * Checks if a bit in a value is set.
+ *
+ * This function checks if a bit inside a value is set or not.
+ * The y value specific the position of the bit, started at the
+ * LSB and count from 0.
+ *
+ * @param x The value to check
+ * @param y The position of the bit to check, started from the LSB
+ * @return True if the bit is set, false else.
+ */
 template<typename T> static inline bool HASBIT(T x, int y)
 {
 	return (x & ((T)1 << y)) != 0;
 }
 
+/**
+ * Set a bit in a variable.
+ *
+ * This function sets a bit in a variable. The variable is changed
+ * and the value is also returned. Parameter y defines the bit and
+ * starts at the LSB with 0.
+ *
+ * @param x The variable to set a bit
+ * @param y The bit position to set
+ * @return The new value of the old value with the bit set
+ */
 template<typename T> static inline T SETBIT(T& x, int y)
 {
 	return x |= (T)1 << y;
 }
 
+/**
+ * Clears a bit in a variable.
+ *
+ * This function clears a bit in a variable. The variable is
+ * changed and the value is also returned. Parameter y defines the bit
+ * to clear and starts at the LSB with 0.
+ *
+ * @param x The variable to clear the bit
+ * @param y The bit position to clear
+ * @return The new value of the old value with the bit cleared
+ */
 template<typename T> static inline T CLRBIT(T& x, int y)
 {
 	return x &= ~((T)1 << y);
 }
 
+/**
+ * Toggles a bit in a variable.
+ *
+ * This function toggles a bit in a variable. The variable is
+ * changed and the value is also returned. Parameter y defines the bit
+ * to toggle and starts at the LSB with 0.
+ *
+ * @param x The varliable to toggle the bit
+ * @param y The bit position to toggle
+ * @return The new value of the old value with the bit toggled
+ */
 template<typename T> static inline T TOGGLEBIT(T& x, int y)
 {
 	return x ^= (T)1 << y;
@@ -96,24 +302,84 @@
 
 
 /* checking more bits. Maybe unneccessary, but easy to use */
+/**
+ * Check several bits in a value.
+ *
+ * This macro checks if a value contains at least one bit of an other
+ * value.
+ *
+ * @param x The first value
+ * @param y The second value
+ * @return True if at least one bit is set in both values, false else.
+ */
 #define HASBITS(x, y) ((x) & (y))
+
+/**
+ * Sets several bits in a variable.
+ *
+ * This macro sets several bits in a variable. The bits to set are provided
+ * by a value. The new value is also returned.
+ *
+ * @param x The variable to set some bits
+ * @param y The value with set bits for setting them in the variable
+ * @return The new value of x
+ */
 #define SETBITS(x, y) ((x) |= (y))
+
+/**
+ * Clears several bits in a variable.
+ *
+ * This macro clears several bits in a variable. The bits to clear are
+ * provided by a value. The new value is also returned.
+ *
+ * @param x The variable to clear some bits
+ * @param y The value with set bits for clearing them in the variable
+ * @return The new value of x
+ */
 #define CLRBITS(x, y) ((x) &= ~(y))
 
 #define GENERAL_SPRITE_COLOR(color) ((color) + PALETTE_RECOLOR_START)
 #define PLAYER_SPRITE_COLOR(owner) (GENERAL_SPRITE_COLOR(_player_colors[owner]))
 
 extern const byte _ffb_64[128];
-/* Returns the position of the first bit that is not zero, counted from the
- * left. Ie, 10110100 returns 2, 00000001 returns 0, etc. When x == 0 returns
+
+/**
+ * Returns the first occure of a bit in a 6-bit value (from right).
+ *
+ * Returns the position of the first bit that is not zero, counted from the
+ * LSB. Ie, 110100 returns 2, 000001 returns 0, etc. When x == 0 returns
  * 0.
+ *
+ * @param x The 6-bit value to check the first zero-bit
+ * @return The first position of a bit started from the LSB or 0 if x is 0.
  */
 #define FIND_FIRST_BIT(x) _ffb_64[(x)]
-/* Returns x with the first bit that is not zero, counted from the left, set
- * to zero. So, 10110100 returns 10110000, 00000001 returns 00000000, etc.
+
+/**
+ * Returns a value with the first occured of a bit set to zero.
+ *
+ * Returns x with the first bit from LSB that is not zero set
+ * to zero. So, 110100 returns 110000, 000001 returns 000000, etc.
+ *
+ * @param x The value to returned a new value
+ * @return The value which the first bit is set to zero
  */
 #define KILL_FIRST_BIT(x) _ffb_64[(x) + 64]
 
+/**
+ * Finds the position of the first bit in an integer.
+ *
+ * This function returns the position of the first bit set in the
+ * integer. It does only check the bits of the bitmask
+ * 0x3F3F (0011111100111111) and checks only the
+ * bits of the bitmask 0x3F00 if and only if the
+ * lower part 0x00FF is 0. This results the bits at 0x00C0 must
+ * be also zero to check the bits at 0x3F00.
+ *
+ * @param value The value to check the first bits
+ * @return The position of the first bit which is set
+ * @see FIND_FIRST_BIT
+ */
 static inline int FindFirstBit2x64(int value)
 {
 /*
@@ -131,9 +397,20 @@
 	} else {
 		return FIND_FIRST_BIT(GB(value, 0, 6));
 	}
-
 }
 
+/**
+ * Clear the first bit in an integer.
+ *
+ * This function returns a value where the first bit (from LSB)
+ * is cleared. This function checks, similar to FindFirstBit2x64,
+ * the bits at 0x3F3F.
+ *
+ * @param value The value to clear the first bit
+ * @return The new value with the first bit cleared
+ * @see KILL_FIRST_BIT
+ * @see FindFirstBit2x64
+ */
 static inline int KillFirstBit2x64(int value)
 {
 	if (GB(value, 0, 8) == 0) {
@@ -143,16 +420,77 @@
 	}
 }
 
-/** returns true if value a has only one bit set to 1 */
+/**
+ * Returns true if value a has only one bit set to 1
+ *
+ * This macro returns true if only one bit is set.
+ *
+ * @param a The value to check
+ * @return True if only one bit is set, false else
+ */
 #define HAS_SINGLE_BIT(a) ( ((a) & ((a) - 1)) == 0)
 
-/* [min,max), strictly less than */
+/**
+ * Checks if a byte is in an interval.
+ *
+ * This macro returns true if a byte value is in the interval of [min, max).
+ *
+ * @param a The byte value to check
+ * @param min The minimum of the interval
+ * @param max The maximum of the interval
+ * @see IS_INSIDE_1D
+ */
 #define IS_BYTE_INSIDE(a, min, max) ((byte)((a) - (min)) < (byte)((max) - (min)))
+
+/**
+ * Checks if an int is in an interval.
+ *
+ * This macro returns true if a integer value is in the interval of [min, max).
+ *
+ * @param a The integer value to check
+ * @param min The minimum of the interval
+ * @param max The maximum of the interval
+ * @see IS_INSIDE_1D
+ */
 #define IS_INT_INSIDE(a, min, max) ((uint)((a) - (min)) < (uint)((max) - (min)))
 
+/**
+ * Flips a coin with a given probability.
+ *
+ * This macro can be used to get true or false randomized according to a
+ * given probability. The parameter a and b create a percent value with
+ * (a/b). The macro returns true in (a/b) percent.
+ *
+ * @param a The numerator of the fraction
+ * @param b The denominator of the fraction, must of course not be null
+ * @return True in (a/b) percent
+ */
+#define CHANCE16(a, b) ((uint16)Random() <= (uint16)((65536 * (a)) / (b)))
 
-#define CHANCE16(a, b) ((uint16)Random() <= (uint16)((65536 * (a)) / (b)))
+/**
+ * Flips a coin with a given probability and saves the randomize-number in a variable.
+ *
+ * This macro uses the same parameters as the CHANCE16 marco. The third parameter
+ * must be a variable the randomize-number from Random() is saved in.
+ *
+ * @param a The numerator of the fraction, see CHANCE16
+ * @param b The denominator of the fraction, see CHANCE16
+ * @param r The variable to save the randomize-number from Random()
+ * @return True in (a/b) percent
+ */
 #define CHANCE16R(a, b, r) ((uint16)(r = Random()) <= (uint16)((65536 * (a)) / (b)))
+
+/**
+ * Checks if a given randomize-number is below a given probability.
+ *
+ * This macro is used to check if the given probability by the fraction of (a/b)
+ * is greater than the given randomize-number v.
+ *
+ * @param a The numerator of the fraction, see CHANCE16
+ * @param b The denominator of the fraction, see CHANCE16
+ * @param v The given randomize-number
+ * @return True if v is less or equals (a/b)
+ */
 #define CHANCE16I(a, b, v) ((uint16)(v) <= (uint16)((65536 * (a)) / (b)))
 
 
--- a/src/main_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/main_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -744,9 +744,9 @@
 	return w;
 }
 
-static Window *PopupMainPlayerToolbMenu(Window *w, int x, int main_button, int gray)
+static Window *PopupMainPlayerToolbMenu(Window *w, int main_button, int gray)
 {
-	x += w->left;
+	int x = w->widget[main_button].left + w->left;
 
 	LowerWindowWidget(w, main_button);
 	InvalidateWidget(w, main_button);
@@ -795,17 +795,17 @@
 
 static void ToolbarStationsClick(Window *w)
 {
-	PopupMainPlayerToolbMenu(w, 162, 7, 0);
+	PopupMainPlayerToolbMenu(w, 7, 0);
 }
 
 static void ToolbarMoneyClick(Window *w)
 {
-	PopupMainPlayerToolbMenu(w, 191, 8, 0);
+	PopupMainPlayerToolbMenu(w, 8, 0);
 }
 
 static void ToolbarPlayersClick(Window *w)
 {
-	PopupMainPlayerToolbMenu(w, 213, 9, 0);
+	PopupMainPlayerToolbMenu(w, 9, 0);
 }
 
 static void ToolbarGraphsClick(Window *w)
@@ -832,7 +832,7 @@
 	FOR_ALL_VEHICLES(v) {
 		if (v->type == VEH_TRAIN && IsFrontEngine(v)) CLRBIT(dis, v->owner);
 	}
-	PopupMainPlayerToolbMenu(w, 310, 13, dis);
+	PopupMainPlayerToolbMenu(w, 13, dis);
 }
 
 static void ToolbarRoadClick(Window *w)
@@ -843,7 +843,7 @@
 	FOR_ALL_VEHICLES(v) {
 		if (v->type == VEH_ROAD && IsRoadVehFront(v)) CLRBIT(dis, v->owner);
 	}
-	PopupMainPlayerToolbMenu(w, 332, 14, dis);
+	PopupMainPlayerToolbMenu(w, 14, dis);
 }
 
 static void ToolbarShipClick(Window *w)
@@ -854,7 +854,7 @@
 	FOR_ALL_VEHICLES(v) {
 		if (v->type == VEH_SHIP) CLRBIT(dis, v->owner);
 	}
-	PopupMainPlayerToolbMenu(w, 354, 15, dis);
+	PopupMainPlayerToolbMenu(w, 15, dis);
 }
 
 static void ToolbarAirClick(Window *w)
@@ -865,7 +865,7 @@
 	FOR_ALL_VEHICLES(v) {
 		if (v->type == VEH_AIRCRAFT) CLRBIT(dis, v->owner);
 	}
-	PopupMainPlayerToolbMenu(w, 376, 16, dis);
+	PopupMainPlayerToolbMenu(w, 16, dis);
 }
 
 /* Zooms a viewport in a window in or out */
@@ -1404,7 +1404,7 @@
 }
 
 static const WindowDesc _scen_edit_land_gen_desc = {
-	WDP_AUTO, WDP_AUTO, 182, 103,
+	WDP_AUTO, WDP_AUTO, 182, 103, 182, 103,
 	WC_SCEN_LAND_GEN, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
 	_scen_edit_land_gen_widgets,
@@ -1525,7 +1525,7 @@
 }
 
 static const WindowDesc _scen_edit_town_gen_desc = {
-	WDP_AUTO, WDP_AUTO, 160, 95,
+	WDP_AUTO, WDP_AUTO, 160, 95, 160, 95,
 	WC_SCEN_TOWN_GEN, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
 	_scen_edit_town_gen_widgets,
@@ -1649,7 +1649,13 @@
 		case WKC_SHIFT | WKC_F2: ShowVehicleListWindow(_local_player, VEH_ROAD); break;
 		case WKC_SHIFT | WKC_F3: ShowVehicleListWindow(_local_player, VEH_SHIP); break;
 		case WKC_SHIFT | WKC_F4: ShowVehicleListWindow(_local_player, VEH_AIRCRAFT); break;
+		case WKC_NUM_PLUS: // Fall through
+		case WKC_EQUALS: // Fall through
+		case WKC_SHIFT | WKC_EQUALS: // Fall through
 		case WKC_SHIFT | WKC_F5: ToolbarZoomInClick(w); break;
+		case WKC_NUM_MINUS: // Fall through
+		case WKC_MINUS: // Fall through
+		case WKC_SHIFT | WKC_MINUS: // Fall through
 		case WKC_SHIFT | WKC_F6: ToolbarZoomOutClick(w); break;
 		case WKC_SHIFT | WKC_F7: if (CanBuildVehicleInfrastructure(VEH_TRAIN)) ShowBuildRailToolbar(_last_built_railtype, -1); break;
 		case WKC_SHIFT | WKC_F8: ShowBuildRoadToolbar(_last_built_roadtype); break;
@@ -1660,8 +1666,10 @@
 		case WKC_CTRL  | 'S': MenuClickSmallScreenshot(); break;
 		case WKC_CTRL  | 'G': MenuClickWorldScreenshot(); break;
 		case WKC_CTRL | WKC_ALT | 'C': if (!_networking) ShowCheatWindow(); break;
-		case 'A': if (CanBuildVehicleInfrastructure(VEH_TRAIN)) ShowBuildRailToolbar(_last_built_railtype, 4); break; /* Invoke Autorail */
+		case 'A': if (CanBuildVehicleInfrastructure(VEH_TRAIN)) ShowBuildRailToolbar(_last_built_railtype, 4); break; // Invoke Autorail
 		case 'L': ShowTerraformToolbar(); break;
+		case 'M': ShowSmallMap(); break;
+		case 'V': ShowExtraViewPortWindow(); break;
 		default: return;
 		}
 		e->we.keypress.cont = false;
@@ -1688,6 +1696,33 @@
 		}
 		break;
 
+	case WE_RESIZE: {
+		/* There are 27 buttons plus some spacings if the space allows it */
+		uint button_width;
+		uint spacing;
+		if (w->width >= 27 * 22) {
+			button_width = 22;
+			spacing = w->width - (27 * button_width);
+		} else {
+			button_width = w->width / 27;
+			spacing = 0;
+		}
+		uint extra_spacing_at[] = { 4, 8, 13, 17, 19, 24, 0 };
+
+		for (uint i = 0, x = 0, j = 0; i < 27; i++) {
+			if (extra_spacing_at[j] == i) {
+				j++;
+				uint add = spacing / (lengthof(extra_spacing_at) - j);
+				spacing -= add;
+				x += add;
+			}
+
+			w->widget[i].left = x;
+			x += (spacing != 0) ? button_width : (w->width - x) / (27 - i);
+			w->widget[i].right = x - 1;
+		}
+	} break;
+
 	case WE_TIMEOUT: {
 		uint i;
 		for (i = 2; i < w->widget_count; i++) {
@@ -1706,44 +1741,44 @@
 }
 
 static const Widget _toolb_normal_widgets[] = {
-{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,    21,     0,    21, SPR_IMG_PAUSE,           STR_0171_PAUSE_GAME},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,    22,    43,     0,    21, SPR_IMG_FASTFORWARD,     STR_FAST_FORWARD},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,    44,    65,     0,    21, SPR_IMG_SETTINGS,        STR_0187_OPTIONS},
-{   WWT_IMGBTN_2,   RESIZE_NONE,    14,    66,    87,     0,    21, SPR_IMG_SAVE,            STR_0172_SAVE_GAME_ABANDON_GAME},
-
-{     WWT_IMGBTN,   RESIZE_NONE,    14,    96,   117,     0,    21, SPR_IMG_SMALLMAP,        STR_0174_DISPLAY_MAP},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   118,   139,     0,    21, SPR_IMG_TOWN,            STR_0176_DISPLAY_TOWN_DIRECTORY},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   140,   161,     0,    21, SPR_IMG_SUBSIDIES,       STR_02DC_DISPLAY_SUBSIDIES},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   162,   183,     0,    21, SPR_IMG_COMPANY_LIST,    STR_0173_DISPLAY_LIST_OF_COMPANY},
-
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   191,   212,     0,    21, SPR_IMG_COMPANY_FINANCE, STR_0177_DISPLAY_COMPANY_FINANCES},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   213,   235,     0,    21, SPR_IMG_COMPANY_GENERAL, STR_0178_DISPLAY_COMPANY_GENERAL},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   236,   257,     0,    21, SPR_IMG_GRAPHS,          STR_0179_DISPLAY_GRAPHS},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   258,   279,     0,    21, SPR_IMG_COMPANY_LEAGUE,  STR_017A_DISPLAY_COMPANY_LEAGUE},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   280,   301,     0,    21, SPR_IMG_INDUSTRY,        STR_0312_FUND_CONSTRUCTION_OF_NEW},
+{     WWT_IMGBTN,   RESIZE_LEFT,    14,     0,     0,     0,    21, SPR_IMG_PAUSE,           STR_0171_PAUSE_GAME},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_FASTFORWARD,     STR_FAST_FORWARD},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_SETTINGS,        STR_0187_OPTIONS},
+{   WWT_IMGBTN_2,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_SAVE,            STR_0172_SAVE_GAME_ABANDON_GAME},
 
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   310,   331,     0,    21, SPR_IMG_TRAINLIST,       STR_017B_DISPLAY_LIST_OF_COMPANY},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   332,   353,     0,    21, SPR_IMG_TRUCKLIST,       STR_017C_DISPLAY_LIST_OF_COMPANY},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   354,   375,     0,    21, SPR_IMG_SHIPLIST,        STR_017D_DISPLAY_LIST_OF_COMPANY},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   376,   397,     0,    21, SPR_IMG_AIRPLANESLIST,   STR_017E_DISPLAY_LIST_OF_COMPANY},
-
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   406,   427,     0,    21, SPR_IMG_ZOOMIN,          STR_017F_ZOOM_THE_VIEW_IN},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   428,   449,     0,    21, SPR_IMG_ZOOMOUT,         STR_0180_ZOOM_THE_VIEW_OUT},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_SMALLMAP,        STR_0174_DISPLAY_MAP},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_TOWN,            STR_0176_DISPLAY_TOWN_DIRECTORY},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_SUBSIDIES,       STR_02DC_DISPLAY_SUBSIDIES},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_COMPANY_LIST,    STR_0173_DISPLAY_LIST_OF_COMPANY},
 
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   457,   478,     0,    21, SPR_IMG_BUILDRAIL,       STR_0181_BUILD_RAILROAD_TRACK},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   479,   500,     0,    21, SPR_IMG_BUILDROAD,       STR_0182_BUILD_ROADS},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   501,   522,     0,    21, SPR_IMG_BUILDWATER,      STR_0183_BUILD_SHIP_DOCKS},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   523,   544,     0,    21, SPR_IMG_BUILDAIR,        STR_0184_BUILD_AIRPORTS},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   545,   566,     0,    21, SPR_IMG_LANDSCAPING,     STR_LANDSCAPING_TOOLBAR_TIP}, // tree icon is 0x2E6
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_COMPANY_FINANCE, STR_0177_DISPLAY_COMPANY_FINANCES},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_COMPANY_GENERAL, STR_0178_DISPLAY_COMPANY_GENERAL},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_GRAPHS,          STR_0179_DISPLAY_GRAPHS},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_COMPANY_LEAGUE,  STR_017A_DISPLAY_COMPANY_LEAGUE},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_INDUSTRY,        STR_0312_FUND_CONSTRUCTION_OF_NEW},
 
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   574,   595,     0,    21, SPR_IMG_MUSIC,           STR_01D4_SHOW_SOUND_MUSIC_WINDOW},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   596,   617,     0,    21, SPR_IMG_MESSAGES,        STR_0203_SHOW_LAST_MESSAGE_NEWS},
-{     WWT_IMGBTN,   RESIZE_NONE,    14,   618,   639,     0,    21, SPR_IMG_QUERY,           STR_0186_LAND_BLOCK_INFORMATION},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_TRAINLIST,       STR_017B_DISPLAY_LIST_OF_COMPANY},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_TRUCKLIST,       STR_017C_DISPLAY_LIST_OF_COMPANY},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_SHIPLIST,        STR_017D_DISPLAY_LIST_OF_COMPANY},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_AIRPLANESLIST,   STR_017E_DISPLAY_LIST_OF_COMPANY},
+
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_ZOOMIN,          STR_017F_ZOOM_THE_VIEW_IN},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_ZOOMOUT,         STR_0180_ZOOM_THE_VIEW_OUT},
+
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_BUILDRAIL,       STR_0181_BUILD_RAILROAD_TRACK},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_BUILDROAD,       STR_0182_BUILD_ROADS},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_BUILDWATER,      STR_0183_BUILD_SHIP_DOCKS},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_BUILDAIR,        STR_0184_BUILD_AIRPORTS},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_LANDSCAPING,     STR_LANDSCAPING_TOOLBAR_TIP}, // tree icon is 0x2E6
+
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_MUSIC,           STR_01D4_SHOW_SOUND_MUSIC_WINDOW},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_MESSAGES,        STR_0203_SHOW_LAST_MESSAGE_NEWS},
+{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,     0,     0,    21, SPR_IMG_QUERY,           STR_0186_LAND_BLOCK_INFORMATION},
 {   WIDGETS_END},
 };
 
 static const WindowDesc _toolb_normal_desc = {
-	0, 0, 640, 22,
+	0, 0, 0, 22, 640, 22,
 	WC_MAIN_TOOLBAR, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET,
 	_toolb_normal_widgets,
@@ -1752,28 +1787,28 @@
 
 
 static const Widget _toolb_scen_widgets[] = {
-{  WWT_IMGBTN, RESIZE_NONE, 14,   0,  21,  0, 21, SPR_IMG_PAUSE,       STR_0171_PAUSE_GAME},
-{  WWT_IMGBTN, RESIZE_NONE, 14,  22,  43,  0, 21, SPR_IMG_FASTFORWARD, STR_FAST_FORWARD},
-{  WWT_IMGBTN, RESIZE_NONE, 14,  44,  65,  0, 21, SPR_IMG_SETTINGS,    STR_0187_OPTIONS},
-{WWT_IMGBTN_2, RESIZE_NONE, 14,  66,  87,  0, 21, SPR_IMG_SAVE,        STR_0297_SAVE_SCENARIO_LOAD_SCENARIO},
-
-{   WWT_PANEL, RESIZE_NONE, 14,  96, 225,  0, 21, 0x0,                 STR_NULL},
-
-{   WWT_PANEL, RESIZE_NONE, 14, 233, 362,  0, 21, 0x0,                 STR_NULL},
-{  WWT_IMGBTN, RESIZE_NONE, 14, 236, 247,  5, 16, SPR_ARROW_DOWN,      STR_029E_MOVE_THE_STARTING_DATE},
-{  WWT_IMGBTN, RESIZE_NONE, 14, 347, 358,  5, 16, SPR_ARROW_UP,        STR_029F_MOVE_THE_STARTING_DATE},
+{  WWT_IMGBTN, RESIZE_LEFT, 14,   0,   0,  0, 21, SPR_IMG_PAUSE,       STR_0171_PAUSE_GAME},
+{  WWT_IMGBTN, RESIZE_NONE, 14,   0,   0,  0, 21, SPR_IMG_FASTFORWARD, STR_FAST_FORWARD},
+{  WWT_IMGBTN, RESIZE_NONE, 14,   0,   0,  0, 21, SPR_IMG_SETTINGS,    STR_0187_OPTIONS},
+{WWT_IMGBTN_2, RESIZE_NONE, 14,   0,   0,  0, 21, SPR_IMG_SAVE,        STR_0297_SAVE_SCENARIO_LOAD_SCENARIO},
 
-{  WWT_IMGBTN, RESIZE_NONE, 14, 371, 392,  0, 21, SPR_IMG_SMALLMAP,    STR_0175_DISPLAY_MAP_TOWN_DIRECTORY},
-
-{  WWT_IMGBTN, RESIZE_NONE, 14, 400, 421,  0, 21, SPR_IMG_ZOOMIN,      STR_017F_ZOOM_THE_VIEW_IN},
-{  WWT_IMGBTN, RESIZE_NONE, 14, 422, 443,  0, 21, SPR_IMG_ZOOMOUT,     STR_0180_ZOOM_THE_VIEW_OUT},
+{   WWT_PANEL, RESIZE_NONE, 14,   0,   0,  0, 21, 0x0,                 STR_NULL},
 
-{  WWT_IMGBTN, RESIZE_NONE, 14, 452, 473,  0, 21, SPR_IMG_LANDSCAPING, STR_022E_LANDSCAPE_GENERATION},
-{  WWT_IMGBTN, RESIZE_NONE, 14, 474, 495,  0, 21, SPR_IMG_TOWN,        STR_022F_TOWN_GENERATION},
-{  WWT_IMGBTN, RESIZE_NONE, 14, 496, 517,  0, 21, SPR_IMG_INDUSTRY,    STR_0230_INDUSTRY_GENERATION},
-{  WWT_IMGBTN, RESIZE_NONE, 14, 518, 539,  0, 21, SPR_IMG_BUILDROAD,   STR_0231_ROAD_CONSTRUCTION},
-{  WWT_IMGBTN, RESIZE_NONE, 14, 540, 561,  0, 21, SPR_IMG_PLANTTREES,  STR_0288_PLANT_TREES},
-{  WWT_IMGBTN, RESIZE_NONE, 14, 562, 583,  0, 21, SPR_IMG_SIGN,        STR_0289_PLACE_SIGN},
+{   WWT_PANEL, RESIZE_NONE, 14,   0, 129,  0, 21, 0x0,                 STR_NULL},
+{  WWT_IMGBTN, RESIZE_NONE, 14,   3,  14,  5, 16, SPR_ARROW_DOWN,      STR_029E_MOVE_THE_STARTING_DATE},
+{  WWT_IMGBTN, RESIZE_NONE, 14, 113, 125,  5, 16, SPR_ARROW_UP,        STR_029F_MOVE_THE_STARTING_DATE},
+
+{  WWT_IMGBTN, RESIZE_NONE, 14,   0,   0,  0, 21, SPR_IMG_SMALLMAP,    STR_0175_DISPLAY_MAP_TOWN_DIRECTORY},
+
+{  WWT_IMGBTN, RESIZE_NONE, 14,   0,   0,  0, 21, SPR_IMG_ZOOMIN,      STR_017F_ZOOM_THE_VIEW_IN},
+{  WWT_IMGBTN, RESIZE_NONE, 14,   0,   0,  0, 21, SPR_IMG_ZOOMOUT,     STR_0180_ZOOM_THE_VIEW_OUT},
+
+{  WWT_IMGBTN, RESIZE_NONE, 14,   0,   0,  0, 21, SPR_IMG_LANDSCAPING, STR_022E_LANDSCAPE_GENERATION},
+{  WWT_IMGBTN, RESIZE_NONE, 14,   0,   0,  0, 21, SPR_IMG_TOWN,        STR_022F_TOWN_GENERATION},
+{  WWT_IMGBTN, RESIZE_NONE, 14,   0,   0,  0, 21, SPR_IMG_INDUSTRY,    STR_0230_INDUSTRY_GENERATION},
+{  WWT_IMGBTN, RESIZE_NONE, 14,   0,   0,  0, 21, SPR_IMG_BUILDROAD,   STR_0231_ROAD_CONSTRUCTION},
+{  WWT_IMGBTN, RESIZE_NONE, 14,   0,   0,  0, 21, SPR_IMG_PLANTTREES,  STR_0288_PLANT_TREES},
+{  WWT_IMGBTN, RESIZE_NONE, 14,   0,   0,  0, 21, SPR_IMG_SIGN,        STR_0289_PLACE_SIGN},
 
 {   WWT_EMPTY, RESIZE_NONE,  0,   0,   0,  0,  0, 0x0,                 STR_NULL},
 {   WWT_EMPTY, RESIZE_NONE,  0,   0,   0,  0,  0, 0x0,                 STR_NULL},
@@ -1782,9 +1817,9 @@
 {   WWT_EMPTY, RESIZE_NONE,  0,   0,   0,  0,  0, 0x0,                 STR_NULL},
 {   WWT_EMPTY, RESIZE_NONE,  0,   0,   0,  0,  0, 0x0,                 STR_NULL},
 {   WWT_EMPTY, RESIZE_NONE,  0,   0,   0,  0,  0, 0x0,                 STR_NULL},
-{  WWT_IMGBTN, RESIZE_NONE, 14, 596, 617,  0, 21, SPR_IMG_MUSIC,       STR_01D4_SHOW_SOUND_MUSIC_WINDOW},
+{  WWT_IMGBTN, RESIZE_NONE, 14,   0,   0,  0, 21, SPR_IMG_MUSIC,       STR_01D4_SHOW_SOUND_MUSIC_WINDOW},
 {   WWT_EMPTY, RESIZE_NONE,  0,   0,   0,  0,  0, 0x0,                 STR_NULL},
-{  WWT_IMGBTN, RESIZE_NONE, 14, 618, 639,  0, 21, SPR_IMG_QUERY,       STR_0186_LAND_BLOCK_INFORMATION},
+{  WWT_IMGBTN, RESIZE_NONE, 14,   0,   0,  0, 21, SPR_IMG_QUERY,       STR_0186_LAND_BLOCK_INFORMATION},
 {WIDGETS_END},
 };
 
@@ -1832,11 +1867,13 @@
 		DrawWindowWidgets(w);
 
 		SetDParam(0, ConvertYMDToDate(_patches_newgame.starting_year, 0, 1));
-		DrawStringCentered(298, 6, STR_00AF, 0);
+		DrawStringCenteredTruncated(w->widget[6].right, w->widget[7].left, 6, STR_00AF, 0);
 
-		SetDParam(0, ConvertYMDToDate(_patches_newgame.starting_year, 0, 1));
-		DrawStringCentered(161, 1, STR_0221_OPENTTD, 0);
-		DrawStringCentered(161, 11,STR_0222_SCENARIO_EDITOR, 0);
+		/* We hide this panel when the toolbar space gets too small */
+		if (w->widget[4].left != w->widget[4].right) {
+			DrawStringCenteredTruncated(w->widget[4].left + 1, w->widget[4].right - 1,  1, STR_0221_OPENTTD, 0);
+			DrawStringCenteredTruncated(w->widget[4].left + 1, w->widget[4].right - 1, 11, STR_0222_SCENARIO_EDITOR, 0);
+		}
 
 		break;
 
@@ -1875,6 +1912,72 @@
 		SetWindowDirty(w);
 	} break;
 
+	case WE_RESIZE: {
+		/* There are 15 buttons plus some spacings if the space allows it.
+		 * Furthermore there are two panels of which one is non-essential
+		 * and that one can be removed is the space is too small. */
+		uint buttons_width;
+		uint spacing;
+
+		static int normal_min_width = (15 * 22) + (2 * 130);
+		static int one_less_panel_min_width = (15 * 22) + 130;
+
+		if (w->width >= one_less_panel_min_width) {
+			buttons_width = 15 * 22;
+			spacing = w->width - ((w->width >= normal_min_width) ? normal_min_width : one_less_panel_min_width);
+		} else {
+			buttons_width = w->width - 130;
+			spacing = 0;
+		}
+		uint extra_spacing_at[] = { 3, 4, 7, 8, 10, 16, 0 };
+
+		/* Yes, it defines about 27 widgets for this toolbar */
+		for (uint i = 0, x = 0, j = 0, b = 0; i < 27; i++) {
+			switch (i) {
+				case 4:
+					w->widget[i].left = x;
+					if (w->width < normal_min_width) {
+						w->widget[i].right = x;
+						j++;
+						continue;
+					}
+
+					x += 130;
+					w->widget[i].right = x - 1;
+					break;
+
+				case 5: {
+					int offset = x - w->widget[i].left;
+					w->widget[i + 1].left  += offset;
+					w->widget[i + 1].right += offset;
+					w->widget[i + 2].left  += offset;
+					w->widget[i + 2].right += offset;
+					w->widget[i].left = x;
+					x += 130;
+					w->widget[i].right = x - 1;
+					i += 2;
+				} break;
+
+				default:
+					if (w->widget[i].bottom == 0) continue;
+
+					w->widget[i].left = x;
+					x += buttons_width / (15 - b);
+					w->widget[i].right = x - 1;
+					buttons_width -= buttons_width / (15 - b);
+					b++;
+					break;
+			}
+
+			if (extra_spacing_at[j] == i) {
+				j++;
+				uint add = spacing / (lengthof(extra_spacing_at) - j);
+				spacing -= add;
+				x += add;
+			}
+		}
+	} break;
+
 	case WE_MOUSELOOP:
 		if (IsWindowWidgetLowered(w, 0) != !!_pause_game) {
 			ToggleWidgetLoweredState(w, 0);
@@ -1894,7 +1997,7 @@
 }
 
 static const WindowDesc _toolb_scen_desc = {
-	0, 0, 640, 22,
+	0, 0, 130, 22, 640, 22,
 	WC_MAIN_TOOLBAR, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_toolb_scen_widgets,
@@ -1904,7 +2007,7 @@
 extern GetNewsStringCallbackProc * const _get_news_string_callback[];
 
 
-static bool DrawScrollingStatusText(const NewsItem *ni, int pos)
+static bool DrawScrollingStatusText(const NewsItem *ni, int pos, int width)
 {
 	char buf[512];
 	StringID str;
@@ -1939,7 +2042,7 @@
 		}
 	}
 
-	if (!FillDrawPixelInfo(&tmp_dpi, 141, 1, 358, 11)) return true;
+	if (!FillDrawPixelInfo(&tmp_dpi, 141, 1, width, 11)) return true;
 
 	old_dpi = _cur_dpi;
 	_cur_dpi = &tmp_dpi;
@@ -1965,29 +2068,35 @@
 		if (p != NULL) {
 			/* Draw player money */
 			SetDParam(0, p->player_money);
-			DrawStringCentered(570, 1, p->player_money >= 0 ? STR_0004 : STR_0005, 0);
+			DrawStringCentered(w->widget[2].left + 70, 1, p->player_money >= 0 ? STR_0004 : STR_0005, 0);
 		}
 
 		/* Draw status bar */
 		if (w->message.msg) { // true when saving is active
-			DrawStringCentered(320, 1, STR_SAVING_GAME, 0);
+			DrawStringCenteredTruncated(w->widget[1].left + 1, w->widget[1].right - 1, 1, STR_SAVING_GAME, 0);
 		} else if (_do_autosave) {
-			DrawStringCentered(320, 1, STR_032F_AUTOSAVE, 0);
+			DrawStringCenteredTruncated(w->widget[1].left + 1, w->widget[1].right - 1, 1, STR_032F_AUTOSAVE, 0);
 		} else if (_pause_game) {
-			DrawStringCentered(320, 1, STR_0319_PAUSED, 0);
+			DrawStringCenteredTruncated(w->widget[1].left + 1, w->widget[1].right - 1, 1, STR_0319_PAUSED, 0);
 		} else if (WP(w,def_d).data_1 > -1280 && FindWindowById(WC_NEWS_WINDOW,0) == NULL && _statusbar_news_item.string_id != 0) {
 			/* Draw the scrolling news text */
-			if (!DrawScrollingStatusText(&_statusbar_news_item, WP(w,def_d).data_1))
+			if (!DrawScrollingStatusText(&_statusbar_news_item, WP(w,def_d).data_1, w->widget[1].right - w->widget[1].left - 2)) {
 				WP(w,def_d).data_1 = -1280;
+				if (p != NULL) {
+					/* This is the default text */
+					SetDParam(0, p->index);
+					DrawStringCenteredTruncated(w->widget[1].left + 1, w->widget[1].right - 1, 1, STR_02BA, 0);
+				}
+			}
 		} else {
 			if (p != NULL) {
 				/* This is the default text */
 				SetDParam(0, p->index);
-				DrawStringCentered(320, 1, STR_02BA, 0);
+				DrawStringCenteredTruncated(w->widget[1].left + 1, w->widget[1].right - 1, 1, STR_02BA, 0);
 			}
 		}
 
-		if (WP(w, def_d).data_2 > 0) DrawSprite(SPR_BLOT, PALETTE_TO_RED, 489, 2);
+		if (WP(w, def_d).data_2 > 0) DrawSprite(SPR_BLOT, PALETTE_TO_RED, w->widget[1].right - 11, 2);
 	} break;
 
 	case WE_MESSAGE:
@@ -2025,13 +2134,13 @@
 
 static const Widget _main_status_widgets[] = {
 {      WWT_PANEL,   RESIZE_NONE,    14,     0,   139,     0,    11, 0x0, STR_NULL},
-{    WWT_PUSHBTN,   RESIZE_NONE,    14,   140,   499,     0,    11, 0x0, STR_02B7_SHOW_LAST_MESSAGE_OR_NEWS},
-{    WWT_PUSHBTN,   RESIZE_NONE,    14,   500,   639,     0,    11, 0x0, STR_NULL},
+{    WWT_PUSHBTN,   RESIZE_RIGHT,   14,   140,   179,     0,    11, 0x0, STR_02B7_SHOW_LAST_MESSAGE_OR_NEWS},
+{    WWT_PUSHBTN,   RESIZE_LR,      14,   180,   319,     0,    11, 0x0, STR_NULL},
 {   WIDGETS_END},
 };
 
 static WindowDesc _main_status_desc = {
-	WDP_CENTER, 0, 640, 12,
+	WDP_CENTER, 0, 320, 12, 640, 12,
 	WC_STATUS_BAR, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_main_status_widgets,
--- a/src/map.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/map.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -282,7 +282,7 @@
 		n = 2;
 		if (proc(TileXY(x, y), data)) return true;
 
-		/* If tile test is not successfull, get one tile down and left,
+		/* If tile test is not successful, get one tile down and left,
 		 * ready for a test in first circle around center tile */
 		x += _tileoffs_by_dir[DIR_W].x;
 		y += _tileoffs_by_dir[DIR_W].y;
@@ -300,7 +300,7 @@
 			uint j;
 			for (j = n; j != 0; j--) {
 				if (x <= MapMaxX() && y <= MapMaxY() && ///< Is the tile within the map?
-						proc(TileXY(x, y), data)) {     ///< Is the callback successfulll?
+						proc(TileXY(x, y), data)) {     ///< Is the callback successful?
 					return true;                        ///< then stop the search
 				}
 
--- a/src/map.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/map.h	Fri Aug 03 18:10:15 2007 +0000
@@ -6,6 +6,7 @@
 #define MAP_H
 
 #include "stdafx.h"
+#include "direction.h"
 
 extern uint _map_tile_mask;
 
@@ -190,17 +191,19 @@
 
 uint TileAddWrap(TileIndex tile, int addx, int addy);
 
-static inline TileIndexDiffC TileIndexDiffCByDiagDir(uint dir) {
-	extern const TileIndexDiffC _tileoffs_by_diagdir[4];
+static inline TileIndexDiffC TileIndexDiffCByDiagDir(DiagDirection dir)
+{
+	extern const TileIndexDiffC _tileoffs_by_diagdir[DIAGDIR_END];
 
-	assert(dir < lengthof(_tileoffs_by_diagdir));
+	assert(IsValidDiagDirection(dir));
 	return _tileoffs_by_diagdir[dir];
 }
 
 /* Returns tile + the diff given in diff. If the result tile would end up
  * outside of the map, INVALID_TILE is returned instead.
  */
-static inline TileIndex AddTileIndexDiffCWrap(TileIndex tile, TileIndexDiffC diff) {
+static inline TileIndex AddTileIndexDiffCWrap(TileIndex tile, TileIndexDiffC diff)
+{
 	int x = TileX(tile) + diff.x;
 	int y = TileY(tile) + diff.y;
 	if (x < 0 || y < 0 || x > (int)MapMaxX() || y > (int)MapMaxY())
@@ -247,19 +250,19 @@
 		} while (var += TileDiffXY(0, 1) - (w), --h_cur != 0); \
 	}
 
-static inline TileIndexDiff TileOffsByDiagDir(uint dir)
+static inline TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
 {
-	extern const TileIndexDiffC _tileoffs_by_diagdir[4];
+	extern const TileIndexDiffC _tileoffs_by_diagdir[DIAGDIR_END];
 
-	assert(dir < lengthof(_tileoffs_by_diagdir));
+	assert(IsValidDiagDirection(dir));
 	return ToTileIndexDiff(_tileoffs_by_diagdir[dir]);
 }
 
-static inline TileIndexDiff TileOffsByDir(uint dir)
+static inline TileIndexDiff TileOffsByDir(Direction dir)
 {
-	extern const TileIndexDiffC _tileoffs_by_dir[8];
+	extern const TileIndexDiffC _tileoffs_by_dir[DIR_END];
 
-	assert(dir < lengthof(_tileoffs_by_dir));
+	assert(IsValidDirection(dir));
 	return ToTileIndexDiff(_tileoffs_by_dir[dir]);
 }
 
--- a/src/misc_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/misc_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -77,7 +77,7 @@
 };
 
 static const WindowDesc _land_info_desc = {
-	WDP_AUTO, WDP_AUTO, 280, 93,
+	WDP_AUTO, WDP_AUTO, 280, 93, 280, 93,
 	WC_LAND_INFO, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_land_info_widgets,
@@ -134,7 +134,7 @@
 	GetString(_landinfo_data[3], STR_LANDINFO_COORDS, lastof(_landinfo_data[3]));
 
 	SetDParam(0, STR_01A9_NONE);
-	if (t != NULL && IsValidTown(t)) {
+	if (t != NULL && t->IsValid()) {
 		SetDParam(0, STR_TOWN);
 		SetDParam(1, t->index);
 	}
@@ -298,7 +298,7 @@
 };
 
 static const WindowDesc _about_desc = {
-	WDP_CENTER, WDP_CENTER, 420, 272,
+	WDP_CENTER, WDP_CENTER, 420, 272, 420, 272,
 	WC_GAME_OPTIONS, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_about_widgets,
@@ -430,7 +430,7 @@
 };
 
 static const WindowDesc _build_trees_desc = {
-	497, 22, 143, 171,
+	497, 22, 143, 171, 143, 171,
 	WC_BUILD_TREES, WC_SCEN_LAND_GEN,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_build_trees_widgets,
@@ -459,7 +459,7 @@
 };
 
 static const WindowDesc _build_trees_scen_desc = {
-	WDP_AUTO, WDP_AUTO, 143, 184,
+	WDP_AUTO, WDP_AUTO, 143, 184, 143, 184,
 	WC_BUILD_TREES, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_build_trees_scen_widgets,
@@ -786,7 +786,8 @@
 	DrawStringMultiLine(str_x, str_y, STR_SPEC_USERSTRING, 144);
 }
 
-void DrawStationCoverageAreaText(int sx, int sy, StationCoverageType sct, int rad) {
+void DrawStationCoverageAreaText(int sx, int sy, StationCoverageType sct, int rad)
+{
 	TileIndex tile = TileVirtXY(_thd.pos.x, _thd.pos.y);
 	AcceptedCargo accepts;
 	if (tile < MapSize()) {
@@ -858,7 +859,7 @@
  * The character is delete from the position the caret is at
  * @param tb Textbuf type to be changed
  * @param delmode Type of deletion, either WKC_BACKSPACE or WKC_DELETE
- * @return Return true on successfull change of Textbuf, or false otherwise
+ * @return Return true on successful change of Textbuf, or false otherwise
  */
 bool DeleteTextBufferChar(Textbuf *tb, int delmode)
 {
@@ -890,7 +891,7 @@
  * length of the string
  * @param tb Textbuf type to be changed
  * @param key Character to be inserted
- * @return Return true on successfull change of Textbuf, or false otherwise
+ * @return Return true on successful change of Textbuf, or false otherwise
  */
 bool InsertTextBufferChar(Textbuf *tb, WChar key)
 {
@@ -914,7 +915,7 @@
  * This defines where the caret will blink and the next characer interaction will occur
  * @param tb Textbuf type where navigation occurs
  * @param navmode Direction in which navigation occurs WKC_LEFT, WKC_RIGHT, WKC_END, WKC_HOME
- * @return Return true on successfull change of Textbuf, or false otherwise
+ * @return Return true on successful change of Textbuf, or false otherwise
  */
 bool MoveTextBufferPos(Textbuf *tb, int navmode)
 {
@@ -1165,7 +1166,7 @@
 };
 
 static const WindowDesc _query_string_desc = {
-	190, 219, 260, 42,
+	190, 219, 260, 42, 260, 42,
 	WC_QUERY_STRING, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_query_string_widgets,
@@ -1289,7 +1290,7 @@
 };
 
 static const WindowDesc _query_desc = {
-	WDP_CENTER, WDP_CENTER, 210, 82,
+	WDP_CENTER, WDP_CENTER, 210, 82, 210, 82,
 	WC_CONFIRM_POPUP_QUERY, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_DEF_WIDGET | WDF_MODAL,
 	_query_widgets,
@@ -1330,11 +1331,11 @@
 { WWT_PUSHTXTBTN,   RESIZE_NONE,    14,     0,   127,    14,    25, STR_SORT_BY_NAME, STR_SORT_ORDER_TIP},
 { WWT_PUSHTXTBTN,   RESIZE_NONE,    14,   128,   256,    14,    25, STR_SORT_BY_DATE, STR_SORT_ORDER_TIP},
 {      WWT_PANEL,  RESIZE_RIGHT,    14,     0,   256,    26,    47, 0x0,              STR_NULL},
-{      WWT_PANEL,     RESIZE_RB,    14,     0,   256,    48,   293, 0x0,              STR_NULL},
+{      WWT_PANEL,     RESIZE_RB,    14,     0,   256,    48,   153, 0x0,              STR_NULL},
 { WWT_PUSHIMGBTN,     RESIZE_LR,    14,   245,   256,    48,    59, SPR_HOUSE_ICON,   STR_SAVELOAD_HOME_BUTTON},
-{      WWT_INSET,     RESIZE_RB,    14,     2,   243,    50,   291, 0x0,              STR_400A_LIST_OF_DRIVES_DIRECTORIES},
-{  WWT_SCROLLBAR,    RESIZE_LRB,    14,   245,   256,    60,   281, 0x0,              STR_0190_SCROLL_BAR_SCROLLS_LIST},
-{  WWT_RESIZEBOX,   RESIZE_LRTB,    14,   245,   256,   282,   293, 0x0,              STR_RESIZE_BUTTON},
+{      WWT_INSET,     RESIZE_RB,    14,     2,   243,    50,   151, 0x0,              STR_400A_LIST_OF_DRIVES_DIRECTORIES},
+{  WWT_SCROLLBAR,    RESIZE_LRB,    14,   245,   256,    60,   141, 0x0,              STR_0190_SCROLL_BAR_SCROLLS_LIST},
+{  WWT_RESIZEBOX,   RESIZE_LRTB,    14,   245,   256,   142,   153, 0x0,              STR_RESIZE_BUTTON},
 {   WIDGETS_END},
 };
 
@@ -1344,15 +1345,15 @@
 { WWT_PUSHTXTBTN,   RESIZE_NONE,    14,     0,   127,    14,    25, STR_SORT_BY_NAME, STR_SORT_ORDER_TIP},
 { WWT_PUSHTXTBTN,   RESIZE_NONE,    14,   128,   256,    14,    25, STR_SORT_BY_DATE, STR_SORT_ORDER_TIP},
 {      WWT_PANEL,  RESIZE_RIGHT,    14,     0,   256,    26,    47, 0x0,              STR_NULL},
-{      WWT_PANEL,     RESIZE_RB,    14,     0,   256,    48,   291, 0x0,              STR_NULL},
+{      WWT_PANEL,     RESIZE_RB,    14,     0,   256,    48,   151, 0x0,              STR_NULL},
 { WWT_PUSHIMGBTN,     RESIZE_LR,    14,   245,   256,    48,    59, SPR_HOUSE_ICON,   STR_SAVELOAD_HOME_BUTTON},
-{      WWT_INSET,     RESIZE_RB,    14,     2,   243,    50,   290, 0x0,              STR_400A_LIST_OF_DRIVES_DIRECTORIES},
-{  WWT_SCROLLBAR,    RESIZE_LRB,    14,   245,   256,    60,   291, 0x0,              STR_0190_SCROLL_BAR_SCROLLS_LIST},
-{      WWT_PANEL,    RESIZE_RTB,    14,     0,   256,   292,   307, 0x0,              STR_NULL},
-{      WWT_PANEL,    RESIZE_RTB,    14,     2,   254,   294,   305, 0x0,              STR_400B_CURRENTLY_SELECTED_NAME},
-{ WWT_PUSHTXTBTN,     RESIZE_TB,    14,     0,   127,   308,   319, STR_4003_DELETE,  STR_400C_DELETE_THE_CURRENTLY_SELECTED},
-{ WWT_PUSHTXTBTN,     RESIZE_TB,    14,   128,   244,   308,   319, STR_4002_SAVE,    STR_400D_SAVE_THE_CURRENT_GAME_USING},
-{  WWT_RESIZEBOX,   RESIZE_LRTB,    14,   245,   256,   308,   319, 0x0,              STR_RESIZE_BUTTON},
+{      WWT_INSET,     RESIZE_RB,    14,     2,   243,    50,   150, 0x0,              STR_400A_LIST_OF_DRIVES_DIRECTORIES},
+{  WWT_SCROLLBAR,    RESIZE_LRB,    14,   245,   256,    60,   151, 0x0,              STR_0190_SCROLL_BAR_SCROLLS_LIST},
+{      WWT_PANEL,    RESIZE_RTB,    14,     0,   256,   152,   167, 0x0,              STR_NULL},
+{      WWT_PANEL,    RESIZE_RTB,    14,     2,   254,   154,   165, 0x0,              STR_400B_CURRENTLY_SELECTED_NAME},
+{ WWT_PUSHTXTBTN,     RESIZE_TB,    14,     0,   127,   168,   179, STR_4003_DELETE,  STR_400C_DELETE_THE_CURRENTLY_SELECTED},
+{ WWT_PUSHTXTBTN,     RESIZE_TB,    14,   128,   244,   168,   179, STR_4002_SAVE,    STR_400D_SAVE_THE_CURRENT_GAME_USING},
+{  WWT_RESIZEBOX,   RESIZE_LRTB,    14,   245,   256,   168,   179, 0x0,              STR_RESIZE_BUTTON},
 {   WIDGETS_END},
 };
 
@@ -1436,6 +1437,10 @@
 
 	switch (e->event) {
 	case WE_CREATE: // Set up OPENTTD button
+		w->vscroll.cap = 10;
+		w->resize.step_width = 2;
+		w->resize.step_height = 10;
+
 		o_dir.type = FIOS_TYPE_DIRECT;
 		switch (_saveload_mode) {
 			case SLD_SAVE_GAME:
@@ -1584,7 +1589,7 @@
 				ShowErrorMessage(INVALID_STRING_ID, STR_4008_UNABLE_TO_DELETE_FILE, 0, 0);
 			} else {
 				BuildFileList();
-				/* Reset file name to current date on successfull delete */
+				/* Reset file name to current date on successful delete */
 				if (_saveload_mode == SLD_SAVE_GAME) GenerateFileName();
 			}
 
@@ -1626,7 +1631,7 @@
 }
 
 static const WindowDesc _load_dialog_desc = {
-	WDP_CENTER, WDP_CENTER, 257, 294,
+	WDP_CENTER, WDP_CENTER, 257, 154, 257, 294,
 	WC_SAVELOAD, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
 	_load_dialog_widgets,
@@ -1634,7 +1639,7 @@
 };
 
 static const WindowDesc _save_dialog_desc = {
-	WDP_CENTER, WDP_CENTER, 257, 320,
+	WDP_CENTER, WDP_CENTER, 257, 180, 257, 320,
 	WC_SAVELOAD, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
 	_save_dialog_widgets,
@@ -1671,10 +1676,6 @@
 	assert((uint)mode < lengthof(saveload_captions));
 	w = AllocateWindowDesc(sld);
 	w->widget[1].data = saveload_captions[mode];
-	w->vscroll.cap = 24;
-	w->resize.step_width = 2;
-	w->resize.step_height = 10;
-	w->resize.height = w->height - 14 * 10; // Minimum of 10 items
 	LowerWindowWidget(w, 7);
 
 	WP(w, querystr_d).afilter = CS_ALPHANUMERAL;
@@ -1951,7 +1952,7 @@
 }
 
 static const WindowDesc _cheats_desc = {
-	240, 22, 400, 170,
+	240, 22, 400, 170, 400, 170,
 	WC_CHEATS, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_cheat_widgets,
--- a/src/mixer.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/mixer.h	Fri Aug 03 18:10:15 2007 +0000
@@ -15,9 +15,9 @@
 };
 
 bool MxInitialize(uint rate);
-void MxMixSamples(void* buffer, uint samples);
+void MxMixSamples(void *buffer, uint samples);
 
-MixerChannel* MxAllocateChannel();
+MixerChannel *MxAllocateChannel();
 void MxSetChannelRawSrc(MixerChannel *mc, int8 *mem, uint size, uint rate, uint flags);
 void MxSetChannelVolume(MixerChannel *mc, uint left, uint right);
 void MxActivateChannel(MixerChannel*);
--- a/src/music_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/music_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -322,7 +322,7 @@
 };
 
 static const WindowDesc _music_track_selection_desc = {
-	104, 131, 432, 218,
+	104, 131, 432, 218, 432, 218,
 	WC_MUSIC_TRACK_SELECTION, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_music_track_selection_widgets,
@@ -490,7 +490,7 @@
 };
 
 static const WindowDesc _music_window_desc = {
-	0, 22, 300, 66,
+	0, 22, 300, 66, 300, 66,
 	WC_MUSIC_WINDOW, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_music_window_widgets,
--- a/src/network/core/udp.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/network/core/udp.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -110,6 +110,7 @@
 	client_len = sizeof(client_addr);
 
 	/* Try to receive anything */
+	SetNonBlocking(this->sock); // Some OSes seem to loose the non-blocking status of the socket
 	nbytes = recvfrom(this->sock, (char*)p.buffer, packet_len, 0, (struct sockaddr *)&client_addr, &client_len);
 
 	/* We got some bytes for the base header of the packet. */
--- a/src/network/network_gamelist.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/network/network_gamelist.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -18,9 +18,6 @@
 
 NetworkGameList *_network_game_list = NULL;
 
-/** Should we stop/contiue requerying of offline servers? */
-static bool _stop_requerying = false;
-
 /** Add a new item to the linked gamelist. If the IP and Port match
  * return the existing item instead of adding it again
  * @param ip the IP-address (inet_addr) of the to-be added item
@@ -50,7 +47,6 @@
 	DEBUG(net, 4, "[gamelist] added server to list");
 
 	UpdateNetworkGameWindow(false);
-	_stop_requerying = false;
 
 	return item;
 }
@@ -84,8 +80,9 @@
 }
 
 enum {
-	MAX_GAME_LIST_REQUERY_COUNT =  5,
-	REQUERY_EVERY_X_GAMELOOPS   = 60,
+	MAX_GAME_LIST_REQUERY_COUNT  =  5, ///< How often do we requery in number of times per server?
+	REQUERY_EVERY_X_GAMELOOPS    = 60, ///< How often do we requery in time?
+	REFRESH_GAMEINFO_X_REQUERIES = 50, ///< Refresh the game info itself after REFRESH_GAMEINFO_X_REQUERIES * REQUERY_EVERY_X_GAMELOOPS game loops
 };
 
 /** Requeries the (game) servers we have not gotten a reply from */
@@ -93,27 +90,23 @@
 {
 	static uint8 requery_cnt = 0;
 
-	if (_stop_requerying || ++requery_cnt < REQUERY_EVERY_X_GAMELOOPS) return;
-
+	if (++requery_cnt < REQUERY_EVERY_X_GAMELOOPS) return;
 	requery_cnt = 0;
-	_stop_requerying = true;
 
 	struct in_addr ip;
 	NetworkGameList *item;
 
 	for (item = _network_game_list; item != NULL; item = item->next) {
-		if (item->online || item->retries >= MAX_GAME_LIST_REQUERY_COUNT) continue;
+		item->retries++;
+		if (item->retries < REFRESH_GAMEINFO_X_REQUERIES && (item->online || item->retries >= MAX_GAME_LIST_REQUERY_COUNT)) continue;
 
 		ip.s_addr = item->ip;
 
 		/* item gets mostly zeroed by NetworkUDPQueryServer */
 		uint8 retries = item->retries;
 		NetworkUDPQueryServer(inet_ntoa(ip), item->port);
-		item->retries = retries + 1;
-
-		_stop_requerying = false;
+		item->retries = (retries >= REFRESH_GAMEINFO_X_REQUERIES) ? 0 : retries;
 	}
-
 }
 
 #endif /* ENABLE_NETWORK */
--- a/src/network/network_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/network/network_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -87,7 +87,8 @@
 
 static StringID _language_dropdown[NETLANG_COUNT + 1] = {STR_NULL};
 
-void SortNetworkLanguages() {
+void SortNetworkLanguages()
+{
 	/* Init the strings */
 	if (_language_dropdown[0] == STR_NULL) {
 		for (int i = 0; i < NETLANG_COUNT; i++) _language_dropdown[i] = STR_NETWORK_LANG_ANY + i;
@@ -230,6 +231,9 @@
 
 	switch (e->event) {
 	case WE_CREATE: /* Focus input box */
+		w->vscroll.cap = 13;
+		w->resize.step_height = NET_PRC__SIZE_OF_ROW;
+
 		nd->field = 3;
 		nd->server = NULL;
 
@@ -266,7 +270,7 @@
 		DrawEditBox(w, &WP(w, network_ql_d).q, 3);
 
 		DrawString(9, 23, STR_NETWORK_CONNECTION, 2);
-		DrawString(210, 23, STR_NETWORK_PLAYER_NAME, 2);
+		DrawString(w->widget[3].left - 100, 23, STR_NETWORK_PLAYER_NAME, 2);
 
 		/* Sort based on widgets: name, clients, compatibility */
 		switch (ld->sort_type) {
@@ -298,7 +302,7 @@
 				SetDParam(1, cur_item->info.clients_max);
 				SetDParam(2, cur_item->info.companies_on);
 				SetDParam(3, cur_item->info.companies_max);
-				DrawStringCentered(210, y, STR_NETWORK_GENERAL_ONLINE, 2);
+				DrawStringCentered(w->widget[7].left + 39, y, STR_NETWORK_GENERAL_ONLINE, 2);
 
 				// only draw icons if the server is online
 				if (cur_item->online) {
@@ -319,19 +323,19 @@
 		}
 
 		/* Draw the right menu */
-		GfxFillRect(311, 43, 539, 92, 157);
+		GfxFillRect(w->widget[15].left + 1, 43, w->widget[15].right - 1, 92, 157);
 		if (sel == NULL) {
-			DrawStringCentered(425, 58, STR_NETWORK_GAME_INFO, 0);
+			DrawStringCentered(w->widget[15].left + 115, 58, STR_NETWORK_GAME_INFO, 0);
 		} else if (!sel->online) {
 			SetDParamStr(0, sel->info.server_name);
-			DrawStringCentered(425, 68, STR_ORANGE, 0); // game name
+			DrawStringCentered(w->widget[15].left + 115, 68, STR_ORANGE, 0); // game name
 
-			DrawStringCentered(425, 132, STR_NETWORK_SERVER_OFFLINE, 0); // server offline
+			DrawStringCentered(w->widget[15].left + 115, 132, STR_NETWORK_SERVER_OFFLINE, 0); // server offline
 		} else { // show game info
 			uint16 y = 100;
 			const uint16 x = w->widget[15].left + 5;
 
-			DrawStringCentered(425, 48, STR_NETWORK_GAME_INFO, 0);
+			DrawStringCentered(w->widget[15].left + 115, 48, STR_NETWORK_GAME_INFO, 0);
 
 
 			SetDParamStr(0, sel->info.server_name);
@@ -380,12 +384,12 @@
 			y += 2;
 
 			if (!sel->info.compatible) {
-				DrawStringCentered(425, y, sel->info.version_compatible ? STR_NETWORK_GRF_MISMATCH : STR_NETWORK_VERSION_MISMATCH, 0); // server mismatch
+				DrawStringCentered(w->widget[15].left + 115, y, sel->info.version_compatible ? STR_NETWORK_GRF_MISMATCH : STR_NETWORK_VERSION_MISMATCH, 0); // server mismatch
 			} else if (sel->info.clients_on == sel->info.clients_max) {
 				// Show: server full, when clients_on == clients_max
-				DrawStringCentered(425, y, STR_NETWORK_SERVER_FULL, 0); // server full
+				DrawStringCentered(w->widget[15].left + 115, y, STR_NETWORK_SERVER_FULL, 0); // server full
 			} else if (sel->info.use_password) {
-				DrawStringCentered(425, y, STR_NETWORK_PASSWORD, 0); // password warning
+				DrawStringCentered(w->widget[15].left + 115, y, STR_NETWORK_PASSWORD, 0); // password warning
 			}
 
 			y += 10;
@@ -395,7 +399,7 @@
 	case WE_CLICK:
 		nd->field = e->we.click.widget;
 		switch (e->we.click.widget) {
-		case 0: case 14: /* Close 'X' | Cancel button */
+		case 14: // Cancel button
 			DeleteWindowById(WC_NETWORK_WINDOW, 0);
 			break;
 		case 4: case 5:
@@ -507,6 +511,23 @@
 		NetworkRebuildHostList();
 		break;
 
+	case WE_RESIZE: {
+		w->vscroll.cap += e->we.sizing.diff.y / (int)w->resize.step_height;
+
+		w->widget[9].data = (w->vscroll.cap << 8) + 1;
+
+		int widget_width = w->widget[11].right - w->widget[11].left;
+		int space = (w->width - 4 * widget_width - 25) / 3;
+
+		int offset = 10;
+		for (uint i = 0; i < 4; i++) {
+			w->widget[11 + i].left  = offset;
+			offset += widget_width;
+			w->widget[11 + i].right = offset;
+			offset += space;
+		}
+	} break;
+
 	case WE_DESTROY: /* Nicely clean up the sort-list */
 		free(WP(w, network_ql_d).sort_list);
 		break;
@@ -515,43 +536,45 @@
 
 static const Widget _network_game_window_widgets[] = {
 {   WWT_CLOSEBOX,   RESIZE_NONE,   BGC,     0,    10,     0,    13, STR_00C5,                    STR_018B_CLOSE_WINDOW},
-{    WWT_CAPTION,   RESIZE_NONE,   BGC,    11,   549,     0,    13, STR_NETWORK_MULTIPLAYER,     STR_NULL},
-{      WWT_PANEL,   RESIZE_NONE,   BGC,     0,   549,    14,   263, 0x0,                         STR_NULL},
+{    WWT_CAPTION,   RESIZE_RIGHT,  BGC,    11,   449,     0,    13, STR_NETWORK_MULTIPLAYER,     STR_NULL},
+{      WWT_PANEL,   RESIZE_RB,     BGC,     0,   449,    14,   263, 0x0,                         STR_NULL},
 
 /* LEFT SIDE */
-{      WWT_PANEL,   RESIZE_NONE,   BGC,   310,   461,    22,    33, 0x0,                         STR_NETWORK_ENTER_NAME_TIP},
+{      WWT_PANEL,   RESIZE_LR,     BGC,   290,   440,    22,    33, 0x0,                         STR_NETWORK_ENTER_NAME_TIP},
 
 {      WWT_INSET,   RESIZE_NONE,   BGC,    90,   181,    22,    33, STR_NETWORK_COMBO1,          STR_NETWORK_CONNECTION_TIP},
 {    WWT_TEXTBTN,   RESIZE_NONE,   BGC,   170,   180,    23,    32, STR_0225,                    STR_NETWORK_CONNECTION_TIP},
 
-{ WWT_PUSHTXTBTN,   RESIZE_NONE,   BTC,    10,   170,    42,    53, STR_NETWORK_GAME_NAME,       STR_NETWORK_GAME_NAME_TIP},
-{ WWT_PUSHTXTBTN,   RESIZE_NONE,   BTC,   171,   250,    42,    53, STR_NETWORK_CLIENTS_CAPTION, STR_NETWORK_CLIENTS_CAPTION_TIP},
-{ WWT_PUSHTXTBTN,   RESIZE_NONE,   BTC,   251,   290,    42,    53, STR_EMPTY,                   STR_NETWORK_INFO_ICONS_TIP},
+{ WWT_PUSHTXTBTN,   RESIZE_RIGHT,  BTC,    10,    70,    42,    53, STR_NETWORK_GAME_NAME,       STR_NETWORK_GAME_NAME_TIP},
+{ WWT_PUSHTXTBTN,   RESIZE_LR,     BTC,    71,   150,    42,    53, STR_NETWORK_CLIENTS_CAPTION, STR_NETWORK_CLIENTS_CAPTION_TIP},
+{ WWT_PUSHTXTBTN,   RESIZE_LR,     BTC,   151,   190,    42,    53, STR_EMPTY,                   STR_NETWORK_INFO_ICONS_TIP},
 
-{     WWT_MATRIX,   RESIZE_NONE,   BGC,    10,   290,    54,   236, (13 << 8) + 1,               STR_NETWORK_CLICK_GAME_TO_SELECT},
-{  WWT_SCROLLBAR,   RESIZE_NONE,   BGC,   291,   302,    42,   236, STR_NULL,                    STR_0190_SCROLL_BAR_SCROLLS_LIST},
+{     WWT_MATRIX,   RESIZE_RB,     BGC,    10,   190,    54,   236, (13 << 8) + 1,               STR_NETWORK_CLICK_GAME_TO_SELECT},
+{  WWT_SCROLLBAR,   RESIZE_LRB,    BGC,   191,   202,    42,   236, STR_NULL,                    STR_0190_SCROLL_BAR_SCROLLS_LIST},
 
-{ WWT_PUSHTXTBTN,   RESIZE_NONE,   BTC,    30,   130,   246,   257, STR_NETWORK_FIND_SERVER,     STR_NETWORK_FIND_SERVER_TIP},
-{ WWT_PUSHTXTBTN,   RESIZE_NONE,   BTC,   180,   280,   246,   257, STR_NETWORK_ADD_SERVER,      STR_NETWORK_ADD_SERVER_TIP},
+{ WWT_PUSHTXTBTN,   RESIZE_TB,     BTC,    10,   110,   246,   257, STR_NETWORK_FIND_SERVER,     STR_NETWORK_FIND_SERVER_TIP},
+{ WWT_PUSHTXTBTN,   RESIZE_TB,     BTC,   118,   218,   246,   257, STR_NETWORK_ADD_SERVER,      STR_NETWORK_ADD_SERVER_TIP},
 
 /* RIGHT SIDE */
-{ WWT_PUSHTXTBTN,   RESIZE_NONE,   BTC,   315,   415,   246,   257, STR_NETWORK_START_SERVER,    STR_NETWORK_START_SERVER_TIP},
-{ WWT_PUSHTXTBTN,   RESIZE_NONE,   BTC,   430,   535,   246,   257, STR_012E_CANCEL,             STR_NULL},
+{ WWT_PUSHTXTBTN,   RESIZE_TB,     BTC,   226,   326,   246,   257, STR_NETWORK_START_SERVER,    STR_NETWORK_START_SERVER_TIP},
+{ WWT_PUSHTXTBTN,   RESIZE_TB,     BTC,   334,   434,   246,   257, STR_012E_CANCEL,             STR_NULL},
 
-{      WWT_PANEL,   RESIZE_NONE,   BGC,   310,   540,    42,   236, 0x0,                         STR_NULL},
+{      WWT_PANEL,   RESIZE_LRB,    BGC,   210,   440,    42,   236, 0x0,                         STR_NULL},
 
-{ WWT_PUSHTXTBTN,   RESIZE_NONE,   BTC,   315,   415,   215,   226, STR_NETWORK_JOIN_GAME,       STR_NULL},
-{ WWT_PUSHTXTBTN,   RESIZE_NONE,   BTC,   430,   535,   215,   226, STR_NETWORK_REFRESH,         STR_NETWORK_REFRESH_TIP},
+{ WWT_PUSHTXTBTN,   RESIZE_LRTB,   BTC,   215,   315,   215,   226, STR_NETWORK_JOIN_GAME,       STR_NULL},
+{ WWT_PUSHTXTBTN,   RESIZE_LRTB,   BTC,   330,   435,   215,   226, STR_NETWORK_REFRESH,         STR_NETWORK_REFRESH_TIP},
 
-{ WWT_PUSHTXTBTN,   RESIZE_NONE,   BTC,   430,   535,   197,   208, STR_NEWGRF_SETTINGS_BUTTON,  STR_NULL},
+{ WWT_PUSHTXTBTN,   RESIZE_LRTB,   BTC,   330,   435,   197,   208, STR_NEWGRF_SETTINGS_BUTTON,  STR_NULL},
+
+{  WWT_RESIZEBOX,   RESIZE_LRTB,   BGC,   438,   449,   252,   263, 0x0,                         STR_RESIZE_BUTTON },
 
 {   WIDGETS_END},
 };
 
 static const WindowDesc _network_game_window_desc = {
-	WDP_CENTER, WDP_CENTER, 550, 264,
+	WDP_CENTER, WDP_CENTER, 450, 264, 550, 264,
 	WC_NETWORK_WINDOW, WC_NONE,
-	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
+	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
 	_network_game_window_widgets,
 	NetworkGameWindowWndProc,
 };
@@ -581,8 +604,6 @@
 		querystr_d *querystr = &WP(w, network_ql_d).q;
 
 		ttd_strlcpy(_edit_str_buf, _network_player_name, lengthof(_edit_str_buf));
-		w->vscroll.cap = 13;
-
 		querystr->afilter = CS_ALPHANUMERAL;
 		InitializeTextBuffer(&querystr->text, _edit_str_buf, lengthof(_edit_str_buf), 120);
 
@@ -785,7 +806,7 @@
 };
 
 static const WindowDesc _network_start_server_window_desc = {
-	WDP_CENTER, WDP_CENTER, 420, 244,
+	WDP_CENTER, WDP_CENTER, 420, 244, 420, 244,
 	WC_NETWORK_WINDOW, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_network_start_server_window_widgets,
@@ -994,7 +1015,7 @@
 };
 
 static const WindowDesc _network_lobby_window_desc = {
-	WDP_CENTER, WDP_CENTER, 420, 235,
+	WDP_CENTER, WDP_CENTER, 420, 235, 420, 235,
 	WC_NETWORK_WINDOW, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_network_lobby_window_widgets,
@@ -1059,7 +1080,7 @@
 };
 
 static WindowDesc _client_list_desc = {
-	WDP_AUTO, WDP_AUTO, 250, 1,
+	WDP_AUTO, WDP_AUTO, 250, 1, 250, 1,
 	WC_CLIENT_LIST, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
 	_client_list_widgets,
@@ -1133,7 +1154,8 @@
 
 
 // Help, a action is clicked! What do we do?
-static void HandleClientListPopupClick(byte index, byte clientno) {
+static void HandleClientListPopupClick(byte index, byte clientno)
+{
 	// A click on the Popup of the ClientList.. handle the command
 	if (index < MAX_CLIENTLIST_ACTION && _clientlist_proc[index] != NULL) {
 		_clientlist_proc[index](clientno);
@@ -1166,7 +1188,8 @@
 }
 
 // Finds the amount of actions in the popup and set the height correct
-static uint ClientListPopupHeigth() {
+static uint ClientListPopupHeight()
+{
 	int i, num = 0;
 
 	// Find the amount of actions
@@ -1236,7 +1259,7 @@
 	}
 
 	/* Calculate the height */
-	h = ClientListPopupHeigth();
+	h = ClientListPopupHeight();
 
 	// Allocate the popup
 	w = AllocateWindow(x, y, 150, h + 1, ClientListPopupWndProc, WC_TOOLBAR_MENU, _client_list_popup_widgets);
@@ -1468,7 +1491,7 @@
 };
 
 static const WindowDesc _network_join_status_window_desc = {
-	WDP_CENTER, WDP_CENTER, 250, 85,
+	WDP_CENTER, WDP_CENTER, 250, 85, 250, 85,
 	WC_NETWORK_STATUS_WINDOW, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_MODAL,
 	_network_join_status_window_widget,
@@ -1486,7 +1509,7 @@
 
 static void SendChat(const char *buf, DestType type, int dest)
 {
-	if (buf[0] == '\0') return;
+	if (StrEmpty(buf)) return;
 	if (!_network_server) {
 		SEND_COMMAND(PACKET_CLIENT_CHAT)((NetworkAction)(NETWORK_ACTION_CHAT + type), type, dest, buf);
 	} else {
@@ -1694,15 +1717,15 @@
 }
 
 static const Widget _chat_window_widgets[] = {
-{   WWT_CLOSEBOX, RESIZE_NONE, 14,   0,  10,  0, 13, STR_00C5,         STR_018B_CLOSE_WINDOW},
-{      WWT_PANEL, RESIZE_NONE, 14,  11, 639,  0, 13, 0x0,              STR_NULL}, // background
-{      WWT_PANEL, RESIZE_NONE, 14,  75, 577,  1, 12, 0x0,              STR_NULL}, // text box
-{ WWT_PUSHTXTBTN, RESIZE_NONE, 14, 578, 639,  1, 12, STR_NETWORK_SEND, STR_NULL}, // send button
+{   WWT_CLOSEBOX, RESIZE_NONE,  14,   0,  10,  0, 13, STR_00C5,         STR_018B_CLOSE_WINDOW},
+{      WWT_PANEL, RESIZE_RIGHT, 14,  11, 319,  0, 13, 0x0,              STR_NULL}, // background
+{      WWT_PANEL, RESIZE_RIGHT, 14,  75, 257,  1, 12, 0x0,              STR_NULL}, // text box
+{ WWT_PUSHTXTBTN, RESIZE_LR,    14, 258, 319,  1, 12, STR_NETWORK_SEND, STR_NULL}, // send button
 {   WIDGETS_END},
 };
 
 static const WindowDesc _chat_window_desc = {
-	WDP_CENTER, -26, 640, 14, // x, y, width, height
+	WDP_CENTER, -26, 320, 14, 640, 14, // x, y, width, height
 	WC_SEND_NETWORK_MSG, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET,
 	_chat_window_widgets,
--- a/src/network/network_udp.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/network/network_udp.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -44,7 +44,7 @@
 DEF_UDP_RECEIVE_COMMAND(Master, PACKET_UDP_MASTER_ACK_REGISTER)
 {
 	_network_advertise_retries = 0;
-	DEBUG(net, 2, "[udp] advertising on master server successfull");
+	DEBUG(net, 2, "[udp] advertising on master server successful");
 
 	/* We are advertised, but we don't want to! */
 	if (!_network_advertise) NetworkUDPRemoveAdvertise();
@@ -490,10 +490,12 @@
 
 	// Clear item in gamelist
 	item = NetworkGameListAddItem(inet_addr(inet_ntoa(out_addr.sin_addr)), ntohs(out_addr.sin_port));
-	memset(&item->info, 0, sizeof(item->info));
-	ttd_strlcpy(item->info.server_name, host, lengthof(item->info.server_name));
-	ttd_strlcpy(item->info.hostname, host, lengthof(item->info.hostname));
-	item->online   = false;
+	if (StrEmpty(item->info.server_name)) {
+		memset(&item->info, 0, sizeof(item->info));
+		ttd_strlcpy(item->info.server_name, host, lengthof(item->info.server_name));
+		ttd_strlcpy(item->info.hostname, host, lengthof(item->info.hostname));
+		item->online = false;
+	}
 	item->manually = manually;
 
 	// Init the packet
--- a/src/newgrf_callbacks.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_callbacks.h	Fri Aug 03 18:10:15 2007 +0000
@@ -15,6 +15,9 @@
  * Names are formatted as CBID_<CLASS>_<CALLBACK>
  */
 enum CallbackID {
+	/** Set when using the callback resolve system, but not to resolve a callback. */
+	CBID_NO_CALLBACK                     = 0x00,
+
 	/** Set when calling a randomizing trigger (almost undocumented). */
 	CBID_RANDOM_TRIGGER                  = 0x01,
 
--- a/src/newgrf_canal.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_canal.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -73,7 +73,7 @@
 
 	res->u.canal.tile = tile;
 
-	res->callback        = 0;
+	res->callback        = CBID_NO_CALLBACK;
 	res->callback_param1 = 0;
 	res->callback_param2 = 0;
 	res->last_value      = 0;
--- a/src/newgrf_cargo.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_cargo.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -58,7 +58,7 @@
 
 	res->u.cargo.cs = cs;
 
-	res->callback        = 0;
+	res->callback        = CBID_NO_CALLBACK;
 	res->callback_param1 = 0;
 	res->callback_param2 = 0;
 	res->last_value      = 0;
@@ -81,7 +81,7 @@
 }
 
 
-uint16 GetCargoCallback(uint16 callback, uint32 param1, uint32 param2, const CargoSpec *cs)
+uint16 GetCargoCallback(CallbackID callback, uint32 param1, uint32 param2, const CargoSpec *cs)
 {
 	ResolverObject object;
 	const SpriteGroup *group;
--- a/src/newgrf_cargo.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_cargo.h	Fri Aug 03 18:10:15 2007 +0000
@@ -5,6 +5,8 @@
 #ifndef NEWGRF_CARGO_H
 #define NEWGRF_CARGO_H
 
+#include "newgrf_callbacks.h"
+
 enum {
 	CC_NOAVAILABLE  = 0,
 	CC_PASSENGERS   = 1 << 0,
@@ -26,7 +28,7 @@
 struct GRFFile;
 
 SpriteID GetCustomCargoSprite(const CargoSpec *cs);
-uint16 GetCargoCallback(uint16 callback, uint32 param1, uint32 param2, const CargoSpec *cs);
+uint16 GetCargoCallback(CallbackID callback, uint32 param1, uint32 param2, const CargoSpec *cs);
 CargoID GetCargoTranslation(uint8 cargo, const GRFFile *grffile);
 uint8 GetReverseCargoTranslation(CargoID cargo, const GRFFile *grffile);
 
--- a/src/newgrf_commons.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_commons.h	Fri Aug 03 18:10:15 2007 +0000
@@ -25,8 +25,7 @@
 	uint8  substitute_id;  ///< The (original) entity ID to use if this GRF is not available
 };
 
-class OverrideManagerBase
-{
+class OverrideManagerBase {
 protected:
 	uint16 *entity_overrides;
 
@@ -50,40 +49,38 @@
 	uint16 GetSubstituteID(byte entity_id);
 	uint16 GetID(uint8 grf_local_id, uint32 grfid);
 
-	inline uint16 GetMaxMapping() { return max_new_entities; };
-	inline uint16 GetMaxOffset() { return max_offset; };
+	inline uint16 GetMaxMapping() { return max_new_entities; }
+	inline uint16 GetMaxOffset() { return max_offset; }
 };
 
 
 struct HouseSpec;
-class HouseOverrideManager : public OverrideManagerBase
-{
+class HouseOverrideManager : public OverrideManagerBase {
 public:
 	HouseOverrideManager(uint16 offset, uint16 maximum, uint16 invalid) :
-			OverrideManagerBase(offset, maximum, invalid) {};
+			OverrideManagerBase(offset, maximum, invalid) {}
 	void SetEntitySpec(const HouseSpec *hs);
 };
 
 
 struct IndustrySpec;
-class IndustryOverrideManager : public OverrideManagerBase
-{
-	public:
-		IndustryOverrideManager(uint16 offset, uint16 maximum, uint16 invalid) :
-				OverrideManagerBase(offset, maximum, invalid) {};
+class IndustryOverrideManager : public OverrideManagerBase {
+public:
+	IndustryOverrideManager(uint16 offset, uint16 maximum, uint16 invalid) :
+			OverrideManagerBase(offset, maximum, invalid) {}
 
-		virtual uint16 AddEntityID(byte grf_local_id, uint32 grfid, byte substitute_id);
-		void SetEntitySpec(const IndustrySpec *inds);
+	virtual uint16 AddEntityID(byte grf_local_id, uint32 grfid, byte substitute_id);
+	void SetEntitySpec(const IndustrySpec *inds);
 };
 
 
 struct IndustryTileSpec;
-class IndustryTileOverrideManager : public OverrideManagerBase
-{
-	public:
-		IndustryTileOverrideManager(uint16 offset, uint16 maximum, uint16 invalid) :
-				OverrideManagerBase(offset, maximum, invalid) {};
-		void SetEntitySpec(const IndustryTileSpec *indts);
+class IndustryTileOverrideManager : public OverrideManagerBase {
+public:
+	IndustryTileOverrideManager(uint16 offset, uint16 maximum, uint16 invalid) :
+			OverrideManagerBase(offset, maximum, invalid) {}
+
+	void SetEntitySpec(const IndustryTileSpec *indts);
 };
 
 extern HouseOverrideManager _house_mngr;
--- a/src/newgrf_engine.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_engine.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -847,7 +847,7 @@
 
 	res->info_view = false;
 
-	res->callback        = 0;
+	res->callback        = CBID_NO_CALLBACK;
 	res->callback_param1 = 0;
 	res->callback_param2 = 0;
 	res->last_value      = 0;
@@ -947,7 +947,7 @@
  * @param v        The vehicle to evaluate the callback for, or NULL if it doesnt exist yet
  * @return The value the callback returned, or CALLBACK_FAILED if it failed
  */
-uint16 GetVehicleCallback(uint16 callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
+uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
 {
 	const SpriteGroup *group;
 	ResolverObject object;
@@ -974,7 +974,7 @@
  * @param parent   The vehicle to use for parent scope
  * @return The value the callback returned, or CALLBACK_FAILED if it failed
  */
-uint16 GetVehicleCallbackParent(uint16 callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent)
+uint16 GetVehicleCallbackParent(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent)
 {
 	const SpriteGroup *group;
 	ResolverObject object;
--- a/src/newgrf_engine.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_engine.h	Fri Aug 03 18:10:15 2007 +0000
@@ -30,8 +30,8 @@
 const struct GRFFile *GetEngineGRF(EngineID engine);
 uint32 GetEngineGRFID(EngineID engine);
 
-uint16 GetVehicleCallback(uint16 callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v);
-uint16 GetVehicleCallbackParent(uint16 callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent);
+uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v);
+uint16 GetVehicleCallbackParent(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v, const Vehicle *parent);
 bool UsesWagonOverride(const Vehicle *v);
 #define GetCustomVehicleSprite(v, direction) GetCustomEngineSprite(v->engine_type, v, direction)
 #define GetCustomVehicleIcon(et, direction) GetCustomEngineSprite(et, NULL, direction)
--- a/src/newgrf_fsmports.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_fsmports.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -402,7 +402,7 @@
 	res->u.station.fsmportspec = fsmportspec;
 	res->u.station.tile     = tile;
 
-	res->callback        = 0;
+	res->callback        = CBID_NO_CALLBACK;
 	res->callback_param1 = 0;
 	res->callback_param2 = 0;
 	res->last_value      = 0;
@@ -474,7 +474,7 @@
 }
 
 
-uint16 GetFSMportsCallback(uint16 callback, uint32 param1, uint32 param2, const FSMportsSpec *fsmportspec, const Station *st, TileIndex tile)
+uint16 GetFSMportsCallback(CallbackID callback, uint32 param1, uint32 param2, const FSMportsSpec *fsmportspec, const Station *st, TileIndex tile)
 {
 	const SpriteGroup *group;
 	ResolverObject object;
--- a/src/newgrf_fsmports.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_fsmports.h	Fri Aug 03 18:10:15 2007 +0000
@@ -124,7 +124,7 @@
  * for variational sprite groups. */
 SpriteID GetCustomFSMportsRelocation(const FSMportsSpec *FSMPORTSspec, const Station *st, TileIndex tile);
 SpriteID GetCustomFSMportsGroundRelocation(const FSMportsSpec *FSMPORTSspec, const Station *st, TileIndex tile);
-uint16 GetFSMportsCallback(uint16 callback, uint32 param1, uint32 param2, const FSMportsSpec *FSMPORTSspec, const Station *st, TileIndex tile);
+uint16 GetFSMportsCallback(CallbackID callback, uint32 param1, uint32 param2, const FSMportsSpec *FSMPORTSspec, const Station *st, TileIndex tile);
 
 /* Allocate a FSMportsSpec to a Station. This is called once per build operation. */
 int AllocateFSMportsSpecToStation(const FSMportsSpec *FSMPORTSspec, Station *st, bool exec);
--- a/src/newgrf_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -219,22 +219,22 @@
 {    WWT_CAPTION,   RESIZE_RIGHT, 14,  11, 306,   0,  13, STR_NEWGRF_ADD_CAPTION,  STR_018C_WINDOW_TITLE_DRAG_THIS },
 
 /* List of files */
-{      WWT_PANEL,      RESIZE_RB, 14,   0, 294,  14, 221, 0x0,                     STR_NULL },
-{      WWT_INSET,      RESIZE_RB, 14,   2, 292,  16, 219, 0x0,                     STR_NULL },
-{  WWT_SCROLLBAR,     RESIZE_LRB, 14, 295, 306,  14, 221, 0x0,                     STR_NULL },
+{      WWT_PANEL,      RESIZE_RB, 14,   0, 294,  14, 121, 0x0,                     STR_NULL },
+{      WWT_INSET,      RESIZE_RB, 14,   2, 292,  16, 119, 0x0,                     STR_NULL },
+{  WWT_SCROLLBAR,     RESIZE_LRB, 14, 295, 306,  14, 121, 0x0,                     STR_NULL },
 
 /* NewGRF file info */
-{      WWT_PANEL,     RESIZE_RTB, 14,   0, 306, 222, 324, 0x0,                     STR_NULL },
+{      WWT_PANEL,     RESIZE_RTB, 14,   0, 306, 122, 224, 0x0,                     STR_NULL },
 
-{ WWT_PUSHTXTBTN,     RESIZE_RTB, 14,   0, 146, 325, 336, STR_NEWGRF_ADD_FILE,     STR_NEWGRF_ADD_FILE_TIP },
-{ WWT_PUSHTXTBTN,    RESIZE_LRTB, 14, 147, 294, 325, 336, STR_NEWGRF_RESCAN_FILES, STR_NEWGRF_RESCAN_FILES_TIP },
-{  WWT_RESIZEBOX,    RESIZE_LRTB, 14, 295, 306, 325, 336, 0x0,                     STR_RESIZE_BUTTON },
+{ WWT_PUSHTXTBTN,     RESIZE_RTB, 14,   0, 146, 225, 236, STR_NEWGRF_ADD_FILE,     STR_NEWGRF_ADD_FILE_TIP },
+{ WWT_PUSHTXTBTN,    RESIZE_LRTB, 14, 147, 294, 225, 236, STR_NEWGRF_RESCAN_FILES, STR_NEWGRF_RESCAN_FILES_TIP },
+{  WWT_RESIZEBOX,    RESIZE_LRTB, 14, 295, 306, 225, 236, 0x0,                     STR_RESIZE_BUTTON },
 {   WIDGETS_END },
 };
 
 
 static const WindowDesc _newgrf_add_dlg_desc = {
-	WDP_CENTER, WDP_CENTER, 307, 337,
+	WDP_CENTER, WDP_CENTER, 307, 237, 307, 337,
 	WC_SAVELOAD, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
 	_newgrf_add_dlg_widgets,
@@ -549,7 +549,7 @@
 
 
 static const WindowDesc _newgrf_desc = {
-	WDP_CENTER, WDP_CENTER, 300, 225,
+	WDP_CENTER, WDP_CENTER, 300, 225, 300, 225,
 	WC_GAME_OPTIONS, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
 	_newgrf_widgets,
--- a/src/newgrf_house.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_house.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -274,7 +274,7 @@
 	res->u.house.town     = town;
 	res->u.house.house_id = house_id;
 
-	res->callback        = 0;
+	res->callback        = CBID_NO_CALLBACK;
 	res->callback_param1 = 0;
 	res->callback_param2 = 0;
 	res->last_value      = 0;
@@ -282,7 +282,7 @@
 	res->reseed          = 0;
 }
 
-uint16 GetHouseCallback(uint16 callback, uint32 param1, uint32 param2, HouseID house_id, Town *town, TileIndex tile)
+uint16 GetHouseCallback(CallbackID callback, uint32 param1, uint32 param2, HouseID house_id, Town *town, TileIndex tile)
 {
 	ResolverObject object;
 	const SpriteGroup *group;
@@ -314,10 +314,7 @@
 		image = dtss->image + stage;
 		pal   = dtss->pal;
 
-		if (!HASBIT(image, SPRITE_MODIFIER_OPAQUE) && HASBIT(_transparent_opt, TO_HOUSES)) {
-			SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
-			pal = PALETTE_TO_TRANSPARENT;
-		} else if (HASBIT(image, PALETTE_MODIFIER_COLOR)) {
+		if ((HASBIT(image, SPRITE_MODIFIER_OPAQUE) || !HASBIT(_transparent_opt, TO_HOUSES)) && HASBIT(image, PALETTE_MODIFIER_COLOR)) {
 			if (pal == 0) {
 				const HouseSpec *hs = GetHouseSpecs(house_id);
 				if (HASBIT(hs->callback_mask, CBM_BUILDING_COLOUR)) {
@@ -339,7 +336,8 @@
 				image, pal,
 				ti->x + dtss->delta_x, ti->y + dtss->delta_y,
 				dtss->size_x, dtss->size_y,
-				dtss->size_z, ti->z + dtss->delta_z
+				dtss->size_z, ti->z + dtss->delta_z,
+				HASBIT(_transparent_opt, TO_HOUSES)
 			);
 		} else {
 			AddChildSpriteScreen(image, pal, dtss->delta_x, dtss->delta_y);
@@ -353,7 +351,7 @@
 	const SpriteGroup *group;
 	ResolverObject object;
 
-	if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, ti->tileh);
+	if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
 
 	NewHouseResolver(&object, house_id, ti->tile, GetTownByTile(ti->tile));
 
--- a/src/newgrf_house.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_house.h	Fri Aug 03 18:10:15 2007 +0000
@@ -6,6 +6,7 @@
 #define NEWGRF_HOUSE_H
 
 #include "town.h"
+#include "newgrf_callbacks.h"
 
 /**
  * Makes class IDs unique to each GRF file.
@@ -38,7 +39,7 @@
 void AnimateNewHouseTile(TileIndex tile);
 void ChangeHouseAnimationFrame(TileIndex tile, uint16 callback_result);
 
-uint16 GetHouseCallback(uint16 callback, uint32 param1, uint32 param2, HouseID house_id, Town *town, TileIndex tile);
+uint16 GetHouseCallback(CallbackID callback, uint32 param1, uint32 param2, HouseID house_id, Town *town, TileIndex tile);
 
 bool CanDeleteHouse(TileIndex tile);
 
--- a/src/newgrf_industries.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_industries.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -87,8 +87,8 @@
 
 		if (GetIndustryIndex(new_tile) == i->index) {  // Does it belong to the same industry?
 			IndustryGfx gfx = GetIndustryGfx(new_tile);
-			const IndustryTileSpec *indtsp = GetIndustryTileSpec(gfx);
-			const IndustryTileSpec *indold = GetIndustryTileSpec(GetIndustryGfx(old_tile));
+			const IndustryTileSpec *indtsp = GetIndustryTileSpec(gfx, false);
+			const IndustryTileSpec *indold = GetIndustryTileSpec(GetIndustryGfx(old_tile), false);
 
 			if (gfx < NEW_INDUSTRYOFFSET) {  // Does it belongs to an old type?
 				/* It is an old tile.  We have to see if it's been overriden */
@@ -178,7 +178,7 @@
 		}
 
 		/* Distance of nearest industry of given type */
-		case 0x64: return GetClosestIndustry(tile, MapNewGRFIndustryType(parameter, indspec->grf_prop.grffile->grfid), industry); // Distance of nearest industry of given type
+		case 0x64: return GetClosestIndustry(tile, MapNewGRFIndustryType(parameter, indspec->grf_prop.grffile->grfid), industry);
 		/* Get town zone and Manhattan distance of closest town */
  		case 0x65: return GetTownRadiusGroup(industry->town, tile) << 16 | min(DistanceManhattan(tile, industry->town->xy), 0xFFFF);
 		/* Get square of Euclidian distance of closes town */
@@ -189,6 +189,7 @@
 		 * A lot more should be done, since it has to check for local id, grf id etc...
 		 * let's just say it is a beginning ;) */
 		case 0x67: return GetIndustryTypeCount(industry->type) << 16 | 0;
+		case 0x68: break;
 
 		/* Industry structure access*/
 		case 0x80: return industry->xy;
@@ -274,7 +275,7 @@
 	res->u.industry.ind  = indus;
 	res->u.industry.gfx  = INVALID_INDUSTRYTILE;
 
-	res->callback        = 0;
+	res->callback        = CBID_NO_CALLBACK;
 	res->callback_param1 = 0;
 	res->callback_param2 = 0;
 	res->last_value      = 0;
@@ -282,7 +283,7 @@
 	res->reseed          = 0;
 }
 
-uint16 GetIndustryCallback(uint16 callback, uint32 param1, uint32 param2, Industry *industry, IndustryType type, TileIndex tile)
+uint16 GetIndustryCallback(CallbackID callback, uint32 param1, uint32 param2, Industry *industry, IndustryType type, TileIndex tile)
 {
 	ResolverObject object;
 	const SpriteGroup *group;
--- a/src/newgrf_industries.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_industries.h	Fri Aug 03 18:10:15 2007 +0000
@@ -10,7 +10,7 @@
 
 /* in newgrf_industry.cpp */
 uint32 IndustryGetVariable(const ResolverObject *object, byte variable, byte parameter, bool *available);
-uint16 GetIndustryCallback(uint16 callback, uint32 param1, uint32 param2, Industry *industry, IndustryType type, TileIndex tile);
+uint16 GetIndustryCallback(CallbackID callback, uint32 param1, uint32 param2, Industry *industry, IndustryType type, TileIndex tile);
 uint32 GetIndustryIDAtOffset(TileIndex new_tile, TileIndex old_tile, const Industry *i);
 void IndustryProductionCallback(Industry *ind, int reason);
 bool CheckIfCallBackAllowsCreation(TileIndex tile, IndustryType type, uint itspec_index);
--- a/src/newgrf_industrytiles.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_industrytiles.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -142,7 +142,7 @@
 	res->u.industry.ind  = indus;
 	res->u.industry.gfx  = gfx;
 
-	res->callback        = 0;
+	res->callback        = CBID_NO_CALLBACK;
 	res->callback_param1 = 0;
 	res->callback_param2 = 0;
 	res->last_value      = 0;
@@ -166,10 +166,7 @@
 		image = dtss->image + stage;
 		pal   = dtss->pal;
 
-		if (!HASBIT(image, SPRITE_MODIFIER_OPAQUE) && HASBIT(_transparent_opt, TO_INDUSTRIES)) {
-			SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
-			pal = PALETTE_TO_TRANSPARENT;
-		} else if (HASBIT(image, PALETTE_MODIFIER_COLOR)) {
+		if (HASBIT(image, PALETTE_MODIFIER_COLOR)) {
 			pal = GENERAL_SPRITE_COLOR(rnd_color);
 		} else {
 			pal = PAL_NONE;
@@ -180,7 +177,8 @@
 				image, pal,
 				ti->x + dtss->delta_x, ti->y + dtss->delta_y,
 				dtss->size_x, dtss->size_y,
-				dtss->size_z, ti->z + dtss->delta_z
+				dtss->size_z, ti->z + dtss->delta_z,
+				!HASBIT(image, SPRITE_MODIFIER_OPAQUE) && HASBIT(_transparent_opt, TO_INDUSTRIES)
 			);
 		} else {
 			AddChildSpriteScreen(image, pal, dtss->delta_x, dtss->delta_y);
@@ -188,7 +186,7 @@
 	}
 }
 
-uint16 GetIndustryTileCallback(uint16 callback, uint32 param1, uint32 param2, IndustryGfx gfx_id, Industry *industry, TileIndex tile)
+uint16 GetIndustryTileCallback(CallbackID callback, uint32 param1, uint32 param2, IndustryGfx gfx_id, Industry *industry, TileIndex tile)
 {
 	ResolverObject object;
 	const SpriteGroup *group;
@@ -217,7 +215,7 @@
 			draw_old_one = callback_res != 0;
 		}
 
-		if (draw_old_one) DrawFoundation(ti, ti->tileh);
+		if (draw_old_one) DrawFoundation(ti, FOUNDATION_LEVELED);
 	}
 
 	NewIndustryTileResolver(&object, gfx, ti->tile, i);
--- a/src/newgrf_industrytiles.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_industrytiles.h	Fri Aug 03 18:10:15 2007 +0000
@@ -14,7 +14,7 @@
 };
 
 bool DrawNewIndustryTile(TileInfo *ti, Industry *i, IndustryGfx gfx, const IndustryTileSpec *inds);
-uint16 GetIndustryTileCallback(uint16 callback, uint32 param1, uint32 param2, IndustryGfx gfx_id, Industry *industry, TileIndex tile);
+uint16 GetIndustryTileCallback(CallbackID callback, uint32 param1, uint32 param2, IndustryGfx gfx_id, Industry *industry, TileIndex tile);
 bool PerformIndustryTileSlopeCheck(TileIndex tile, const IndustryTileSpec *its, IndustryType type, IndustryGfx gfx);
 
 void AnimateNewIndustryTile(TileIndex tile);
--- a/src/newgrf_spritegroup.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_spritegroup.h	Fri Aug 03 18:10:15 2007 +0000
@@ -188,7 +188,7 @@
 
 
 struct ResolverObject {
-	uint16 callback;
+	CallbackID callback;
 	uint32 callback_param1;
 	uint32 callback_param2;
 
--- a/src/newgrf_station.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_station.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -556,7 +556,7 @@
 	res->u.station.statspec = statspec;
 	res->u.station.tile     = tile;
 
-	res->callback        = 0;
+	res->callback        = CBID_NO_CALLBACK;
 	res->callback_param1 = 0;
 	res->callback_param2 = 0;
 	res->last_value      = 0;
@@ -628,7 +628,7 @@
 }
 
 
-uint16 GetStationCallback(uint16 callback, uint32 param1, uint32 param2, const StationSpec *statspec, const Station *st, TileIndex tile)
+uint16 GetStationCallback(CallbackID callback, uint32 param1, uint32 param2, const StationSpec *statspec, const Station *st, TileIndex tile)
 {
 	const SpriteGroup *group;
 	ResolverObject object;
--- a/src/newgrf_station.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/newgrf_station.h	Fri Aug 03 18:10:15 2007 +0000
@@ -6,6 +6,7 @@
 #define NEWGRF_STATION_H
 
 #include "engine.h"
+#include "newgrf_callbacks.h"
 #include "newgrf_cargo.h"
 #include "helpers.hpp"
 
@@ -117,7 +118,7 @@
  * for variational sprite groups. */
 SpriteID GetCustomStationRelocation(const StationSpec *statspec, const Station *st, TileIndex tile);
 SpriteID GetCustomStationGroundRelocation(const StationSpec *statspec, const Station *st, TileIndex tile);
-uint16 GetStationCallback(uint16 callback, uint32 param1, uint32 param2, const StationSpec *statspec, const Station *st, TileIndex tile);
+uint16 GetStationCallback(CallbackID callback, uint32 param1, uint32 param2, const StationSpec *statspec, const Station *st, TileIndex tile);
 
 /* Check if a rail station tile is traversable. */
 bool IsStationTileBlocked(TileIndex tile);
--- a/src/news_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/news_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -320,7 +320,7 @@
 };
 
 static WindowDesc _news_type13_desc = {
-	WDP_CENTER, 476, 430, 170,
+	WDP_CENTER, 476, 430, 170, 430, 170,
 	WC_NEWS_WINDOW, WC_NONE,
 	WDF_DEF_WIDGET,
 	_news_type13_widgets,
@@ -334,7 +334,7 @@
 };
 
 static WindowDesc _news_type2_desc = {
-	WDP_CENTER, 476, 430, 130,
+	WDP_CENTER, 476, 430, 130, 430, 130,
 	WC_NEWS_WINDOW, WC_NONE,
 	WDF_DEF_WIDGET,
 	_news_type2_widgets,
@@ -350,7 +350,7 @@
 };
 
 static WindowDesc _news_type0_desc = {
-	WDP_CENTER, 476, 280, 87,
+	WDP_CENTER, 476, 280, 87, 280, 87,
 	WC_NEWS_WINDOW, WC_NONE,
 	WDF_DEF_WIDGET,
 	_news_type0_widgets,
@@ -700,7 +700,7 @@
 };
 
 static const WindowDesc _message_history_desc = {
-	240, 22, 400, 140,
+	240, 22, 400, 140, 400, 140,
 	WC_MESSAGE_HISTORY, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_message_history_widgets,
@@ -910,7 +910,7 @@
 };
 
 static const WindowDesc _message_options_desc = {
-	270, 22, 410, 197,
+	270, 22, 410, 197, 410, 197,
 	WC_GAME_OPTIONS, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_message_options_widgets,
--- a/src/npf.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/npf.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -232,7 +232,7 @@
 			}
 			break;
 
-		case MP_STREET:
+		case MP_ROAD:
 			if (!IsTileDepotType(tile, TRANSPORT_ROAD)) {
 				SetRoadside(tile, ROADSIDE_BARREN);
 				MarkTileDirtyByTile(tile);
@@ -276,7 +276,7 @@
 			cost = IsTunnel(tile) ? NPFTunnelCost(current) : NPFBridgeCost(current);
 			break;
 
-		case MP_STREET:
+		case MP_ROAD:
 			cost = NPF_TILE_LENGTH;
 			/* Increase the cost for level crossings */
 			if (IsLevelCrossing(tile)) cost += _patches.npf_crossing_penalty;
@@ -327,7 +327,7 @@
 			cost = _trackdir_length[trackdir]; /* Should be different for diagonal tracks */
 			break;
 
-		case MP_STREET: /* Railway crossing */
+		case MP_ROAD: /* Railway crossing */
 			cost = NPF_TILE_LENGTH;
 			break;
 
@@ -468,7 +468,7 @@
 	}
 
 	switch (GetTileType(tile)) {
-		case MP_STREET:
+		case MP_ROAD:
 			/* rail-road crossing : are we looking at the railway part? */
 			if (IsLevelCrossing(tile) &&
 					DiagDirToAxis(enterdir) != GetCrossingRoadAxis(tile)) {
--- a/src/oldloader.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/oldloader.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -520,7 +520,7 @@
 
 	if (!LoadChunk(ls, GetDepot(num), depot_chunk)) return false;
 
-	if (IsValidDepot(GetDepot(num))) {
+	if (IsValidDepotID(num)) {
 		GetDepot(num)->town_index = REMAP_TOWN_IDX(_old_town_index);
 	}
 
@@ -715,7 +715,7 @@
 	i = GetIndustry(num);
 	if (!LoadChunk(ls, i, industry_chunk)) return false;
 
-	if (IsValidIndustry(i)) {
+	if (i->IsValid()) {
 		i->town = GetTown(REMAP_TOWN_IDX(_old_town_index));
 	}
 
@@ -1053,8 +1053,8 @@
 };
 
 static const OldChunks vehicle_special_chunk[] = {
-	OCL_SVAR( OC_UINT16, VehicleSpecial, unk0 ),
-	OCL_SVAR(  OC_UINT8, VehicleSpecial, unk2 ),
+	OCL_SVAR( OC_UINT16, VehicleSpecial, animation_state ),
+	OCL_SVAR(  OC_UINT8, VehicleSpecial, animation_substate ),
 
 	OCL_NULL( 7 ), // Junk
 
@@ -1063,7 +1063,7 @@
 
 static const OldChunks vehicle_disaster_chunk[] = {
 	OCL_SVAR( OC_UINT16, VehicleDisaster, image_override ),
-	OCL_SVAR( OC_UINT16, VehicleDisaster, unk2 ),
+	OCL_SVAR( OC_UINT16, VehicleDisaster, big_ufo_destroyer_target ),
 
 	OCL_NULL( 6 ), ///< Junk
 
--- a/src/oldpool.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/oldpool.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -12,27 +12,28 @@
 /**
  * Clean a pool in a safe way (does free all blocks)
  */
-void CleanPool(OldMemoryPool *pool)
+void OldMemoryPoolBase::CleanPool()
 {
 	uint i;
 
-	DEBUG(misc, 4, "[Pool] (%s) cleaning pool..", pool->name);
+	DEBUG(misc, 4, "[Pool] (%s) cleaning pool..", this->name);
 
 	/* Free all blocks */
-	for (i = 0; i < pool->current_blocks; i++) {
-		if (pool->clean_block_proc != NULL) {
-			pool->clean_block_proc(i * (1 << pool->block_size_bits), (i + 1) * (1 << pool->block_size_bits) - 1);
+	for (i = 0; i < this->current_blocks; i++) {
+		if (this->clean_block_proc != NULL) {
+			this->clean_block_proc(i * (1 << this->block_size_bits), (i + 1) * (1 << this->block_size_bits) - 1);
 		}
-		free(pool->blocks[i]);
+		free(this->blocks[i]);
 	}
 
 	/* Free the block itself */
-	free(pool->blocks);
+	free(this->blocks);
 
 	/* Clear up some critical data */
-	pool->total_items = 0;
-	pool->current_blocks = 0;
-	pool->blocks = NULL;
+	this->total_items = 0;
+	this->current_blocks = 0;
+	this->blocks = NULL;
+	this->first_free_index = 0;
 }
 
 /**
@@ -41,34 +42,32 @@
  *
  * @return Returns false if the pool could not be increased
  */
-bool AddBlockToPool(OldMemoryPool *pool)
+bool OldMemoryPoolBase::AddBlockToPool()
 {
 	/* Is the pool at his max? */
-	if (pool->max_blocks == pool->current_blocks)
-		return false;
+	if (this->max_blocks == this->current_blocks) return false;
 
-	pool->total_items = (pool->current_blocks + 1) * (1 << pool->block_size_bits);
+	this->total_items = (this->current_blocks + 1) * (1 << this->block_size_bits);
 
-	DEBUG(misc, 4, "[Pool] (%s) increasing size of pool to %d items (%d bytes)", pool->name, pool->total_items, pool->total_items * pool->item_size);
+	DEBUG(misc, 4, "[Pool] (%s) increasing size of pool to %d items (%d bytes)", this->name, this->total_items, this->total_items * this->item_size);
 
 	/* Increase the poolsize */
-	pool->blocks = ReallocT(pool->blocks, pool->current_blocks + 1);
-	if (pool->blocks == NULL) error("Pool: (%s) could not allocate memory for blocks", pool->name);
+	this->blocks = ReallocT(this->blocks, this->current_blocks + 1);
+	if (this->blocks == NULL) error("Pool: (%s) could not allocate memory for blocks", this->name);
 
 	/* Allocate memory to the new block item */
-	pool->blocks[pool->current_blocks] = MallocT<byte>(pool->item_size * (1 << pool->block_size_bits));
-	if (pool->blocks[pool->current_blocks] == NULL)
-		error("Pool: (%s) could not allocate memory for blocks", pool->name);
+	this->blocks[this->current_blocks] = MallocT<byte>(this->item_size * (1 << this->block_size_bits));
+	if (this->blocks[this->current_blocks] == NULL)
+		error("Pool: (%s) could not allocate memory for blocks", this->name);
 
 	/* Clean the content of the new block */
-	memset(pool->blocks[pool->current_blocks], 0, pool->item_size * (1 << pool->block_size_bits));
+	memset(this->blocks[this->current_blocks], 0, this->item_size * (1 << this->block_size_bits));
 
 	/* Call a custom function if defined (e.g. to fill indexes) */
-	if (pool->new_block_proc != NULL)
-		pool->new_block_proc(pool->current_blocks * (1 << pool->block_size_bits));
+	if (this->new_block_proc != NULL) this->new_block_proc(this->current_blocks * (1 << this->block_size_bits));
 
 	/* We have a new block */
-	pool->current_blocks++;
+	this->current_blocks++;
 
 	return true;
 }
@@ -78,11 +77,10 @@
  *
  * @return Returns false if adding failed
  */
-bool AddBlockIfNeeded(OldMemoryPool *pool, uint index)
+bool OldMemoryPoolBase::AddBlockIfNeeded(uint index)
 {
-	while (index >= pool->total_items) {
-		if (!AddBlockToPool(pool))
-			return false;
+	while (index >= this->total_items) {
+		if (!this->AddBlockToPool()) return false;
 	}
 
 	return true;
--- a/src/oldpool.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/oldpool.h	Fri Aug 03 18:10:15 2007 +0000
@@ -5,8 +5,6 @@
 #ifndef OLDPOOL_H
 #define OLDPOOL_H
 
-struct OldMemoryPool;
-
 /* The function that is called after a new block is added
      start_item is the first item of the new made block */
 typedef void OldMemoryPoolNewBlock(uint start_item);
@@ -17,12 +15,22 @@
  * Stuff for dynamic vehicles. Use the wrappers to access the OldMemoryPool
  *  please try to avoid manual calls!
  */
-struct OldMemoryPool {
+struct OldMemoryPoolBase {
+	void CleanPool();
+	bool AddBlockToPool();
+	bool AddBlockIfNeeded(uint index);
+
+protected:
+	OldMemoryPoolBase(const char *name, uint max_blocks, uint block_size_bits, uint item_size,
+				OldMemoryPoolNewBlock *new_block_proc, OldMemoryPoolCleanBlock *clean_block_proc) :
+		name(name), max_blocks(max_blocks), block_size_bits(block_size_bits),
+		new_block_proc(new_block_proc), clean_block_proc(clean_block_proc), current_blocks(0),
+		total_items(0), item_size(item_size), first_free_index(0), blocks(NULL) {}
+
 	const char* name;     ///< Name of the pool (just for debugging)
 
-	uint max_blocks;      ///< The max amount of blocks this pool can have
-	uint block_size_bits; ///< The size of each block in bits
-	uint item_size;       ///< How many bytes one block is
+	const uint max_blocks;      ///< The max amount of blocks this pool can have
+	const uint block_size_bits; ///< The size of each block in bits
 
 	/// Pointer to a function that is called after a new block is added
 	OldMemoryPoolNewBlock *new_block_proc;
@@ -32,7 +40,70 @@
 	uint current_blocks;        ///< How many blocks we have in our pool
 	uint total_items;           ///< How many items we now have in this pool
 
+public:
+	const uint item_size;       ///< How many bytes one block is
+	uint first_free_index;      ///< The index of the first free pool item in this pool
 	byte **blocks;              ///< An array of blocks (one block hold all the items)
+
+	/**
+	 * Get the size of this pool, i.e. the total number of items you
+	 * can put into it at the current moment; the pool might still
+	 * be able to increase the size of the pool.
+	 * @return the size of the pool
+	 */
+	inline uint GetSize() const
+	{
+		return this->total_items;
+	}
+
+	/**
+	 * Can this pool allocate more blocks, i.e. is the maximum amount
+	 * of allocated blocks not yet reached?
+	 * @return the if and only if the amount of allocable blocks is
+	 *         less than the amount of allocated blocks.
+	 */
+	inline bool CanAllocateMoreBlocks() const
+	{
+		return this->current_blocks < this->max_blocks;
+	}
+
+	/**
+	 * Get the maximum number of allocable blocks.
+	 * @return the numebr of blocks
+	 */
+	inline uint GetBlockCount() const
+	{
+		return this->current_blocks;
+	}
+
+	/**
+	 * Get the name of this pool.
+	 * @return the name
+	 */
+	inline const char *GetName() const
+	{
+		return this->name;
+	}
+};
+
+template <typename T>
+struct OldMemoryPool : public OldMemoryPoolBase {
+	OldMemoryPool(const char *name, uint max_blocks, uint block_size_bits, uint item_size,
+				OldMemoryPoolNewBlock *new_block_proc, OldMemoryPoolCleanBlock *clean_block_proc) :
+		OldMemoryPoolBase(name, max_blocks, block_size_bits, item_size, new_block_proc, clean_block_proc) {}
+
+	/**
+	 * Get the pool entry at the given index.
+	 * @param index the index into the pool
+	 * @pre index < this->GetSize()
+	 * @return the pool entry.
+	 */
+	inline T *Get(uint index) const
+	{
+		assert(index < this->GetSize());
+		return (T*)(this->blocks[index >> this->block_size_bits] +
+				(index & ((1 << this->block_size_bits) - 1)) * this->item_size);
+	}
 };
 
 /**
@@ -42,15 +113,171 @@
  *   AddBlockToPool adds 1 more block to the pool. Returns false if there is no
  *     more room
  */
-void CleanPool(OldMemoryPool *array);
-bool AddBlockToPool(OldMemoryPool *array);
+static inline void CleanPool(OldMemoryPoolBase *array) { array->CleanPool(); }
+static inline bool AddBlockToPool(OldMemoryPoolBase *array) { return array->AddBlockToPool(); }
 
 /**
  * Adds blocks to the pool if needed (and possible) till index fits inside the pool
  *
  * @return Returns false if adding failed
  */
-bool AddBlockIfNeeded(OldMemoryPool *array, uint index);
+static inline bool AddBlockIfNeeded(OldMemoryPoolBase *array, uint index) { return array->AddBlockIfNeeded(index); }
+
+
+/**
+ * Generic function to initialize a new block in a pool.
+ * @param start_item the first item that needs to be initialized
+ */
+template <typename T, OldMemoryPool<T> *Tpool>
+static void PoolNewBlock(uint start_item)
+{
+	for (T *t = Tpool->Get(start_item); t != NULL; t = (t->index + 1U < Tpool->GetSize()) ? Tpool->Get(t->index + 1U) : NULL) {
+		t = new (t) T();
+		t->index = start_item++;
+	}
+}
+
+/**
+ * Generic function to free a new block in a pool.
+ * This function uses QuickFree that is intended to only free memory that would be lost if the pool is freed.
+ * @param start_item the first item that needs to be cleaned
+ * @param end_item   the last item that needs to be cleaned
+ */
+template <typename T, OldMemoryPool<T> *Tpool>
+static void PoolCleanBlock(uint start_item, uint end_item)
+{
+	for (uint i = start_item; i <= end_item; i++) {
+		T *t = Tpool->Get(i);
+		if (t->IsValid()) {
+			t->QuickFree();
+		}
+	}
+}
+
+
+/**
+ * Generalization for all pool items that are saved in the savegame.
+ * It specifies all the mechanics to access the pool easily.
+ */
+template <typename T, typename Tid, OldMemoryPool<T> *Tpool>
+struct PoolItem {
+	/**
+	 * The pool-wide index of this object.
+	 */
+	Tid index;
+
+	/**
+	 * We like to have the correct class destructed.
+	 */
+	virtual ~PoolItem()
+	{
+		if (this->index < Tpool->first_free_index) Tpool->first_free_index = this->index;
+	}
+
+	/**
+	 * Called on each object when the pool is being destroyed, so one
+	 * can free allocated memory without the need for freeing for
+	 * example orders.
+	 */
+	virtual void QuickFree()
+	{
+	}
+
+	/**
+	 * An overriden version of new that allocates memory on the pool.
+	 * @param size the size of the variable (unused)
+	 * @return the memory that is 'allocated'
+	 */
+	void *operator new(size_t size)
+	{
+		return AllocateRaw();
+	}
+
+	/**
+	 * 'Free' the memory allocated by the overriden new.
+	 * @param p the memory to 'free'
+	 */
+	void operator delete(void *p)
+	{
+	}
+
+	/**
+	 * An overriden version of new, so you can directly allocate a new object with
+	 * the correct index when one is loading the savegame.
+	 * @param size  the size of the variable (unused)
+	 * @param index the index of the object
+	 * @return the memory that is 'allocated'
+	 */
+	void *operator new(size_t size, int index)
+	{
+		if (!Tpool->AddBlockIfNeeded(index)) error("%s: failed loading savegame: too many %s", Tpool->GetName(), Tpool->GetName());
+
+		return Tpool->Get(index);
+	}
+
+	/**
+	 * 'Free' the memory allocated by the overriden new.
+	 * @param p     the memory to 'free'
+	 * @param index the original parameter given to create the memory
+	 */
+	void operator delete(void *p, int index)
+	{
+	}
+
+	/**
+	 * An overriden version of new, so you can use the vehicle instance
+	 * instead of a newly allocated piece of memory.
+	 * @param size the size of the variable (unused)
+	 * @param pn   the already existing object to use as 'storage' backend
+	 * @return the memory that is 'allocated'
+	 */
+	void *operator new(size_t size, T *pn)
+	{
+		return pn;
+	}
+
+	/**
+	 * 'Free' the memory allocated by the overriden new.
+	 * @param p  the memory to 'free'
+	 * @param pn the pointer that was given to 'new' on creation.
+	 */
+	void operator delete(void *p, T *pn)
+	{
+	}
+
+	/**
+	 * Is this a valid object or not?
+	 * @return true if and only if it is valid
+	 */
+	virtual bool IsValid() const
+	{
+		return false;
+	}
+
+private:
+	/**
+	 * Allocate a pool item; possibly allocate a new block in the pool.
+	 * @return the allocated pool item (or NULL when the pool is full).
+	 */
+	static T *AllocateRaw()
+	{
+		for (T *t = Tpool->Get(Tpool->first_free_index); t != NULL; t = (t->index + 1U < Tpool->GetSize()) ? Tpool->Get(t->index + 1U) : NULL) {
+			if (!t->IsValid()) {
+				Tpool->first_free_index = t->index;
+				Tid index = t->index;
+
+				memset(t, 0, Tpool->item_size);
+				t->index = index;
+				return t;
+			}
+		}
+
+		/* Check if we can add a block to the pool */
+		if (Tpool->AddBlockToPool()) return AllocateRaw();
+
+		return NULL;
+	}
+};
 
 
 #define OLD_POOL_ENUM(name, type, block_size_bits, max_blocks) \
@@ -61,33 +288,25 @@
 
 
 #define OLD_POOL_ACCESSORS(name, type) \
-	static inline type* Get##name(uint index) \
-	{ \
-		assert(index < _##name##_pool.total_items); \
-		return (type*)( \
-			_##name##_pool.blocks[index >> name##_POOL_BLOCK_SIZE_BITS] + \
-			(index & ((1 << name##_POOL_BLOCK_SIZE_BITS) - 1)) * sizeof(type) \
-		); \
-	} \
-\
-	static inline uint Get##name##PoolSize() \
-	{ \
-		return _##name##_pool.total_items; \
-	}
+	static inline type* Get##name(uint index) { return _##name##_pool.Get(index);  } \
+	static inline uint Get##name##PoolSize()  { return _##name##_pool.GetSize(); }
 
 
 #define DECLARE_OLD_POOL(name, type, block_size_bits, max_blocks) \
 	OLD_POOL_ENUM(name, type, block_size_bits, max_blocks) \
-	extern OldMemoryPool _##name##_pool; \
+	extern OldMemoryPool<type> _##name##_pool; \
 	OLD_POOL_ACCESSORS(name, type)
 
 
 #define DEFINE_OLD_POOL(name, type, new_block_proc, clean_block_proc) \
-	OldMemoryPool _##name##_pool = { \
+	OldMemoryPool<type> _##name##_pool( \
 		#name, name##_POOL_MAX_BLOCKS, name##_POOL_BLOCK_SIZE_BITS, sizeof(type), \
-		new_block_proc, clean_block_proc, \
-		0, 0, NULL \
-	};
+		new_block_proc, clean_block_proc);
+
+#define DEFINE_OLD_POOL_GENERIC(name, type) \
+	OldMemoryPool<type> _##name##_pool( \
+		#name, name##_POOL_MAX_BLOCKS, name##_POOL_BLOCK_SIZE_BITS, sizeof(type), \
+		PoolNewBlock<type, &_##name##_pool>, PoolCleanBlock<type, &_##name##_pool>);
 
 
 #define STATIC_OLD_POOL(name, type, block_size_bits, max_blocks, new_block_proc, clean_block_proc) \
--- a/src/openttd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/openttd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -5,7 +5,6 @@
 #include "stdafx.h"
 #define VARDEF
 #include "string.h"
-#include "table/strings.h"
 #include "debug.h"
 #include "driver.h"
 #include "saveload.h"
@@ -15,6 +14,7 @@
 #include "helpers.hpp"
 
 #include "openttd.h"
+#include "table/strings.h"
 #include "strings.h"
 #include "bridge_map.h"
 #include "functions.h"
@@ -1153,7 +1153,7 @@
 
 	for (tile = 0; tile != MapSize(); tile++) {
 		switch (GetTileType(tile)) {
-			case MP_STREET:
+			case MP_ROAD:
 				if (GB(_m[tile].m5, 4, 2) == ROAD_TILE_CROSSING && HASBIT(_m[tile].m4, 7)) {
 					_m[tile].m4 = OWNER_TOWN;
 				}
@@ -1473,7 +1473,7 @@
 					SetTownIndex(t, CalcClosestTownFromTile(t, (uint)-1)->index);
 					break;
 
-				case MP_STREET:
+				case MP_ROAD:
 					_m[t].m4 |= (_m[t].m2 << 4);
 					if (IsTileOwner(t, OWNER_TOWN)) {
 						SetTownIndex(t, CalcClosestTownFromTile(t, (uint)-1)->index);
@@ -1535,7 +1535,7 @@
 					}
 					break;
 
-				case MP_STREET:
+				case MP_ROAD:
 					/* Swap m3 and m4, so the track type for rail crossings is the
 					 * same as for normal rail. */
 					Swap(_m[t].m3, _m[t].m4);
@@ -1551,7 +1551,7 @@
 		bool old_bridge = CheckSavegameVersion(42);
 		for (TileIndex t = 0; t < map_size; t++) {
 			switch(GetTileType(t)) {
-				case MP_STREET:
+				case MP_ROAD:
 					SB(_m[t].m5, 6, 2, GB(_m[t].m5, 4, 2));
 					switch (GetRoadTileType(t)) {
 						default: NOT_REACHED();
@@ -1679,7 +1679,7 @@
 					SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
 					break;
 
-				case MP_STREET:
+				case MP_ROAD:
 					if (IsLevelCrossing(t)) {
 						SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
 					}
@@ -1781,7 +1781,7 @@
 					}
 					break;
 
-				case MP_STREET: /* Clear PBS reservation on crossing */
+				case MP_ROAD: /* Clear PBS reservation on crossing */
 					if (IsLevelCrossing(t)) CLRBIT(_m[t].m5, 0);
 					break;
 
--- a/src/openttd.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/openttd.h	Fri Aug 03 18:10:15 2007 +0000
@@ -51,7 +51,7 @@
 typedef uint16 EngineID;
 typedef uint16 UnitID;
 typedef uint16 StringID;
-#define INVALID_STRING_ID 0xFFFF
+static const StringID INVALID_STRING_ID = 0xFFFF;
 
 typedef EngineID *EngineList; ///< engine list type placeholder acceptable for C code (see helpers.cpp)
 
@@ -472,7 +472,7 @@
 typedef void ChangeTileOwnerProc(TileIndex tile, PlayerID old_player, PlayerID new_player);
 /** @see VehicleEnterTileStatus to see what the return values mean */
 typedef uint32 VehicleEnterTileProc(Vehicle *v, TileIndex tile, int x, int y);
-typedef Slope GetSlopeTilehProc(TileIndex, Slope tileh);
+typedef Foundation GetFoundationProc(TileIndex tile, Slope tileh);
 
 struct TileTypeProcs {
 	DrawTileProc *draw_tile_proc;
@@ -487,7 +487,7 @@
 	ChangeTileOwnerProc *change_tile_owner_proc;
 	GetProducedCargoProc *get_produced_cargo_proc;
 	VehicleEnterTileProc *vehicle_enter_tile_proc;
-	GetSlopeTilehProc *get_slope_tileh_proc;
+	GetFoundationProc *get_foundation_proc;
 };
 
 
--- a/src/order.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/order.h	Fri Aug 03 18:10:15 2007 +0000
@@ -83,26 +83,30 @@
 	CO_UNSHARE = 2
 };
 
+struct Order;
+DECLARE_OLD_POOL(Order, Order, 6, 1000)
+
 /* If you change this, keep in mind that it is saved on 3 places:
  * - Load_ORDR, all the global orders
  * - Vehicle -> current_order
  * - REF_ORDER (all REFs are currently limited to 16 bits!!)
  */
-struct Order {
+struct Order : PoolItem<Order, OrderID, &_Order_pool> {
 	Order *next;          ///< Pointer to next order. If NULL, end of list
 
 	OrderTypeByte type;
 	uint8  flags;
 	DestinationID dest;   ///< The destionation of the order.
 
-	OrderID index;         ///< Index of the order, is not saved or anything, just for reference
-
 	CargoID refit_cargo; // Refit CargoID
 	byte refit_subtype; // Refit subtype
 
 	uint16 wait_time;    ///< How long in ticks to wait at the destination.
 	uint16 travel_time;  ///< How long in ticks the journey to this destination should take.
 
+	Order() : refit_cargo(CT_NO_REFIT) {}
+	~Order() { this->type = OT_NOTHING; }
+
 	bool IsValid() const;
 	void Free();
 	void FreeChain();
@@ -121,8 +125,6 @@
 VARDEF TileIndex _backup_orders_tile;
 VARDEF BackuppedOrders _backup_orders_data[1];
 
-DECLARE_OLD_POOL(Order, Order, 6, 1000)
-
 static inline VehicleOrderID GetMaxOrderIndex()
 {
 	/* TODO - This isn't the real content of the function, but
@@ -143,21 +145,21 @@
  */
 inline bool Order::IsValid() const
 {
-	return type != OT_NOTHING;
+	return this->type != OT_NOTHING;
 }
 
 inline void Order::Free()
 {
-	type  = OT_NOTHING;
-	flags = 0;
-	dest  = 0;
-	next  = NULL;
+	this->type  = OT_NOTHING;
+	this->flags = 0;
+	this->dest  = 0;
+	this->next  = NULL;
 }
 
 inline void Order::FreeChain()
 {
 	if (next != NULL) next->FreeChain();
-	Free();
+	delete this;
 }
 
 #define FOR_ALL_ORDERS_FROM(order, start) for (order = GetOrder(start); order != NULL; order = (order->index + 1U < GetOrderPoolSize()) ? GetOrder(order->index + 1U) : NULL) if (order->IsValid())
@@ -171,13 +173,9 @@
 	const Order *order;
 
 	/* There is always room if not all blocks in the pool are reserved */
-	if (_Order_pool.current_blocks < _Order_pool.max_blocks)
-		return true;
+	if (_Order_pool.CanAllocateMoreBlocks()) return true;
 
-	FOR_ALL_ORDERS(order)
-		if (!order->IsValid())
-			if (--amount == 0)
-				return true;
+	FOR_ALL_ORDERS(order) if (!order->IsValid() && --amount == 0) return true;
 
 	return false;
 }
--- a/src/order_cmd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/order_cmd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -20,19 +20,7 @@
 #include "cargotype.h"
 #include "strings.h"
 
-/**
- * Called if a new block is added to the order-pool
- */
-static void OrderPoolNewBlock(uint start_item)
-{
-	Order *order;
-
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (order = GetOrder(start_item); order != NULL; order = (order->index + 1U < GetOrderPoolSize()) ? GetOrder(order->index + 1U) : NULL) order->index = start_item++;
-}
-
-DEFINE_OLD_POOL(Order, Order, OrderPoolNewBlock, NULL)
+DEFINE_OLD_POOL_GENERIC(Order, Order)
 
 /**
  *
@@ -113,41 +101,6 @@
 
 /**
  *
- * Allocate a new order
- *
- * @return Order* if a free space is found, else NULL.
- *
- */
-static Order *AllocateOrder()
-{
-	Order *order;
-
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (order = GetOrder(0); order != NULL; order = (order->index + 1U < GetOrderPoolSize()) ? GetOrder(order->index + 1U) : NULL) {
-		if (!order->IsValid()) {
-			OrderID index = order->index;
-
-			memset(order, 0, sizeof(*order));
-			order->index = index;
-			order->next = NULL;
-			order->refit_cargo   = CT_NO_REFIT;
-			order->refit_subtype = 0;
-			order->wait_time     = 0;
-			order->travel_time   = 0;
-
-			return order;
-		}
-	}
-
-	/* Check if we can add a block to the pool */
-	if (AddBlockToPool(&_Order_pool)) return AllocateOrder();
-
-	return NULL;
-}
-
-/**
- *
  * Assign data to an order (from an other order)
  *   This function makes sure that the index is maintained correctly
  *
@@ -395,7 +348,7 @@
 
 	if (flags & DC_EXEC) {
 		Vehicle *u;
-		Order *new_o = AllocateOrder();
+		Order *new_o = new Order();
 		AssignOrder(new_o, new_order);
 
 		/* Create new order and link in list */
@@ -890,7 +843,7 @@
 
 				order_dst = &dst->orders;
 				FOR_VEHICLE_ORDERS(src, order) {
-					*order_dst = AllocateOrder();
+					*order_dst = new Order();
 					AssignOrder(*order_dst, *order);
 					order_dst = &(*order_dst)->next;
 				}
@@ -1367,10 +1320,8 @@
 			SlArray(orders, len, SLE_UINT16);
 
 			for (i = 0; i < len; ++i) {
-				if (!AddBlockIfNeeded(&_Order_pool, i))
-					error("Orders: failed loading savegame: too many orders");
-
-				AssignOrder(GetOrder(i), UnpackVersion4Order(orders[i]));
+				Order *order = new (i) Order();
+				AssignOrder(order, UnpackVersion4Order(orders[i]));
 			}
 		} else if (CheckSavegameVersionOldStyle(5, 2)) {
 			uint32 orders[5000];
@@ -1381,10 +1332,8 @@
 			SlArray(orders, len, SLE_UINT32);
 
 			for (i = 0; i < len; ++i) {
-				if (!AddBlockIfNeeded(&_Order_pool, i))
-					error("Orders: failed loading savegame: too many orders");
-
-				AssignOrder(GetOrder(i), UnpackOrder(orders[i]));
+				Order *order = new (i) Order();
+				AssignOrder(order, UnpackOrder(orders[i]));
 			}
 		}
 
@@ -1400,12 +1349,7 @@
 		int index;
 
 		while ((index = SlIterateArray()) != -1) {
-			Order *order;
-
-			if (!AddBlockIfNeeded(&_Order_pool, index))
-				error("Orders: failed loading savegame: too many orders");
-
-			order = GetOrder(index);
+			Order *order = new (index) Order();
 			SlObject(order, _order_desc);
 		}
 	}
--- a/src/order_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/order_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -115,7 +115,6 @@
 	int sel;
 	int y, i;
 	bool shared_orders;
-	byte color;
 
 	v = GetVehicle(w->window_number);
 
@@ -192,6 +191,11 @@
 			SetDParam(1, 6);
 
 			switch (order->type) {
+				case OT_DUMMY:
+					SetDParam(1, STR_INVALID_ORDER);
+					SetDParam(2, order->dest);
+					break;
+
 				case OT_GOTO_STATION:
 					SetDParam(1, StationOrderStrings[order->flags]);
 					SetDParam(2, order->dest);
@@ -234,15 +238,10 @@
 				default: break;
 			}
 
-			color = (i == WP(w,order_d).sel) ? 0xC : 0x10;
+			const byte colour = (i == WP(w,order_d).sel) ? 0xC : 0x10;
 			SetDParam(0, i + 1);
-			if (order->type != OT_DUMMY) {
-				DrawString(2, y, str, color);
-			} else {
-				SetDParam(1, STR_INVALID_ORDER);
-				SetDParam(2, order->dest);
-				DrawString(2, y, str, color);
-			}
+			DrawString(2, y, str, colour);
+
 			y += 10;
 		}
 
@@ -252,8 +251,8 @@
 
 	if (i - w->vscroll.pos < w->vscroll.cap) {
 		str = shared_orders ? STR_END_OF_SHARED_ORDERS : STR_882A_END_OF_ORDERS;
-		color = (i == WP(w,order_d).sel) ? 0xC : 0x10;
-		DrawString(2, y, str, color);
+		const byte colour = (i == WP(w,order_d).sel) ? 0xC : 0x10;
+		DrawString(2, y, str, colour);
 	}
 }
 
@@ -279,7 +278,7 @@
 			}
 			break;
 
-		case MP_STREET:
+		case MP_ROAD:
 			if (GetRoadTileType(tile) == ROAD_TILE_DEPOT && v->type == VEH_ROAD && IsTileOwner(tile, _local_player)) {
 				order.type = OT_GOTO_DEPOT;
 				order.flags = OF_PART_OF_ORDERS;
@@ -771,7 +770,7 @@
 };
 
 static const WindowDesc _orders_train_desc = {
-	WDP_AUTO, WDP_AUTO, 399, 88,
+	WDP_AUTO, WDP_AUTO, 399, 88, 399, 88,
 	WC_VEHICLE_ORDERS,WC_VEHICLE_VIEW,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_RESIZABLE,
 	_orders_train_widgets,
@@ -808,7 +807,7 @@
 };
 
 static const WindowDesc _orders_desc = {
-	WDP_AUTO, WDP_AUTO, 410, 88,
+	WDP_AUTO, WDP_AUTO, 410, 88, 410, 88,
 	WC_VEHICLE_ORDERS,WC_VEHICLE_VIEW,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_RESIZABLE,
 	_orders_widgets,
@@ -845,7 +844,7 @@
 };
 
 static const WindowDesc _other_orders_desc = {
-	WDP_AUTO, WDP_AUTO, 332, 88,
+	WDP_AUTO, WDP_AUTO, 332, 88, 332, 88,
 	WC_VEHICLE_ORDERS,WC_VEHICLE_VIEW,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
 	_other_orders_widgets,
--- a/src/os/macosx/splash.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/os/macosx/splash.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -128,7 +128,7 @@
 	_cur_palette[0xff].b = 0;
 
 	_pal_first_dirty = 0;
-	_pal_count_dirty = 255;
+	_pal_count_dirty = 256;
 
 	png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
 	fclose(f);
--- a/src/os2.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/os2.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -173,7 +173,7 @@
  * and append this up to the maximum length (either absolute or screenlength). If maxlength
  * is zero, we don't care about the screenlength but only about the physical length of the string
  * @param tb Textbuf type to be changed
- * @return Return true on successfull change of Textbuf, or false otherwise
+ * @return Return true on successful change of Textbuf, or false otherwise
  */
 bool InsertTextBufferClipboard(Textbuf *tb)
 {
--- a/src/player.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/player.h	Fri Aug 03 18:10:15 2007 +0000
@@ -53,13 +53,13 @@
 
 	TileIndex start_tile_a;
 	TileIndex cur_tile_a;
-	byte cur_dir_a;
-	byte start_dir_a;
+	DiagDirectionByte cur_dir_a;
+	DiagDirectionByte start_dir_a;
 
 	TileIndex start_tile_b;
 	TileIndex cur_tile_b;
-	byte cur_dir_b;
-	byte start_dir_b;
+	DiagDirectionByte cur_dir_b;
+	DiagDirectionByte start_dir_b;
 
 	Vehicle *cur_veh; ///< only used by some states
 
@@ -77,8 +77,8 @@
 	TileIndex start_tile_br; ///< br = bottom-right
 	TileIndex end_tile_tl;   ///< tl = top-left
 	TileIndex end_tile_br;   ///< br = bottom-right
-	byte start_direction;    ///< 0 to 3 or AI_PATHFINDER_NO_DIRECTION
-	byte end_direction;      ///< 0 to 3 or AI_PATHFINDER_NO_DIRECTION
+	DiagDirection start_direction; ///< 0 to 3 or AI_PATHFINDER_NO_DIRECTION
+	DiagDirection end_direction;   ///< 0 to 3 or AI_PATHFINDER_NO_DIRECTION
 
 	TileIndex route[500];
 	byte route_extra[500];   ///< Some extra information about the route like bridge/tunnel
@@ -127,8 +127,8 @@
 	TileIndex from_tile;
 	TileIndex to_tile;
 
-	byte from_direction;
-	byte to_direction;
+	DiagDirectionByte from_direction;
+	DiagDirectionByte to_direction;
 
 	bool from_deliver; ///< True if this is the station that GIVES cargo
 	bool to_deliver;
@@ -212,8 +212,8 @@
 
 void ChangeOwnershipOfPlayerItems(PlayerID old_player, PlayerID new_player);
 void GetNameOfOwner(Owner owner, TileIndex tile);
-Money CalculateCompanyValue(const Player* p);
-void InvalidatePlayerWindows(const Player* p);
+Money CalculateCompanyValue(const Player *p);
+void InvalidatePlayerWindows(const Player *p);
 void SetLocalPlayer(PlayerID new_player);
 #define FOR_ALL_PLAYERS(p) for (p = _players; p != endof(_players); p++)
 
@@ -236,7 +236,7 @@
 	return count;
 }
 
-static inline Player* GetPlayer(PlayerID i)
+static inline Player *GetPlayer(PlayerID i)
 {
 	assert(IS_INSIDE_1D(i, PLAYER_FIRST, lengthof(_players)));
 	return &_players[i];
@@ -282,7 +282,7 @@
  * @param p the player "in action"
  * @return The "best" railtype a player has available
  */
-static inline RailType GetBestRailtype(const Player* p)
+static inline RailType GetBestRailtype(const Player *p)
 {
 	if (HasRailtypeAvail(p, RAILTYPE_MAGLEV)) return RAILTYPE_MAGLEV;
 	if (HasRailtypeAvail(p, RAILTYPE_MONO)) return RAILTYPE_MONO;
--- a/src/player_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/player_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -197,7 +197,7 @@
 }
 
 static const WindowDesc _player_finances_desc = {
-	WDP_AUTO, WDP_AUTO, 407, 216,
+	WDP_AUTO, WDP_AUTO, 407, 216, 407, 216,
 	WC_FINANCES, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON,
 	_player_finances_widgets,
@@ -205,7 +205,7 @@
 };
 
 static const WindowDesc _player_finances_small_desc = {
-	WDP_AUTO, WDP_AUTO, 280, 60,
+	WDP_AUTO, WDP_AUTO, 280, 60, 280, 60,
 	WC_FINANCES, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON,
 	_player_finances_small_widgets,
@@ -213,7 +213,7 @@
 };
 
 static const WindowDesc _other_player_finances_desc = {
-	WDP_AUTO, WDP_AUTO, 407, 204,
+	WDP_AUTO, WDP_AUTO, 407, 204, 407, 204,
 	WC_FINANCES, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON,
 	_other_player_finances_widgets,
@@ -221,7 +221,7 @@
 };
 
 static const WindowDesc _other_player_finances_small_desc = {
-	WDP_AUTO, WDP_AUTO, 280, 48,
+	WDP_AUTO, WDP_AUTO, 280, 48, 280, 48,
 	WC_FINANCES, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON,
 	_other_player_finances_small_widgets,
@@ -480,7 +480,7 @@
 };
 
 static const WindowDesc _select_player_livery_2cc_desc = {
-	WDP_AUTO, WDP_AUTO, 400, 49 + 1 * 14,
+	WDP_AUTO, WDP_AUTO, 400, 49 + 1 * 14, 400, 49 + 1 * 14,
 	WC_PLAYER_COLOR, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_select_player_livery_2cc_widgets,
@@ -507,7 +507,7 @@
 };
 
 static const WindowDesc _select_player_livery_desc = {
-	WDP_AUTO, WDP_AUTO, 275, 49 + 1 * 14,
+	WDP_AUTO, WDP_AUTO, 275, 49 + 1 * 14, 275, 49 + 1 * 14,
 	WC_PLAYER_COLOR, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_select_player_livery_widgets,
@@ -599,7 +599,7 @@
 };
 
 static const WindowDesc _select_player_face_desc = {
-	WDP_AUTO, WDP_AUTO, 190, 149,
+	WDP_AUTO, WDP_AUTO, 190, 149, 190, 149,
 	WC_PLAYER_FACE, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_select_player_face_widgets,
@@ -912,7 +912,7 @@
 
 
 static const WindowDesc _player_company_desc = {
-	WDP_AUTO, WDP_AUTO, 360, 170,
+	WDP_AUTO, WDP_AUTO, 360, 170, 360, 170,
 	WC_COMPANY, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_player_company_widgets,
@@ -972,7 +972,7 @@
 };
 
 static const WindowDesc _buy_company_desc = {
-	153, 171, 334, 137,
+	153, 171, 334, 137, 334, 137,
 	WC_BUY_COMPANY, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_buy_company_widgets,
@@ -1092,7 +1092,7 @@
 };
 
 static const WindowDesc _highscore_desc = {
-	0, 0, 641, 481,
+	0, 0, 641, 481, 641, 481,
 	WC_HIGHSCORE, WC_NONE,
 	0,
 	_highscore_widgets,
@@ -1100,7 +1100,7 @@
 };
 
 static const WindowDesc _endgame_desc = {
-	0, 0, 641, 481,
+	0, 0, 641, 481, 641, 481,
 	WC_ENDSCREEN, WC_NONE,
 	0,
 	_highscore_widgets,
--- a/src/queue.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/queue.h	Fri Aug 03 18:10:15 2007 +0000
@@ -12,20 +12,20 @@
 
 
 struct Queue;
-typedef bool Queue_PushProc(Queue* q, void* item, int priority);
-typedef void* Queue_PopProc(Queue* q);
-typedef bool Queue_DeleteProc(Queue* q, void* item, int priority);
-typedef void Queue_ClearProc(Queue* q, bool free_values);
-typedef void Queue_FreeProc(Queue* q, bool free_values);
+typedef bool Queue_PushProc(Queue *q, void *item, int priority);
+typedef void* Queue_PopProc(Queue *q);
+typedef bool Queue_DeleteProc(Queue *q, void* item, int priority);
+typedef void Queue_ClearProc(Queue *q, bool free_values);
+typedef void Queue_FreeProc(Queue *q, bool free_values);
 
 struct InsSortNode {
-	void* item;
+	void *item;
 	int priority;
 	InsSortNode* next;
 };
 
 struct BinaryHeapNode {
-	void* item;
+	void *item;
 	int priority;
 };
 
@@ -35,39 +35,39 @@
 	 * Pushes an element into the queue, at the appropriate place for the queue.
 	 * Requires the queue pointer to be of an appropriate type, of course.
 	 */
-	Queue_PushProc* push;
+	Queue_PushProc *push;
 	/*
 	 * Pops the first element from the queue. What exactly is the first element,
 	 * is defined by the exact type of queue.
 	 */
-	Queue_PopProc* pop;
+	Queue_PopProc *pop;
 	/*
 	 * Deletes the item from the queue. priority should be specified if
 	 * known, which speeds up the deleting for some queue's. Should be -1
 	 * if not known.
 	 */
-	Queue_DeleteProc* del;
+	Queue_DeleteProc *del;
 
 	/* Clears the queue, by removing all values from it. It's state is
 	 * effectively reset. If free_items is true, each of the items cleared
 	 * in this way are free()'d.
 	 */
-	Queue_ClearProc* clear;
+	Queue_ClearProc *clear;
 	/* Frees the queue, by reclaiming all memory allocated by it. After
 	 * this it is no longer usable. If free_items is true, any remaining
 	 * items are free()'d too.
 	 */
-	Queue_FreeProc* free;
+	Queue_FreeProc *free;
 
 	union {
 		struct {
-			InsSortNode* first;
+			InsSortNode *first;
 		} inssort;
 		struct {
 			uint max_size;
 			uint size;
 			uint blocks; ///< The amount of blocks for which space is reserved in elements
-			BinaryHeapNode** elements;
+			BinaryHeapNode **elements;
 		} binaryheap;
 	} data;
 };
@@ -79,7 +79,7 @@
 
 /* Initializes a inssort and allocates internal memory. There is no maximum
  * size */
-void init_InsSort(Queue* q);
+void init_InsSort(Queue *q);
 
 
 /*
@@ -93,7 +93,7 @@
 
 /** Initializes a binary heap and allocates internal memory for maximum of
  * max_size elements */
-void init_BinaryHeap(Queue* q, uint max_size);
+void init_BinaryHeap(Queue *q, uint max_size);
 
 
 /*
@@ -102,8 +102,8 @@
 struct HashNode {
 	uint key1;
 	uint key2;
-	void* value;
-	HashNode* next;
+	void *value;
+	HashNode *next;
 };
 /**
  * Generates a hash code from the given key pair. You should make sure that
@@ -112,16 +112,16 @@
 typedef uint Hash_HashProc(uint key1, uint key2);
 struct Hash {
 	/* The hash function used */
-	Hash_HashProc* hash;
+	Hash_HashProc *hash;
 	/* The amount of items in the hash */
 	uint size;
 	/* The number of buckets allocated */
 	uint num_buckets;
 	/* A pointer to an array of num_buckets buckets. */
-	HashNode* buckets;
+	HashNode *buckets;
 	/* A pointer to an array of numbuckets booleans, which will be true if
 	 * there are any Nodes in the bucket */
-	bool* buckets_in_use;
+	bool *buckets_in_use;
 };
 
 /* Call these function to manipulate a hash */
@@ -129,32 +129,32 @@
 /** Deletes the value with the specified key pair from the hash and returns
  * that value. Returns NULL when the value was not present. The value returned
  * is _not_ free()'d! */
-void* Hash_Delete(Hash* h, uint key1, uint key2);
+void *Hash_Delete(Hash *h, uint key1, uint key2);
 /** Sets the value associated with the given key pair to the given value.
  * Returns the old value if the value was replaced, NULL when it was not yet present. */
-void* Hash_Set(Hash* h, uint key1, uint key2, void* value);
+void *Hash_Set(Hash *h, uint key1, uint key2, void *value);
 /** Gets the value associated with the given key pair, or NULL when it is not
  * present. */
-void* Hash_Get(const Hash* h, uint key1, uint key2);
+void *Hash_Get(const Hash *h, uint key1, uint key2);
 
 /* Call these function to create/destroy a hash */
 
 /** Builds a new hash in an existing struct. Make sure that hash() always
  * returns a hash less than num_buckets! Call delete_hash after use */
-void init_Hash(Hash* h, Hash_HashProc* hash, uint num_buckets);
+void init_Hash(Hash *h, Hash_HashProc *hash, uint num_buckets);
 /**
  * Deletes the hash and cleans up. Only cleans up memory allocated by new_Hash
  * & friends. If free is true, it will call free() on all the values that
  * are left in the hash.
  */
-void delete_Hash(Hash* h, bool free_values);
+void delete_Hash(Hash *h, bool free_values);
 /**
  * Cleans the hash, but keeps the memory allocated
  */
-void clear_Hash(Hash* h, bool free_values);
+void clear_Hash(Hash *h, bool free_values);
 /**
  * Gets the current size of the Hash
  */
-uint Hash_Size(const Hash* h);
+uint Hash_Size(const Hash *h);
 
 #endif /* QUEUE_H */
--- a/src/rail.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/rail.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -110,7 +110,7 @@
 		case MP_RAILWAY:
 			return GetRailType(tile);
 
-		case MP_STREET:
+		case MP_ROAD:
 			/* rail/road crossing */
 			if (IsLevelCrossing(tile)) return GetRailType(tile);
 			break;
--- a/src/rail.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/rail.h	Fri Aug 03 18:10:15 2007 +0000
@@ -9,14 +9,19 @@
 #include "direction.h"
 #include "tile.h"
 
+/**
+ * Enumeration for all possible railtypes.
+ *
+ * This enumeration defines all 4 possible railtypes.
+ */
 enum RailType {
-	RAILTYPE_BEGIN    = 0,
-	RAILTYPE_RAIL     = 0,
-	RAILTYPE_ELECTRIC = 1,
-	RAILTYPE_MONO     = 2,
-	RAILTYPE_MAGLEV   = 3,
-	RAILTYPE_END,
-	INVALID_RAILTYPE  = 0xFF
+	RAILTYPE_BEGIN    = 0,          ///< Used for iterations
+	RAILTYPE_RAIL     = 0,          ///< Standard non-electric rails
+	RAILTYPE_ELECTRIC = 1,          ///< Electric rails
+	RAILTYPE_MONO     = 2,          ///< Monorail
+	RAILTYPE_MAGLEV   = 3,          ///< Maglev
+	RAILTYPE_END,                   ///< Used for iterations
+	INVALID_RAILTYPE  = 0xFF        ///< Flag for invalid railtype
 };
 
 typedef byte RailTypeMask;
@@ -28,18 +33,20 @@
 typedef TinyEnumT<RailType> RailTypeByte;
 
 
-/** These are used to specify a single track.
- * Can be translated to a trackbit with TrackToTrackbit */
+/**
+ * These are used to specify a single track.
+ * Can be translated to a trackbit with TrackToTrackbit
+ */
 enum Track {
-	TRACK_BEGIN = 0,
-	TRACK_X     = 0,
-	TRACK_Y     = 1,
-	TRACK_UPPER = 2,
-	TRACK_LOWER = 3,
-	TRACK_LEFT  = 4,
-	TRACK_RIGHT = 5,
-	TRACK_END,
-	INVALID_TRACK = 0xFF
+	TRACK_BEGIN = 0,        ///< Used for iterations
+	TRACK_X     = 0,        ///< Track along the x-axis (north-east to south-west)
+	TRACK_Y     = 1,        ///< Track along the y-axis (north-west to south-east)
+	TRACK_UPPER = 2,        ///< Track in the upper corner of the tile (north)
+	TRACK_LOWER = 3,        ///< Track in the lower corner of the tile (south)
+	TRACK_LEFT  = 4,        ///< Track in the left corner of the tile (west)
+	TRACK_RIGHT = 5,        ///< Track in the right corner of the tile (east)
+	TRACK_END,              ///< Used for iterations
+	INVALID_TRACK = 0xFF    ///< Flag for an invalid track
 };
 
 /** Allow incrementing of Track variables */
@@ -49,10 +56,14 @@
 typedef TinyEnumT<Track> TrackByte;
 
 
-/** Convert an Axis to the corresponding Track
+/**
+ * Convert an Axis to the corresponding Track
  * AXIS_X -> TRACK_X
  * AXIS_Y -> TRACK_Y
  * Uses the fact that they share the same internal encoding
+ *
+ * @param a the axis to convert
+ * @return the track corresponding to the axis
  */
 static inline Track AxisToTrack(Axis a)
 {
@@ -62,25 +73,25 @@
 
 /** Bitfield corresponding to Track */
 enum TrackBits {
-	TRACK_BIT_NONE    = 0U,
-	TRACK_BIT_X       = 1U << TRACK_X,
-	TRACK_BIT_Y       = 1U << TRACK_Y,
-	TRACK_BIT_UPPER   = 1U << TRACK_UPPER,
-	TRACK_BIT_LOWER   = 1U << TRACK_LOWER,
-	TRACK_BIT_LEFT    = 1U << TRACK_LEFT,
-	TRACK_BIT_RIGHT   = 1U << TRACK_RIGHT,
-	TRACK_BIT_CROSS   = TRACK_BIT_X     | TRACK_BIT_Y,
-	TRACK_BIT_HORZ    = TRACK_BIT_UPPER | TRACK_BIT_LOWER,
-	TRACK_BIT_VERT    = TRACK_BIT_LEFT  | TRACK_BIT_RIGHT,
-	TRACK_BIT_3WAY_NE = TRACK_BIT_X     | TRACK_BIT_UPPER | TRACK_BIT_RIGHT,
-	TRACK_BIT_3WAY_SE = TRACK_BIT_Y     | TRACK_BIT_LOWER | TRACK_BIT_RIGHT,
-	TRACK_BIT_3WAY_SW = TRACK_BIT_X     | TRACK_BIT_LOWER | TRACK_BIT_LEFT,
-	TRACK_BIT_3WAY_NW = TRACK_BIT_Y     | TRACK_BIT_UPPER | TRACK_BIT_LEFT,
-	TRACK_BIT_ALL     = TRACK_BIT_CROSS | TRACK_BIT_HORZ  | TRACK_BIT_VERT,
-	TRACK_BIT_MASK    = 0x3FU,
-	TRACK_BIT_WORMHOLE = 0x40U,
-	TRACK_BIT_DEPOT   = 0x80U,
-	INVALID_TRACK_BIT = 0xFF
+	TRACK_BIT_NONE    = 0U,                                                 ///< No track
+	TRACK_BIT_X       = 1U << TRACK_X,                                      ///< X-axis track
+	TRACK_BIT_Y       = 1U << TRACK_Y,                                      ///< Y-axis track
+	TRACK_BIT_UPPER   = 1U << TRACK_UPPER,                                  ///< Upper track
+	TRACK_BIT_LOWER   = 1U << TRACK_LOWER,                                  ///< Lower track
+	TRACK_BIT_LEFT    = 1U << TRACK_LEFT,                                   ///< Left track
+	TRACK_BIT_RIGHT   = 1U << TRACK_RIGHT,                                  ///< Right track
+	TRACK_BIT_CROSS   = TRACK_BIT_X     | TRACK_BIT_Y,                      ///< X-Y-axis cross
+	TRACK_BIT_HORZ    = TRACK_BIT_UPPER | TRACK_BIT_LOWER,                  ///< Upper and lower track
+	TRACK_BIT_VERT    = TRACK_BIT_LEFT  | TRACK_BIT_RIGHT,                  ///< Left and right track
+	TRACK_BIT_3WAY_NE = TRACK_BIT_X     | TRACK_BIT_UPPER | TRACK_BIT_RIGHT,///< "Arrow" to the north-east
+	TRACK_BIT_3WAY_SE = TRACK_BIT_Y     | TRACK_BIT_LOWER | TRACK_BIT_RIGHT,///< "Arrow" to the south-east
+	TRACK_BIT_3WAY_SW = TRACK_BIT_X     | TRACK_BIT_LOWER | TRACK_BIT_LEFT, ///< "Arrow" to the south-west
+	TRACK_BIT_3WAY_NW = TRACK_BIT_Y     | TRACK_BIT_UPPER | TRACK_BIT_LEFT, ///< "Arrow" to the north-west
+	TRACK_BIT_ALL     = TRACK_BIT_CROSS | TRACK_BIT_HORZ  | TRACK_BIT_VERT, ///< All possible tracks
+	TRACK_BIT_MASK    = 0x3FU,                                              ///< Bitmask for the first 6 bits
+	TRACK_BIT_WORMHOLE = 0x40U,                                             ///< Bitflag for a wormhole (used for tunnels)
+	TRACK_BIT_DEPOT   = 0x80U,                                              ///< Bitflag for a depot
+	INVALID_TRACK_BIT = 0xFF                                                ///< Flag for an invalid trackbits value
 };
 
 /** Define basic enum properties */
@@ -91,70 +102,83 @@
 
 /**
  * Maps a Track to the corresponding TrackBits value
+ * @param track the track to convert
+ * @return the converted TrackBits value of the track
  */
 static inline TrackBits TrackToTrackBits(Track track)
 {
 	return (TrackBits)(1 << track);
 }
 
-
+/**
+ * Maps an Axis to the corresponding TrackBits value
+ * @param a the axis to convert
+ * @return the converted TrackBits value of the axis
+ */
 static inline TrackBits AxisToTrackBits(Axis a)
 {
 	return TrackToTrackBits(AxisToTrack(a));
 }
 
 
-/** These are a combination of tracks and directions. Values are 0-5 in one
+/**
+ * Enumeration for tracks and directions.
+ *
+ * These are a combination of tracks and directions. Values are 0-5 in one
  * direction (corresponding to the Track enum) and 8-13 in the other direction.
  * 6, 7, 14 and 15 are used to encode the reversing of road vehicles. Those
  * reversing track dirs are not considered to be 'valid' except in a small
  * corner in the road vehicle controller.
  */
 enum Trackdir {
-	TRACKDIR_BEGIN    =  0,
-	TRACKDIR_X_NE     =  0,
-	TRACKDIR_Y_SE     =  1,
-	TRACKDIR_UPPER_E  =  2,
-	TRACKDIR_LOWER_E  =  3,
-	TRACKDIR_LEFT_S   =  4,
-	TRACKDIR_RIGHT_S  =  5,
-	TRACKDIR_RVREV_NE =  6,
-	TRACKDIR_RVREV_SE =  7,
-	TRACKDIR_X_SW     =  8,
-	TRACKDIR_Y_NW     =  9,
-	TRACKDIR_UPPER_W  = 10,
-	TRACKDIR_LOWER_W  = 11,
-	TRACKDIR_LEFT_N   = 12,
-	TRACKDIR_RIGHT_N  = 13,
-	TRACKDIR_RVREV_SW = 14,
-	TRACKDIR_RVREV_NW = 15,
-	TRACKDIR_END,
-	INVALID_TRACKDIR  = 0xFF,
+	TRACKDIR_BEGIN    =  0,         ///< Used for iterations
+	TRACKDIR_X_NE     =  0,         ///< X-axis and direction to north-east
+	TRACKDIR_Y_SE     =  1,         ///< Y-axis and direction to south-east
+	TRACKDIR_UPPER_E  =  2,         ///< Upper track and direction to east
+	TRACKDIR_LOWER_E  =  3,         ///< Lower track and direction to east
+	TRACKDIR_LEFT_S   =  4,         ///< Left track and direction to south
+	TRACKDIR_RIGHT_S  =  5,         ///< Right track and direction to south
+	TRACKDIR_RVREV_NE =  6,         ///< (Road vehicle) reverse direction north-east
+	TRACKDIR_RVREV_SE =  7,         ///< (Road vehicle) reverse direction south-east
+	TRACKDIR_X_SW     =  8,         ///< X-axis and direction to south-west
+	TRACKDIR_Y_NW     =  9,         ///< Y-axis and direction to north-west
+	TRACKDIR_UPPER_W  = 10,         ///< Upper track and direction to west
+	TRACKDIR_LOWER_W  = 11,         ///< Lower track and direction to west
+	TRACKDIR_LEFT_N   = 12,         ///< Left track and direction to north
+	TRACKDIR_RIGHT_N  = 13,         ///< Right track and direction to north
+	TRACKDIR_RVREV_SW = 14,         ///< (Road vehicle) reverse direction south-west
+	TRACKDIR_RVREV_NW = 15,         ///< (Road vehicle) reverse direction north-west
+	TRACKDIR_END,                   ///< Used for iterations
+	INVALID_TRACKDIR  = 0xFF,       ///< Flag for an invalid trackdir
 };
 
 /** Define basic enum properties */
 template <> struct EnumPropsT<Trackdir> : MakeEnumPropsT<Trackdir, byte, TRACKDIR_BEGIN, TRACKDIR_END, INVALID_TRACKDIR> {};
 typedef TinyEnumT<Trackdir> TrackdirByte;
 
-/** These are a combination of tracks and directions. Values are 0-5 in one
- * direction (corresponding to the Track enum) and 8-13 in the other direction. */
+/**
+ * Enumeration of bitmasks for the TrackDirs
+ *
+ * These are a combination of tracks and directions. Values are 0-5 in one
+ * direction (corresponding to the Track enum) and 8-13 in the other direction.
+ */
 enum TrackdirBits {
-	TRACKDIR_BIT_NONE     = 0x0000,
-	TRACKDIR_BIT_X_NE     = 0x0001,
-	TRACKDIR_BIT_Y_SE     = 0x0002,
-	TRACKDIR_BIT_UPPER_E  = 0x0004,
-	TRACKDIR_BIT_LOWER_E  = 0x0008,
-	TRACKDIR_BIT_LEFT_S   = 0x0010,
-	TRACKDIR_BIT_RIGHT_S  = 0x0020,
+	TRACKDIR_BIT_NONE     = 0x0000, ///< No track build
+	TRACKDIR_BIT_X_NE     = 0x0001, ///< Track x-axis, direction north-east
+	TRACKDIR_BIT_Y_SE     = 0x0002, ///< Track y-axis, direction south-east
+	TRACKDIR_BIT_UPPER_E  = 0x0004, ///< Track upper, direction east
+	TRACKDIR_BIT_LOWER_E  = 0x0008, ///< Track lower, direction east
+	TRACKDIR_BIT_LEFT_S   = 0x0010, ///< Track left, direction south
+	TRACKDIR_BIT_RIGHT_S  = 0x0020, ///< Track right, direction south
 	/* Again, note the two missing values here. This enables trackdir -> track conversion by doing (trackdir & 0xFF) */
-	TRACKDIR_BIT_X_SW     = 0x0100,
-	TRACKDIR_BIT_Y_NW     = 0x0200,
-	TRACKDIR_BIT_UPPER_W  = 0x0400,
-	TRACKDIR_BIT_LOWER_W  = 0x0800,
-	TRACKDIR_BIT_LEFT_N   = 0x1000,
-	TRACKDIR_BIT_RIGHT_N  = 0x2000,
-	TRACKDIR_BIT_MASK     = 0x3F3F,
-	INVALID_TRACKDIR_BIT  = 0xFFFF,
+	TRACKDIR_BIT_X_SW     = 0x0100, ///< Track x-axis, direction south-west
+	TRACKDIR_BIT_Y_NW     = 0x0200, ///< Track y-axis, direction north-west
+	TRACKDIR_BIT_UPPER_W  = 0x0400, ///< Track upper, direction west
+	TRACKDIR_BIT_LOWER_W  = 0x0800, ///< Track lower, direction west
+	TRACKDIR_BIT_LEFT_N   = 0x1000, ///< Track left, direction north
+	TRACKDIR_BIT_RIGHT_N  = 0x2000, ///< Track right, direction north
+	TRACKDIR_BIT_MASK     = 0x3F3F, ///< Bitmask for bit-operations
+	INVALID_TRACKDIR_BIT  = 0xFFFF, ///< Flag for an invalid trackdirbit value
 };
 
 /** Define basic enum properties */
@@ -195,14 +219,14 @@
 	} gui_sprites;
 
 	struct {
-		CursorID rail_ns;
-		CursorID rail_swne;
-		CursorID rail_ew;
-		CursorID rail_nwse;
-		CursorID autorail;
-		CursorID depot;
-		CursorID tunnel;
-		CursorID convert;
+		CursorID rail_ns;    ///< Cursor for building rail in N-S direction
+		CursorID rail_swne;  ///< Cursor for building rail in X direction
+		CursorID rail_ew;    ///< Cursor for building rail in E-W direction
+		CursorID rail_nwse;  ///< Cursor for building rail in Y direction
+		CursorID autorail;   ///< Cursor for autorail tool
+		CursorID depot;      ///< Cursor for building a depot
+		CursorID tunnel;     ///< Cursor for building a tunnel
+		CursorID convert;    ///< Cursor for converting track
 	} cursor;
 
 	struct {
@@ -248,12 +272,28 @@
 
 /**
  * Maps a Trackdir to the corresponding TrackdirBits value
+ * @param trackdir the track direction to convert
+ * @return the converted TrackdirBits value
  */
-static inline TrackdirBits TrackdirToTrackdirBits(Trackdir trackdir) { return (TrackdirBits)(1 << trackdir); }
+static inline TrackdirBits TrackdirToTrackdirBits(Trackdir trackdir)
+{
+	return (TrackdirBits)(1 << trackdir);
+}
 
 /**
-* Removes first Track from TrackBits and returns it
-*/
+ * Removes first Track from TrackBits and returns it
+ *
+ * This function searchs for the first bit in the TrackBits,
+ * remove this bit from the parameter and returns the found
+ * bit as Track value. It returns INVALID_TRACK if the
+ * parameter was TRACK_BIT_NONE or INVALID_TRACK_BIT. This
+ * is basically used in while-loops to get up to 6 possible
+ * tracks on a tile until the parameter becomes TRACK_BIT_NONE.
+ *
+ * @param tracks The value with the TrackBits
+ * @return The first Track from the TrackBits value
+ * @see FindFirstTrack
+ */
 static inline Track RemoveFirstTrack(TrackBits *tracks)
 {
 	if (*tracks != TRACK_BIT_NONE && *tracks != INVALID_TRACK_BIT) {
@@ -265,8 +305,19 @@
 }
 
 /**
-* Removes first Trackdir from TrackdirBits and returns it
-*/
+ * Removes first Trackdir from TrackdirBits and returns it
+ *
+ * This function searchs for the first bit in the TrackdirBits parameter,
+ * remove this bit from the parameter and returns the fnound bit as
+ * Trackdir value. It returns INVALID_TRACKDIR if the trackdirs is
+ * TRACKDIR_BIT_NONE or INVALID_TRACKDIR_BIT. This is basically used in a
+ * while-loop to get all track-directions step by step until the value
+ * reaches TRACKDIR_BIT_NONE.
+ *
+ * @param trackdirs The value with the TrackdirBits
+ * @return The first Trackdir from the TrackdirBits value
+ * @see FindFirstTrackdir
+ */
 static inline Trackdir RemoveFirstTrackdir(TrackdirBits *trackdirs)
 {
 	if (*trackdirs != TRACKDIR_BIT_NONE && *trackdirs != INVALID_TRACKDIR_BIT) {
@@ -278,16 +329,31 @@
 }
 
 /**
-* Returns first Track from TrackBits or INVALID_TRACK
-*/
+ * Returns first Track from TrackBits or INVALID_TRACK
+ *
+ * This function returns the first Track found in the TrackBits value as Track-value.
+ * It returns INVALID_TRACK if the parameter is TRACK_BIT_NONE or INVALID_TRACK_BIT.
+ *
+ * @param tracks The TrackBits value
+ * @return The first Track found or INVALID_TRACK
+ * @see RemoveFirstTrack
+ */
 static inline Track FindFirstTrack(TrackBits tracks)
 {
 	return (tracks != TRACK_BIT_NONE && tracks != INVALID_TRACK_BIT) ? (Track)FIND_FIRST_BIT(tracks) : INVALID_TRACK;
 }
 
 /**
-* Converts TrackBits to Track. TrackBits must contain just one Track or INVALID_TRACK_BIT!
-*/
+ * Converts TrackBits to Track.
+ *
+ * This function converts a TrackBits value to a Track value. As it
+ * is not possible to convert two or more tracks to one track the
+ * parameter must contain only one track or be the INVALID_TRACK_BIT value.
+ *
+ * @param tracks The TrackBits value to convert
+ * @return The Track from the value or INVALID_TRACK
+ * @pre tracks must contains only one Track or be INVALID_TRACK_BIT
+ */
 static inline Track TrackBitsToTrack(TrackBits tracks)
 {
 	assert(tracks == INVALID_TRACK_BIT || (tracks != TRACK_BIT_NONE && KILL_FIRST_BIT(tracks & TRACK_BIT_MASK) == 0));
@@ -295,8 +361,17 @@
 }
 
 /**
-* Returns first Trackdir from TrackdirBits or INVALID_TRACKDIR
-*/
+ * Returns first Trackdir from TrackdirBits or INVALID_TRACKDIR
+ *
+ * This function returns the first Trackdir in the given TrackdirBits value or
+ * INVALID_TRACKDIR if the value is TRACKDIR_BIT_NONE. The TrackdirBits must
+ * not be INVALID_TRACKDIR_BIT.
+ *
+ * @param trackdirs The TrackdirBits value
+ * @return The first Trackdir from the TrackdirBits or INVALID_TRACKDIR on TRACKDIR_BIT_NONE.
+ * @pre trackdirs must not be INVALID_TRACKDIR_BIT
+ * @see RemoveFirstTrackdir
+ */
 static inline Trackdir FindFirstTrackdir(TrackdirBits trackdirs)
 {
 	assert((trackdirs & ~TRACKDIR_BIT_MASK) == TRACKDIR_BIT_NONE);
@@ -304,13 +379,30 @@
 }
 
 /**
- * These functions check the validity of Tracks and Trackdirs. assert against
- * them when convenient.
+ * Checks if a Track is valid.
+ *
+ * @param track The value to check
+ * @return true if the given value is a valid track.
+ * @note Use this in an assert()
  */
-static inline bool IsValidTrack(Track track) { return track < TRACK_END; }
-static inline bool IsValidTrackdir(Trackdir trackdir) { return (TrackdirToTrackdirBits(trackdir) & TRACKDIR_BIT_MASK) != 0; }
+static inline bool IsValidTrack(Track track)
+{
+	return track < TRACK_END;
+}
 
 /**
+ * Checks if a Trackdir is valid.
+ *
+ * @param trackdir The value to check
+ * @return true if the given valie is a valid Trackdir
+ * @note Use this in an assert()
+ */
+static inline bool IsValidTrackdir(Trackdir trackdir)
+{
+	return (TrackdirToTrackdirBits(trackdir) & TRACKDIR_BIT_MASK) != 0;
+}
+
+/*
  * Functions to map tracks to the corresponding bits in the signal
  * presence/status bytes in the map. You should not use these directly, but
  * wrapper functions below instead. XXX: Which are these?
@@ -354,6 +446,13 @@
 
 /**
  * Maps a trackdir to the reverse trackdir.
+ *
+ * Returns the reverse trackdir of a Trackdir value. The reverse trackdir
+ * is the same track with the other direction on it.
+ *
+ * @param trackdir The Trackdir value
+ * @return The reverse trackdir
+ * @pre trackdir must not be INVALID_TRACKDIR
  */
 static inline Trackdir ReverseTrackdir(Trackdir trackdir)
 {
@@ -363,20 +462,42 @@
 
 /**
  * Returns the Track that a given Trackdir represents
+ *
+ * This function filters the Track which is used in the Trackdir value and
+ * returns it as a Track value.
+ *
+ * @param trackdir The trackdir value
+ * @return The Track which is used in the value
  */
-static inline Track TrackdirToTrack(Trackdir trackdir) { return (Track)(trackdir & 0x7); }
+static inline Track TrackdirToTrack(Trackdir trackdir)
+{
+	return (Track)(trackdir & 0x7);
+}
 
 /**
- * Returns a Trackdir for the given Track. Since every Track corresponds to
- * two Trackdirs, we choose the one which points between NE and S.
- * Note that the actual implementation is quite futile, but this might change
+ * Returns a Trackdir for the given Track
+ *
+ * Since every Track corresponds to two Trackdirs, we choose the
+ * one which points between NE and S. Note that the actual
+ * implementation is quite futile, but this might change
  * in the future.
+ *
+ * @param track The given Track
+ * @return The Trackdir from the given Track
  */
-static inline Trackdir TrackToTrackdir(Track track) { return (Trackdir)track; }
+static inline Trackdir TrackToTrackdir(Track track)
+{
+	return (Trackdir)track;
+}
 
 /**
- * Returns a TrackdirBit mask that contains the two TrackdirBits that
+ * Returns a TrackdirBit mask from a given Track
+ *
+ * The TrackdirBit mask contains the two TrackdirBits that
  * correspond with the given Track (one for each direction).
+ *
+ * @param track The track to get the TrackdirBits from
+ * @return The TrackdirBits which the selected tracks
  */
 static inline TrackdirBits TrackToTrackdirBits(Track track)
 {
@@ -385,8 +506,12 @@
 }
 
 /**
- * Discards all directional information from the given TrackdirBits. Any
- * Track which is present in either direction will be present in the result.
+ * Discards all directional information from a TrackdirBits value
+ *
+ * Any Track which is present in either direction will be present in the result.
+ *
+ * @param bits The TrackdirBits to get the TrackBits from
+ * @return The TrackBits
  */
 static inline TrackBits TrackdirBitsToTrackBits(TrackdirBits bits)
 {
@@ -395,8 +520,13 @@
 
 /**
  * Maps a trackdir to the trackdir that you will end up on if you go straight
- * ahead. This will be the same trackdir for diagonal trackdirs, but a
+ * ahead.
+ *
+ * This will be the same trackdir for diagonal trackdirs, but a
  * different (alternating) one for straight trackdirs
+ *
+ * @param trackdir The given trackdir
+ * @return The next Trackdir value of the next tile.
  */
 static inline Trackdir NextTrackdir(Trackdir trackdir)
 {
@@ -406,6 +536,13 @@
 
 /**
  * Maps a track to all tracks that make 90 deg turns with it.
+ *
+ * For the diagonal directions these are the complement of the
+ * direction, for the straight directions these are the
+ * two vertical or horizontal tracks, depend on the given direction
+ *
+ * @param track The given track
+ * @return The TrackBits with the tracks marked which cross the given track by 90 deg.
  */
 static inline TrackBits TrackCrossesTracks(Track track)
 {
@@ -416,6 +553,14 @@
 /**
  * Maps a trackdir to the (4-way) direction the tile is exited when following
  * that trackdir.
+ *
+ * For the diagonal directions these are the same directions. For
+ * the straight directions these are the directions from the imagined
+ * base-tile to the bordering tile which will be joined if the given
+ * straight direction is leaved from the base-tile.
+ *
+ * @param trackdir The given track direction
+ * @return The direction which points to the resulting tile if following the Trackdir
  */
 static inline DiagDirection TrackdirToExitdir(Trackdir trackdir)
 {
@@ -426,6 +571,17 @@
 /**
  * Maps a track and an (4-way) dir to the trackdir that represents the track
  * with the exit in the given direction.
+ *
+ * For the diagonal tracks the resulting track direction are clear for a given
+ * DiagDirection. It either matches the direction or it returns INVALID_TRACKDIR,
+ * as a TRACK_X cannot be applied with DIAG_SE.
+ * For the straight tracks the resulting track direction will be the
+ * direction which the DiagDirection is pointing. But this will be INVALID_TRACKDIR
+ * if the DiagDirection is pointing 'away' the track.
+ *
+ * @param track The track to applie an direction on
+ * @param diagdir The DiagDirection to applie on
+ * @return The resulting track direction or INVALID_TRACKDIR if not possible.
  */
 static inline Trackdir TrackExitdirToTrackdir(Track track, DiagDirection diagdir)
 {
@@ -435,7 +591,20 @@
 
 /**
  * Maps a track and an (4-way) dir to the trackdir that represents the track
- * with the exit in the given direction.
+ * with the entry in the given direction.
+ *
+ * For the diagonal tracks the return value is clear, its either the matching
+ * track direction or INVALID_TRACKDIR.
+ * For the straight tracks this returns the track direction which results if
+ * you follow the DiagDirection and then turn by 45 deg left or right on the
+ * next tile. The new direction on the new track will be the returning Trackdir
+ * value. If the parameters makes no sense like the track TRACK_UPPER and the
+ * diraction DIAGDIR_NE (target track cannot be reached) this function returns
+ * INVALID_TRACKDIR.
+ *
+ * @param track The target track
+ * @param diagdir The direction to "come from"
+ * @return the resulting Trackdir or INVALID_TRACKDIR if not possible.
  */
 static inline Trackdir TrackEnterdirToTrackdir(Track track, DiagDirection diagdir)
 {
@@ -456,6 +625,9 @@
 /**
  * Maps a (4-way) direction to the diagonal trackdir that runs in that
  * direction.
+ *
+ * @param diagdir The direction
+ * @return The resulting Trackdir direction
  */
 static inline Trackdir DiagdirToDiagTrackdir(DiagDirection diagdir)
 {
@@ -465,8 +637,15 @@
 
 /**
  * Returns all trackdirs that can be reached when entering a tile from a given
- * (diagonal) direction. This will obviously include 90 degree turns, since no
- * information is available about the exact angle of entering */
+ * (diagonal) direction.
+ *
+ * This will obviously include 90 degree turns, since no information is available
+ * about the exact angle of entering
+ *
+ * @param diagdir The joining direction
+ * @return The TrackdirBits which can be used from the given direction
+ * @see DiagdirReachesTracks
+ */
 static inline TrackdirBits DiagdirReachesTrackdirs(DiagDirection diagdir)
 {
 	extern const TrackdirBits _exitdir_reaches_trackdirs[DIAGDIR_END];
@@ -475,26 +654,46 @@
 
 /**
  * Returns all tracks that can be reached when entering a tile from a given
- * (diagonal) direction. This will obviously include 90 degree turns, since no
- * information is available about the exact angle of entering */
+ * (diagonal) direction.
+ *
+ * This will obviously include 90 degree turns, since no
+ * information is available about the exact angle of entering
+ *
+ * @param diagdir The joining irection
+ * @return The tracks which can be used
+ * @see DiagdirReachesTrackdirs
+ */
 static inline TrackBits DiagdirReachesTracks(DiagDirection diagdir) { return TrackdirBitsToTrackBits(DiagdirReachesTrackdirs(diagdir)); }
 
 /**
  * Maps a trackdir to the trackdirs that can be reached from it (ie, when
- * entering the next tile. This will include 90 degree turns!
+ * entering the next tile.
+ *
+ * This will include 90 degree turns!
+ *
+ * @param trackdir The track direction which will be leaved
+ * @return The track directions which can be used from this direction (in the next tile)
  */
 static inline TrackdirBits TrackdirReachesTrackdirs(Trackdir trackdir)
 {
 	extern const TrackdirBits _exitdir_reaches_trackdirs[DIAGDIR_END];
 	return _exitdir_reaches_trackdirs[TrackdirToExitdir(trackdir)];
 }
-
 /* Note that there is no direct table for this function (there used to be),
  * but it uses two simpeler tables to achieve the result */
 
-
 /**
  * Maps a trackdir to all trackdirs that make 90 deg turns with it.
+ *
+ * For the diagonal tracks this returns the track direction bits
+ * of the other axis in both directions, which cannot be joined by
+ * the given track direction.
+ * For the straight tracks this returns all possible 90 deg turns
+ * either on the current tile (which no train can joined) or on the
+ * bordering tiles.
+ *
+ * @param trackdir The track direction
+ * @return The TrackdirBits which are (more or less) 90 deg turns.
  */
 static inline TrackdirBits TrackdirCrossesTrackdirs(Trackdir trackdir)
 {
@@ -502,13 +701,27 @@
 	return _track_crosses_trackdirs[TrackdirToTrack(trackdir)];
 }
 
+/**
+ * Checks if a given Track is diagonal
+ *
+ * @param track The given track to check
+ * @return true if diagonal, else false
+ */
+static inline bool IsDiagonalTrack(Track track)
+{
+	return (track == TRACK_X) || (track == TRACK_Y);
+}
 
-/* Checks if a given Track is diagonal */
-static inline bool IsDiagonalTrack(Track track) { return (track == TRACK_X) || (track == TRACK_Y); }
-
-/* Checks if a given Trackdir is diagonal. */
-static inline bool IsDiagonalTrackdir(Trackdir trackdir) { return IsDiagonalTrack(TrackdirToTrack(trackdir)); }
-
+/**
+ * Checks if a given Trackdir is diagonal.
+ *
+ * @param trackdir The given trackdir
+ * @return true if the trackdir use a diagonal track
+ */
+static inline bool IsDiagonalTrackdir(Trackdir trackdir)
+{
+	return IsDiagonalTrack(TrackdirToTrack(trackdir));
+}
 
 /**
  * Returns a pointer to the Railtype information for a given railtype
@@ -535,6 +748,14 @@
 	return HASBIT(GetRailTypeInfo(enginetype)->compatible_railtypes, tiletype);
 }
 
+/**
+ * Checks if an engine of the given RailType got power on a tile with a given
+ * RailType. This would normally just be an equality check, but for electric
+ * rails (which also support non-electric engines).
+ * @return Whether the engine got power on this tile.
+ * @param  enginetype The RailType of the engine we are considering.
+ * @param  tiletype   The RailType of the tile we are considering.
+ */
 static inline bool HasPowerOnRail(RailType enginetype, RailType tiletype)
 {
 	return HASBIT(GetRailTypeInfo(enginetype)->powered_railtypes, tiletype);
@@ -567,7 +788,7 @@
  */
 void DrawCatenary(const TileInfo *ti);
 
-uint GetRailFoundation(Slope tileh, TrackBits bits);
+Foundation GetRailFoundation(Slope tileh, TrackBits bits);
 
 int32 SettingsDisableElrail(int32 p1); ///< _patches.disable_elrail callback
 
--- a/src/rail_cmd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/rail_cmd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -37,6 +37,7 @@
 #include "newgrf_callbacks.h"
 #include "newgrf_station.h"
 #include "train.h"
+#include "misc/autoptr.hpp"
 
 const byte _track_sloped_sprites[14] = {
 	14, 15, 22, 13,
@@ -156,36 +157,22 @@
 }
 };
 
-uint GetRailFoundation(Slope tileh, TrackBits bits)
+Foundation GetRailFoundation(Slope tileh, TrackBits bits)
 {
-	uint i;
-
 	if (!IsSteepSlope(tileh)) {
-		if ((~_valid_tileh_slopes[0][tileh] & bits) == 0) return 0;
-		if ((~_valid_tileh_slopes[1][tileh] & bits) == 0) return tileh;
+		if ((~_valid_tileh_slopes[0][tileh] & bits) == 0) return FOUNDATION_NONE;
+		if ((~_valid_tileh_slopes[1][tileh] & bits) == 0) return FOUNDATION_LEVELED;
 	}
 
 	switch (bits) {
 		default: NOT_REACHED();
-		case TRACK_BIT_X: i = 0; break;
-		case TRACK_BIT_Y: i = 1; break;
-		case TRACK_BIT_LEFT:  return 15 + 8 + (tileh == SLOPE_STEEP_W ? 4 : 0);
-		case TRACK_BIT_LOWER: return 15 + 8 + (tileh == SLOPE_STEEP_S ? 5 : 1);
-		case TRACK_BIT_RIGHT: return 15 + 8 + (tileh == SLOPE_STEEP_E ? 6 : 2);
-		case TRACK_BIT_UPPER: return 15 + 8 + (tileh == SLOPE_STEEP_N ? 7 : 3);
+		case TRACK_BIT_X:     return FOUNDATION_INCLINED_X;
+		case TRACK_BIT_Y:     return FOUNDATION_INCLINED_Y;
+		case TRACK_BIT_LEFT:  return (tileh == SLOPE_STEEP_W ? FOUNDATION_STEEP_HIGHER : FOUNDATION_STEEP_LOWER);
+		case TRACK_BIT_LOWER: return (tileh == SLOPE_STEEP_S ? FOUNDATION_STEEP_HIGHER : FOUNDATION_STEEP_LOWER);
+		case TRACK_BIT_RIGHT: return (tileh == SLOPE_STEEP_E ? FOUNDATION_STEEP_HIGHER : FOUNDATION_STEEP_LOWER);
+		case TRACK_BIT_UPPER: return (tileh == SLOPE_STEEP_N ? FOUNDATION_STEEP_HIGHER : FOUNDATION_STEEP_LOWER);
 	}
-	switch (tileh) {
-		case SLOPE_W:
-		case SLOPE_STEEP_W: i += 0; break;
-		case SLOPE_S:
-		case SLOPE_STEEP_S: i += 2; break;
-		case SLOPE_E:
-		case SLOPE_STEEP_E: i += 4; break;
-		case SLOPE_N:
-		case SLOPE_STEEP_N: i += 6; break;
-		default: return 0;
-	}
-	return i + 15;
 }
 
 
@@ -279,7 +266,7 @@
 			}
 			break;
 
-		case MP_STREET:
+		case MP_ROAD:
 #define M(x) (1 << (x))
 			/* Level crossings may only be built on these slopes */
 			if (!HASBIT(M(SLOPE_SEN) | M(SLOPE_ENW) | M(SLOPE_NWS) | M(SLOPE_NS) | M(SLOPE_WSE) | M(SLOPE_EW) | M(SLOPE_FLAT), tileh)) {
@@ -368,7 +355,7 @@
 	SET_EXPENSES_TYPE(EXPENSES_CONSTRUCTION);
 
 	switch (GetTileType(tile)) {
-		case MP_STREET: {
+		case MP_ROAD: {
 			if (!IsLevelCrossing(tile) ||
 					GetCrossingRailBits(tile) != trackbit ||
 					(_current_player != OWNER_WATER && !CheckTileOwnership(tile)) ||
@@ -588,7 +575,6 @@
  */
 CommandCost CmdBuildTrainDepot(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 {
-	Depot *d;
 	CommandCost cost;
 	Slope tileh;
 
@@ -623,18 +609,20 @@
 
 	if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
 
-	d = AllocateDepot();
+	Depot *d = new Depot(tile);
+
 	if (d == NULL) return CMD_ERROR;
+	AutoPtrT<Depot> d_auto_delete = d;
 
 	if (flags & DC_EXEC) {
 		MakeRailDepot(tile, _current_player, dir, (RailType)p1);
 		MarkTileDirtyByTile(tile);
 
-		d->xy = tile;
 		d->town_index = ClosestTownFromTile(tile, (uint)-1)->index;
 
 		UpdateSignalsOnSegment(tile, dir);
 		YapfNotifyTrackLayoutChange(tile, TrackdirToTrack(DiagdirToDiagTrackdir(dir)));
+		d_auto_delete.Detach();
 	}
 
 	return cost.AddCost(_price.build_train_depot);
@@ -771,7 +759,7 @@
 			}
 			return true;
 
-		case MP_STREET:
+		case MP_ROAD:
 			if (!IsLevelCrossing(tile)) return false;
 			signal_ctr += 2;
 			return true;
@@ -1090,7 +1078,7 @@
 			switch (GetTileType(tile)) {
 				case MP_RAILWAY:      proc = DoConvertRail;             break;
 				case MP_STATION:      proc = DoConvertStationRail;      break;
-				case MP_STREET:       proc = DoConvertStreetRail;       break;
+				case MP_ROAD:         proc = DoConvertStreetRail;       break;
 				case MP_TUNNELBRIDGE: proc = DoConvertTunnelBridgeRail; break;
 				default: continue;
 			}
@@ -1124,7 +1112,8 @@
 	if (flags & DC_EXEC) {
 		DiagDirection dir = GetRailDepotDirection(tile);
 
-		DeleteDepot(GetDepotByTile(tile));
+		DoClearSquare(tile);
+		delete GetDepotByTile(tile);
 		UpdateSignalsOnSegment(tile, dir);
 		YapfNotifyTrackLayoutChange(tile, TrackdirToTrack(DiagdirToDiagTrackdir(dir)));
 	}
@@ -1225,16 +1214,16 @@
 
 static void DrawTrackFence_NW(const TileInfo *ti)
 {
-	SpriteID image = 0x515;
-	if (ti->tileh != SLOPE_FLAT) image = (ti->tileh & SLOPE_S) ? 0x519 : 0x51B;
+	SpriteID image = SPR_TRACK_FENCE_FLAT_X;
+	if (ti->tileh != SLOPE_FLAT) image = (ti->tileh & SLOPE_S) ? SPR_TRACK_FENCE_SLOPE_SW : SPR_TRACK_FENCE_SLOPE_NE;
 	AddSortableSpriteToDraw(image, _drawtile_track_palette,
 		ti->x, ti->y + 1, 16, 1, 4, ti->z);
 }
 
 static void DrawTrackFence_SE(const TileInfo *ti)
 {
-	SpriteID image = 0x515;
-	if (ti->tileh != SLOPE_FLAT) image = (ti->tileh & SLOPE_S) ? 0x519 : 0x51B;
+	SpriteID image = SPR_TRACK_FENCE_FLAT_X;
+	if (ti->tileh != SLOPE_FLAT) image = (ti->tileh & SLOPE_S) ? SPR_TRACK_FENCE_SLOPE_SW : SPR_TRACK_FENCE_SLOPE_NE;
 	AddSortableSpriteToDraw(image, _drawtile_track_palette,
 		ti->x, ti->y + TILE_SIZE - 1, 16, 1, 4, ti->z);
 }
@@ -1247,16 +1236,16 @@
 
 static void DrawTrackFence_NE(const TileInfo *ti)
 {
-	SpriteID image = 0x516;
-	if (ti->tileh != SLOPE_FLAT) image = (ti->tileh & SLOPE_S) ? 0x51A : 0x51C;
+	SpriteID image = SPR_TRACK_FENCE_FLAT_Y;
+	if (ti->tileh != SLOPE_FLAT) image = (ti->tileh & SLOPE_S) ? SPR_TRACK_FENCE_SLOPE_SE : SPR_TRACK_FENCE_SLOPE_NW;
 	AddSortableSpriteToDraw(image, _drawtile_track_palette,
 		ti->x + 1, ti->y, 1, 16, 4, ti->z);
 }
 
 static void DrawTrackFence_SW(const TileInfo *ti)
 {
-	SpriteID image = 0x516;
-	if (ti->tileh != SLOPE_FLAT) image = (ti->tileh & SLOPE_S) ? 0x51A : 0x51C;
+	SpriteID image = SPR_TRACK_FENCE_FLAT_Y;
+	if (ti->tileh != SLOPE_FLAT) image = (ti->tileh & SLOPE_S) ? SPR_TRACK_FENCE_SLOPE_SE : SPR_TRACK_FENCE_SLOPE_NW;
 	AddSortableSpriteToDraw(image, _drawtile_track_palette,
 		ti->x + TILE_SIZE - 1, ti->y, 1, 16, 4, ti->z);
 }
@@ -1267,35 +1256,47 @@
 	DrawTrackFence_SW(ti);
 }
 
+/**
+ * Draw fence at eastern side of track.
+ */
 static void DrawTrackFence_NS_1(const TileInfo *ti)
 {
 	int z = ti->z;
 	if (ti->tileh & SLOPE_W) z += TILE_HEIGHT;
-	AddSortableSpriteToDraw(0x517, _drawtile_track_palette,
+	AddSortableSpriteToDraw(SPR_TRACK_FENCE_FLAT_VERT, _drawtile_track_palette,
 		ti->x + TILE_SIZE / 2, ti->y + TILE_SIZE / 2, 1, 1, 4, z);
 }
 
+/**
+ * Draw fence at western side of track.
+ */
 static void DrawTrackFence_NS_2(const TileInfo *ti)
 {
 	int z = ti->z;
 	if (ti->tileh & SLOPE_E) z += TILE_HEIGHT;
-	AddSortableSpriteToDraw(0x517, _drawtile_track_palette,
+	AddSortableSpriteToDraw(SPR_TRACK_FENCE_FLAT_VERT, _drawtile_track_palette,
 		ti->x + TILE_SIZE / 2, ti->y + TILE_SIZE / 2, 1, 1, 4, z);
 }
 
+/**
+ * Draw fence at southern side of track.
+ */
 static void DrawTrackFence_WE_1(const TileInfo *ti)
 {
 	int z = ti->z;
 	if (ti->tileh & SLOPE_N) z += TILE_HEIGHT;
-	AddSortableSpriteToDraw(0x518, _drawtile_track_palette,
+	AddSortableSpriteToDraw(SPR_TRACK_FENCE_FLAT_HORZ, _drawtile_track_palette,
 		ti->x + TILE_SIZE / 2, ti->y + TILE_SIZE / 2, 1, 1, 4, z);
 }
 
+/**
+ * Draw fence at northern side of track.
+ */
 static void DrawTrackFence_WE_2(const TileInfo *ti)
 {
 	int z = ti->z;
 	if (ti->tileh & SLOPE_S) z += TILE_HEIGHT;
-	AddSortableSpriteToDraw(0x518, _drawtile_track_palette,
+	AddSortableSpriteToDraw(SPR_TRACK_FENCE_FLAT_HORZ, _drawtile_track_palette,
 		ti->x + TILE_SIZE / 2, ti->y + TILE_SIZE / 2, 1, 1, 4, z);
 }
 
@@ -1350,14 +1351,11 @@
 	(image++, true);
 
 	if (ti->tileh != SLOPE_FLAT) {
-		uint foundation = GetRailFoundation(ti->tileh, track);
-
-		if (foundation != 0) DrawFoundation(ti, foundation);
+		DrawFoundation(ti, GetRailFoundation(ti->tileh, track));
 
 		/* DrawFoundation() modifies it.
 		 * Default sloped sprites.. */
-		if (ti->tileh != SLOPE_FLAT)
-			image = _track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.track_y;
+		if (ti->tileh != SLOPE_FLAT) image = _track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.track_y;
 	}
 
 	switch (GetRailGroundType(ti->tile)) {
@@ -1434,7 +1432,7 @@
 		const DrawTileSeqStruct* dtss;
 		uint32 relocation;
 
-		if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, ti->tileh);
+		if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
 
 		if (IsRailDepot(ti->tile)) {
 			dts = &_depot_gfx_table[GetRailDepotDirection(ti->tile)];
@@ -1514,10 +1512,7 @@
 				image += relocation;
 			}
 
-			if (HASBIT(_transparent_opt, TO_BUILDINGS)) {
-				SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
-				pal = PALETTE_TO_TRANSPARENT;
-			} else if (HASBIT(image, PALETTE_MODIFIER_COLOR)) {
+			if (!HASBIT(_transparent_opt, TO_BUILDINGS) && HASBIT(image, PALETTE_MODIFIER_COLOR)) {
 				pal = _drawtile_track_palette;
 			} else {
 				pal = dtss->pal;
@@ -1528,7 +1523,8 @@
 					image, pal,
 					ti->x + dtss->delta_x, ti->y + dtss->delta_y,
 					dtss->size_x, dtss->size_y,
-					dtss->size_z, ti->z + dtss->delta_z
+					dtss->size_z, ti->z + dtss->delta_z,
+					HASBIT(_transparent_opt, TO_BUILDINGS)
 				);
 			} else {
 				AddChildSpriteScreen(image, pal, dtss->delta_x, dtss->delta_y);
@@ -1676,13 +1672,10 @@
 		/* check for a vehicle with that trackdir on the end tile of the tunnel */
 		if (VehicleFromPos(end, &dest, SignalVehicleCheckProc) != NULL) return true;
 
-		/* now check all tiles from start to end for a warping vehicle
-		 * NOTE: the hashes for tiles may overlap, so this could maybe be optimised a bit by not checking every tile? */
+		/* now check all tiles from start to end for a warping vehicle */
 		dest.track = 0x40;   //Vehicle inside a tunnel or on a bridge
-		for (; tile != end; tile += TileOffsByDiagDir(direction)) {
-			if (VehicleFromPos(tile, &dest, SignalVehicleCheckProc) != NULL)
-				return true;
-		}
+		if (VehicleFromPos(tile, &dest, SignalVehicleCheckProc) != NULL) return true;
+		if (VehicleFromPos(end, &dest, SignalVehicleCheckProc) != NULL) return true;
 
 		/* no vehicle found */
 		return false;
@@ -1840,34 +1833,16 @@
 
 	if (tileh == SLOPE_FLAT) return z;
 	if (IsPlainRailTile(tile)) {
-		uint f = GetRailFoundation(tileh, GetTrackBits(tile));
-
-		if (f != 0) {
-			if (IsSteepSlope(tileh)) {
-				z += TILE_HEIGHT;
-			} else if (f < 15) {
-				return z + TILE_HEIGHT; // leveled foundation
-			}
-			tileh = _inclined_tileh[f - 15]; // inclined foundation
-		}
+		z += ApplyFoundationToSlope(GetRailFoundation(tileh, GetTrackBits(tile)), &tileh);
 		return z + GetPartialZ(x & 0xF, y & 0xF, tileh);
 	} else {
 		return z + TILE_HEIGHT;
 	}
 }
 
-static Slope GetSlopeTileh_Track(TileIndex tile, Slope tileh)
+static Foundation GetFoundation_Track(TileIndex tile, Slope tileh)
 {
-	if (tileh == SLOPE_FLAT) return SLOPE_FLAT;
-	if (IsPlainRailTile(tile)) {
-		uint f = GetRailFoundation(tileh, GetTrackBits(tile));
-
-		if (f == 0) return tileh;
-		if (f < 15) return SLOPE_FLAT; // leveled foundation
-		return _inclined_tileh[f - 15]; // inclined foundation
-	} else {
-		return SLOPE_FLAT;
-	}
+	return IsPlainRailTile(tile) ? GetRailFoundation(tileh, GetTrackBits(tile)) : FlatteningFoundation(tileh);
 }
 
 static void GetAcceptedCargo_Track(TileIndex tile, AcceptedCargo ac)
@@ -2176,5 +2151,5 @@
 	ChangeTileOwner_Track,    /* change_tile_owner_clear */
 	NULL,                     /* get_produced_cargo_proc */
 	VehicleEnter_Track,       /* vehicle_enter_tile_proc */
-	GetSlopeTileh_Track,      /* get_slope_tileh_proc */
+	GetFoundation_Track,      /* get_foundation_proc */
 };
--- a/src/rail_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/rail_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -600,7 +600,7 @@
 };
 
 static const WindowDesc _build_rail_desc = {
-	WDP_ALIGN_TBR, 22, 350, 36,
+	WDP_ALIGN_TBR, 22, 350, 36, 350, 36,
 	WC_BUILD_TOOLBAR, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
 	_build_rail_widgets,
@@ -1023,7 +1023,7 @@
 };
 
 static const WindowDesc _station_builder_desc = {
-	WDP_AUTO, WDP_AUTO, 148, 200,
+	WDP_AUTO, WDP_AUTO, 148, 200, 148, 200,
 	WC_BUILD_STATION, WC_BUILD_TOOLBAR,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_station_builder_widgets,
@@ -1031,7 +1031,7 @@
 };
 
 static const WindowDesc _newstation_builder_desc = {
-	WDP_AUTO, WDP_AUTO, 148, 290,
+	WDP_AUTO, WDP_AUTO, 148, 290, 148, 290,
 	WC_BUILD_STATION, WC_BUILD_TOOLBAR,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_newstation_builder_widgets,
@@ -1110,7 +1110,7 @@
 };
 
 static const WindowDesc _build_depot_desc = {
-	WDP_AUTO, WDP_AUTO, 140, 122,
+	WDP_AUTO, WDP_AUTO, 140, 122, 140, 122,
 	WC_BUILD_DEPOT, WC_BUILD_TOOLBAR,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_build_depot_widgets,
@@ -1196,7 +1196,7 @@
 };
 
 static const WindowDesc _build_waypoint_desc = {
-	WDP_AUTO, WDP_AUTO, 344, 92,
+	WDP_AUTO, WDP_AUTO, 344, 92, 344, 92,
 	WC_BUILD_DEPOT, WC_BUILD_TOOLBAR,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_build_waypoint_widgets,
--- a/src/rail_map.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/rail_map.h	Fri Aug 03 18:10:15 2007 +0000
@@ -389,8 +389,8 @@
 	RAIL_GROUND_FENCE_NE     =  5, ///< Grass with a fence at the NE edge
 	RAIL_GROUND_FENCE_SW     =  6, ///< Grass with a fence at the SW edge
 	RAIL_GROUND_FENCE_NESW   =  7, ///< Grass with a fence at the NE and SW edges
-	RAIL_GROUND_FENCE_VERT1  =  8, ///< Grass with a fence at the western side
-	RAIL_GROUND_FENCE_VERT2  =  9, ///< Grass with a fence at the eastern side
+	RAIL_GROUND_FENCE_VERT1  =  8, ///< Grass with a fence at the eastern side
+	RAIL_GROUND_FENCE_VERT2  =  9, ///< Grass with a fence at the western side
 	RAIL_GROUND_FENCE_HORIZ1 = 10, ///< Grass with a fence at the southern side
 	RAIL_GROUND_FENCE_HORIZ2 = 11, ///< Grass with a fence at the northern side
 	RAIL_GROUND_ICE_DESERT   = 12, ///< Icy or sandy
--- a/src/road.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/road.h	Fri Aug 03 18:10:15 2007 +0000
@@ -9,30 +9,31 @@
 
 /**
  * The different roadtypes we support
- * @note currently only ROADTYPE_ROAD is supported.
+ *
+ * @note currently only ROADTYPE_ROAD and ROADTYPE_TRAM are supported.
  */
 enum RoadType {
-	ROADTYPE_ROAD = 0,
-	ROADTYPE_TRAM = 1,
-	ROADTYPE_HWAY = 2, ///< Only a placeholder. Not sure what we are going to do with this road type.
-	ROADTYPE_END,
-	INVALID_ROADTYPE = 0xFF
+	ROADTYPE_ROAD = 0,      ///< Basic road type
+	ROADTYPE_TRAM = 1,      ///< Trams
+	ROADTYPE_HWAY = 2,      ///< Only a placeholder. Not sure what we are going to do with this road type.
+	ROADTYPE_END,           ///< Used for iterations
+	INVALID_ROADTYPE = 0xFF ///< flag for invalid roadtype
 };
 DECLARE_POSTFIX_INCREMENT(RoadType);
 
 /**
  * The different roadtypes we support, but then a bitmask of them
- * @note currently only ROADTYPES_ROAD is supported.
+ * @note currently only roadtypes with ROADTYPE_ROAD and ROADTYPE_TRAM are supported.
  */
 enum RoadTypes {
-	ROADTYPES_NONE     = 0,
-	ROADTYPES_ROAD     = 1 << ROADTYPE_ROAD,
-	ROADTYPES_TRAM     = 1 << ROADTYPE_TRAM,
-	ROADTYPES_HWAY     = 1 << ROADTYPE_HWAY,
-	ROADTYPES_ROADTRAM = ROADTYPES_ROAD | ROADTYPES_TRAM,
-	ROADTYPES_ROADHWAY = ROADTYPES_ROAD | ROADTYPES_HWAY,
-	ROADTYPES_TRAMHWAY = ROADTYPES_TRAM | ROADTYPES_HWAY,
-	ROADTYPES_ALL      = ROADTYPES_ROAD | ROADTYPES_TRAM | ROADTYPES_HWAY,
+	ROADTYPES_NONE     = 0,                                                 ///< No roadtypes
+	ROADTYPES_ROAD     = 1 << ROADTYPE_ROAD,                                ///< Road
+	ROADTYPES_TRAM     = 1 << ROADTYPE_TRAM,                                ///< Trams
+	ROADTYPES_HWAY     = 1 << ROADTYPE_HWAY,                                ///< Highway (or whatever substitute)
+	ROADTYPES_ROADTRAM = ROADTYPES_ROAD | ROADTYPES_TRAM,                   ///< Road + trams
+	ROADTYPES_ROADHWAY = ROADTYPES_ROAD | ROADTYPES_HWAY,                   ///< Road + highway (or whatever substitute)
+	ROADTYPES_TRAMHWAY = ROADTYPES_TRAM | ROADTYPES_HWAY,                   ///< Trams + highway (or whatever substitute)
+	ROADTYPES_ALL      = ROADTYPES_ROAD | ROADTYPES_TRAM | ROADTYPES_HWAY,  ///< Road + trams + highway (or whatever substitute)
 };
 DECLARE_ENUM_AS_BIT_SET(RoadTypes);
 
@@ -58,47 +59,91 @@
 
 /**
  * Maps a RoadType to the corresponding RoadTypes value
+ *
+ * @param rt the roadtype to get the roadtypes from
+ * @return the roadtypes with the given roadtype
  */
 static inline RoadTypes RoadTypeToRoadTypes(RoadType rt)
 {
 	return (RoadTypes)(1 << rt);
 }
 
+/**
+ * Returns the RoadTypes which are not present in the given RoadTypes
+ *
+ * This function returns the complement of a given RoadTypes.
+ *
+ * @param r The given RoadTypes
+ * @return The complement of the given RoadTypes
+ * @note The unused value ROADTYPES_HWAY will be used, too.
+ */
 static inline RoadTypes ComplementRoadTypes(RoadTypes r)
 {
 	return (RoadTypes)(ROADTYPES_ALL ^ r);
 }
 
+/**
+ * Enumeration for the road parts on a tile.
+ *
+ * This enumeration defines the possible road parts which
+ * can be build on a tile.
+ */
 enum RoadBits {
-	ROAD_NONE = 0U,
-	ROAD_NW  = 1U,
-	ROAD_SW  = 2U,
-	ROAD_SE  = 4U,
-	ROAD_NE  = 8U,
-	ROAD_X   = ROAD_SW | ROAD_NE,
-	ROAD_Y   = ROAD_NW | ROAD_SE,
-	ROAD_ALL = ROAD_X  | ROAD_Y
+	ROAD_NONE = 0U,                  ///< No road-part is build
+	ROAD_NW   = 1U,                  ///< North-west part
+	ROAD_SW   = 2U,                  ///< South-west part
+	ROAD_SE   = 4U,                  ///< South-east part
+	ROAD_NE   = 8U,                  ///< North-east part
+	ROAD_X    = ROAD_SW | ROAD_NE,   ///< Full road along the x-axis (south-west + north-east)
+	ROAD_Y    = ROAD_NW | ROAD_SE,   ///< Full road along the y-axis (north-west + south-east)
+	ROAD_ALL  = ROAD_X  | ROAD_Y     ///< Full 4-way crossing
 };
 
 DECLARE_ENUM_AS_BIT_SET(RoadBits);
 
+/**
+ * Calculate the complement of a RoadBits value
+ *
+ * Simply flips all bits in the RoadBits value to get the complement
+ * of the RoadBits.
+ *
+ * @param r The given RoadBits value
+ * @return the complement
+ */
 static inline RoadBits ComplementRoadBits(RoadBits r)
 {
 	return (RoadBits)(ROAD_ALL ^ r);
 }
 
+/**
+ * Create the road-part which belongs to the given DiagDirection
+ *
+ * This function returns a RoadBits value which belongs to
+ * the given DiagDirection.
+ *
+ * @param d The DiagDirection
+ * @return The result RoadBits which the selected road-part set
+ */
 static inline RoadBits DiagDirToRoadBits(DiagDirection d)
 {
 	return (RoadBits)(1U << (3 ^ d));
 }
 
-/** Checks whether the trackdir means that we are reversing */
+/**
+ * Checks whether the trackdir means that we are reversing.
+ * @param dir the trackdir to check
+ * @return true if it is a reversing road trackdir
+ */
 static inline bool IsReversingRoadTrackdir(Trackdir dir)
 {
 	return (dir & 0x07) >= 6;
 }
 
-/** Checks whether the given trackdir is a straight road */
+/**
+ * Checks whether the given trackdir is a straight road
+ * @param dir the trackdir to check
+ * @return true if it is a straight road trackdir
+ */
 static inline bool IsStraightRoadTrackdir(Trackdir dir)
 {
 	return (dir & 0x06) == 0;
@@ -115,6 +160,11 @@
  */
 bool CheckAllowRemoveRoad(TileIndex tile, RoadBits remove, Owner owner, bool *edge_road, RoadType rt);
 
+/**
+ * Draw the catenary for tram road bits
+ * @param ti   information about the tile (position, slope)
+ * @param tram the roadbits to draw the catenary for
+ */
 void DrawTramCatenary(TileInfo *ti, RoadBits tram);
 
 #endif /* ROAD_H */
--- a/src/road_cmd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/road_cmd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -31,6 +31,7 @@
 #include "newgrf.h"
 #include "station_map.h"
 #include "tunnel_map.h"
+#include "misc/autoptr.hpp"
 
 
 static uint CountRoadBits(RoadBits r)
@@ -124,7 +125,7 @@
 
 	Town *t = NULL;
 	switch (GetTileType(tile)) {
-		case MP_STREET:
+		case MP_ROAD:
 			if (_game_mode != GM_EDITOR && GetRoadOwner(tile, rt) == OWNER_TOWN) t = GetTownByTile(tile);
 			break;
 
@@ -154,7 +155,7 @@
 	 * removal allowance depends on difficulty setting */
 	if (!CheckforTownRating(flags, t, ROAD_REMOVE)) return CMD_ERROR;
 
-	if (!IsTileType(tile, MP_STREET)) {
+	if (!IsTileType(tile, MP_ROAD)) {
 		/* If it's the last roadtype, just clear the whole tile */
 		if (rts == RoadTypeToRoadTypes(rt)) return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
 
@@ -298,10 +299,11 @@
 	RoadBits road_bits;
 
 	if (IsSteepSlope(tileh)) {
-		if (existing == 0) {
-			/* force full pieces. */
-			*pieces |= (RoadBits)((*pieces & 0xC) >> 2);
-			*pieces |= (RoadBits)((*pieces & 0x3) << 2);
+		/* force full pieces. */
+		*pieces |= (RoadBits)((*pieces & 0xC) >> 2);
+		*pieces |= (RoadBits)((*pieces & 0x3) << 2);
+
+		if (existing == 0 || existing == *pieces) {
 			if (*pieces == ROAD_X || *pieces == ROAD_Y) return _price.terraform;
 		}
 		return CMD_ERROR;
@@ -320,11 +322,12 @@
 		return CommandCost(existing != 0 ? 0 : _price.terraform);
 	}
 
+	*pieces |= (RoadBits)((*pieces & 0xC) >> 2);
+	*pieces |= (RoadBits)((*pieces & 0x3) << 2);
+
 	/* partly leveled up tile, only if there's no road on that tile */
-	if (existing == 0 && (tileh == SLOPE_W || tileh == SLOPE_S || tileh == SLOPE_E || tileh == SLOPE_N)) {
+	if ((existing == 0 || existing == *pieces) && (tileh == SLOPE_W || tileh == SLOPE_S || tileh == SLOPE_E || tileh == SLOPE_N)) {
 		/* force full pieces. */
-		*pieces |= (RoadBits)((*pieces & 0xC) >> 2);
-		*pieces |= (RoadBits)((*pieces & 0x3) << 2);
 		if (*pieces == ROAD_X || *pieces == ROAD_Y) return _price.terraform;
 	}
 	return CMD_ERROR;
@@ -362,7 +365,7 @@
 	tileh = GetTileSlope(tile, NULL);
 
 	switch (GetTileType(tile)) {
-		case MP_STREET:
+		case MP_ROAD:
 			switch (GetRoadTileType(tile)) {
 				case ROAD_TILE_NORMAL: {
 					if (HasRoadWorks(tile)) return_cmd_error(STR_ROAD_WORKS_IN_PROGRESS);
@@ -479,7 +482,7 @@
 		cost.AddCost(ret);
 	}
 
-	if (IsTileType(tile, MP_STREET)) {
+	if (IsTileType(tile, MP_ROAD)) {
 		/* Don't put the pieces that already exist */
 		pieces &= ComplementRoadBits(existing);
 	}
@@ -492,7 +495,7 @@
 
 	if (flags & DC_EXEC) {
 		switch (GetTileType(tile)) {
-			case MP_STREET: {
+			case MP_ROAD: {
 				RoadTileType rtt = GetRoadTileType(tile);
 				if (existing == ROAD_NONE || rtt == ROAD_TILE_CROSSING) {
 					SetRoadTypes(tile, GetRoadTypes(tile) | RoadTypeToRoadTypes(rt));
@@ -527,7 +530,7 @@
 				break;
 		}
 
-		if (rt != ROADTYPE_TRAM && IsTileType(tile, MP_STREET) && GetRoadTileType(tile) == ROAD_TILE_NORMAL) {
+		if (rt != ROADTYPE_TRAM && IsTileType(tile, MP_ROAD) && GetRoadTileType(tile) == ROAD_TILE_NORMAL) {
 			existing |= pieces;
 			SetDisallowedRoadDirections(tile, (existing == ROAD_X || existing == ROAD_Y) ?
 					GetDisallowedRoadDirections(tile) ^ toggle_drd : DRD_NONE);
@@ -719,7 +722,6 @@
 CommandCost CmdBuildRoadDepot(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 {
 	CommandCost cost;
-	Depot *dep;
 	Slope tileh;
 
 	SET_EXPENSES_TYPE(EXPENSES_CONSTRUCTION);
@@ -743,15 +745,16 @@
 
 	if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
 
-	dep = AllocateDepot();
+	Depot *dep = new Depot(tile);
 	if (dep == NULL) return CMD_ERROR;
+	AutoPtrT<Depot> d_auto_delete = dep;
 
 	if (flags & DC_EXEC) {
-		dep->xy = tile;
 		dep->town_index = ClosestTownFromTile(tile, (uint)-1)->index;
 
 		MakeRoadDepot(tile, _current_player, dir, rt);
 		MarkTileDirtyByTile(tile);
+		d_auto_delete.Detach();
 	}
 	return cost.AddCost(_price.build_road_depot);
 }
@@ -763,7 +766,10 @@
 
 	if (!EnsureNoVehicle(tile)) return CMD_ERROR;
 
-	if (flags & DC_EXEC) DeleteDepot(GetDepotByTile(tile));
+	if (flags & DC_EXEC) {
+		DoClearSquare(tile);
+		delete GetDepotByTile(tile);
+	}
 
 	return CommandCost(_price.remove_road_depot);
 }
@@ -837,34 +843,21 @@
 #include "table/road_land.h"
 
 
-uint GetRoadFoundation(Slope tileh, RoadBits bits)
+Foundation GetRoadFoundation(Slope tileh, RoadBits bits)
 {
-	uint i;
-
-	/* normal level sloped building */
-	if (!IsSteepSlope(tileh) &&
-			(~_valid_tileh_slopes_road[1][tileh] & bits) == 0) {
-		return tileh;
+	if (!IsSteepSlope(tileh)) {
+		if ((~_valid_tileh_slopes_road[0][tileh] & bits) == 0) {
+			/* As one can remove a single road piece when in a corner on a foundation as
+			 * it is on a sloped piece of landscape, one creates a state that cannot be
+			 * created directly, but the state itself is still perfectly drawable.
+			 * However, as we do not want this to be build directly, we need to check
+			 * for that situation in here. */
+			return (tileh != 0 && HAS_SINGLE_BIT(bits)) ? FOUNDATION_LEVELED : FOUNDATION_NONE;
+		}
+		if ((~_valid_tileh_slopes_road[1][tileh] & bits) == 0) return FOUNDATION_LEVELED;
 	}
 
-	/* inclined sloped building */
-	switch (bits) {
-		case ROAD_X: i = 0; break;
-		case ROAD_Y: i = 1; break;
-		default:     return 0;
-	}
-	switch (tileh) {
-		case SLOPE_W:
-		case SLOPE_STEEP_W: i += 0; break;
-		case SLOPE_S:
-		case SLOPE_STEEP_S: i += 2; break;
-		case SLOPE_E:
-		case SLOPE_STEEP_E: i += 4; break;
-		case SLOPE_N:
-		case SLOPE_STEEP_N: i += 6; break;
-		default: return 0;
-	}
-	return i + 15;
+	return (bits == ROAD_X ? FOUNDATION_INCLINED_X : FOUNDATION_INCLINED_Y);
 }
 
 const byte _road_sloped_sprites[14] = {
@@ -916,15 +909,8 @@
 		front = SPR_TRAMWAY_BASE + _road_frontwire_sprites_1[tram];
 	}
 
-	SpriteID pal = PAL_NONE;
-	if (HASBIT(_transparent_opt, TO_BUILDINGS)) {
-		SETBIT(front, PALETTE_MODIFIER_TRANSPARENT);
-		SETBIT(back,  PALETTE_MODIFIER_TRANSPARENT);
-		pal = PALETTE_TO_TRANSPARENT;
-	}
-
-	AddSortableSpriteToDraw(back,  pal, ti->x, ti->y, 16, 16, 0x1F, ti->z);
-	AddSortableSpriteToDraw(front, pal, ti->x, ti->y, 16, 16, 0x1F, ti->z);
+	AddSortableSpriteToDraw(back,  PAL_NONE, ti->x, ti->y, 16, 16, 0x1F, ti->z, HASBIT(_transparent_opt, TO_BUILDINGS));
+	AddSortableSpriteToDraw(front, PAL_NONE, ti->x, ti->y, 16, 16, 0x1F, ti->z, HASBIT(_transparent_opt, TO_BUILDINGS));
 }
 
 /**
@@ -959,9 +945,7 @@
 	Roadside roadside;
 
 	if (ti->tileh != SLOPE_FLAT) {
-		int foundation = GetRoadFoundation(ti->tileh, road | tram);
-
-		if (foundation != 0) DrawFoundation(ti, foundation);
+		DrawFoundation(ti, GetRoadFoundation(ti->tileh, road | tram));
 
 		/* DrawFoundation() modifies ti.
 		 * Default sloped sprites.. */
@@ -1034,7 +1018,7 @@
 			SpriteID pal = PAL_NONE;
 			Roadside roadside = GetRoadside(ti->tile);
 
-			if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, ti->tileh);
+			if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
 
 			image = GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.crossing;
 
@@ -1066,7 +1050,7 @@
 			const DrawTileSeqStruct* dtss;
 			SpriteID palette;
 
-			if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, ti->tileh);
+			if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
 
 			palette = PLAYER_SPRITE_COLOR(GetTileOwner(ti->tile));
 
@@ -1082,10 +1066,7 @@
 				SpriteID image = dtss->image;
 				SpriteID pal;
 
-				if (HASBIT(_transparent_opt, TO_BUILDINGS)) {
-					SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
-					pal = PALETTE_TO_TRANSPARENT;
-				} else if (HASBIT(image, PALETTE_MODIFIER_COLOR)) {
+				if (!HASBIT(_transparent_opt, TO_BUILDINGS) && HASBIT(image, PALETTE_MODIFIER_COLOR)) {
 					pal = palette;
 				} else {
 					pal = PAL_NONE;
@@ -1095,7 +1076,8 @@
 					image, pal,
 					ti->x + dtss->delta_x, ti->y + dtss->delta_y,
 					dtss->size_x, dtss->size_y,
-					dtss->size_z, ti->z
+					dtss->size_z, ti->z,
+					HASBIT(_transparent_opt, TO_BUILDINGS)
 				);
 			}
 			break;
@@ -1130,33 +1112,20 @@
 
 	if (tileh == SLOPE_FLAT) return z;
 	if (GetRoadTileType(tile) == ROAD_TILE_NORMAL) {
-		uint f = GetRoadFoundation(tileh, GetAllRoadBits(tile));
-
-		if (f != 0) {
-			if (IsSteepSlope(tileh)) {
-				z += TILE_HEIGHT;
-			} else if (f < 15) {
-				return z + TILE_HEIGHT; // leveled foundation
-			}
-			tileh = _inclined_tileh[f - 15]; // inclined foundation
-		}
+		Foundation f = GetRoadFoundation(tileh, GetAllRoadBits(tile));
+		z += ApplyFoundationToSlope(f, &tileh);
 		return z + GetPartialZ(x & 0xF, y & 0xF, tileh);
 	} else {
 		return z + TILE_HEIGHT;
 	}
 }
 
-static Slope GetSlopeTileh_Road(TileIndex tile, Slope tileh)
+static Foundation GetFoundation_Road(TileIndex tile, Slope tileh)
 {
-	if (tileh == SLOPE_FLAT) return SLOPE_FLAT;
 	if (GetRoadTileType(tile) == ROAD_TILE_NORMAL) {
-		uint f = GetRoadFoundation(tileh, GetAllRoadBits(tile));
-
-		if (f == 0) return tileh;
-		if (f < 15) return SLOPE_FLAT; // leveled foundation
-		return _inclined_tileh[f - 15]; // inclined foundation
+		return GetRoadFoundation(tileh, GetAllRoadBits(tile));
 	} else {
-		return SLOPE_FLAT;
+		return FlatteningFoundation(tileh);
 	}
 }
 
@@ -1414,5 +1383,5 @@
 	ChangeTileOwner_Road,    /* change_tile_owner_clear */
 	NULL,                    /* get_produced_cargo_proc */
 	VehicleEnter_Road,       /* vehicle_enter_tile_proc */
-	GetSlopeTileh_Road,      /* get_slope_tileh_proc */
+	GetFoundation_Road,      /* get_foundation_proc */
 };
--- a/src/road_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/road_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -122,7 +122,7 @@
 {
 	tile += TileOffsByDiagDir(direction);
 	// if there is a roadpiece just outside of the station entrance, build a connecting route
-	if (IsTileType(tile, MP_STREET) && GetRoadTileType(tile) == ROAD_TILE_NORMAL) {
+	if (IsTileType(tile, MP_ROAD) && GetRoadTileType(tile) == ROAD_TILE_NORMAL) {
 		if (GetRoadBits(tile, _cur_roadtype) != ROAD_NONE) {
 			DoCommandP(tile, _cur_roadtype << 4 | DiagDirToRoadBits(ReverseDiagDir(direction)), 0, NULL, CMD_BUILD_ROAD);
 		}
@@ -169,7 +169,7 @@
 static void PlaceRoad_TruckStation(TileIndex tile)
 {
 	if (_remove_button_clicked) {
-		DoCommandP(tile, 0, RoadStop::TRUCK, CcPlaySound1D, CMD_REMOVE_ROAD_STOP | CMD_MSG(_road_type_infos[_cur_roadtype].err_build_station[RoadStop::TRUCK]));
+		DoCommandP(tile, 0, RoadStop::TRUCK, CcPlaySound1D, CMD_REMOVE_ROAD_STOP | CMD_MSG(_road_type_infos[_cur_roadtype].err_remove_station[RoadStop::TRUCK]));
 	} else {
 		PlaceRoadStop(tile, (_ctrl_pressed << 5) | RoadTypeToRoadTypes(_cur_roadtype) << 2 | RoadStop::TRUCK, CMD_BUILD_ROAD_STOP | CMD_AUTO | CMD_NO_WATER | CMD_MSG(_road_type_infos[_cur_roadtype].err_build_station[RoadStop::TRUCK]));
 	}
@@ -386,7 +386,7 @@
 };
 
 static const WindowDesc _build_road_desc = {
-	WDP_ALIGN_TBR, 22, 218, 36,
+	WDP_ALIGN_TBR, 22, 218, 36, 218, 36,
 	WC_BUILD_TOOLBAR, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
 	_build_road_widgets,
@@ -412,7 +412,7 @@
 };
 
 static const WindowDesc _build_tramway_desc = {
-	WDP_ALIGN_TBR, 22, 218, 36,
+	WDP_ALIGN_TBR, 22, 218, 36, 218, 36,
 	WC_BUILD_TOOLBAR, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
 	_build_tramway_widgets,
@@ -447,7 +447,7 @@
 };
 
 static const WindowDesc _build_road_scen_desc = {
-	WDP_AUTO, WDP_AUTO, 152, 36,
+	WDP_AUTO, WDP_AUTO, 152, 36, 152, 36,
 	WC_SCEN_BUILD_ROAD, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
 	_build_road_scen_widgets,
@@ -519,7 +519,7 @@
 };
 
 static const WindowDesc _build_road_depot_desc = {
-	WDP_AUTO, WDP_AUTO, 140, 122,
+	WDP_AUTO, WDP_AUTO, 140, 122, 140, 122,
 	WC_BUILD_DEPOT, WC_BUILD_TOOLBAR,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_build_road_depot_widgets,
@@ -527,7 +527,7 @@
 };
 
 static const WindowDesc _build_tram_depot_desc = {
-	WDP_AUTO, WDP_AUTO, 140, 122,
+	WDP_AUTO, WDP_AUTO, 140, 122, 140, 122,
 	WC_BUILD_DEPOT, WC_BUILD_TOOLBAR,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_build_tram_depot_widgets,
@@ -634,7 +634,7 @@
 };
 
 static const WindowDesc _rv_station_picker_desc = {
-	WDP_AUTO, WDP_AUTO, 207, 177,
+	WDP_AUTO, WDP_AUTO, 207, 177, 207, 177,
 	WC_BUS_STATION, WC_BUILD_TOOLBAR,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_rv_station_picker_widgets,
--- a/src/road_map.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/road_map.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -19,7 +19,7 @@
 	if (!HASBIT(GetRoadTypes(tile), rt)) return ROAD_NONE;
 
 	switch (GetTileType(tile)) {
-		case MP_STREET:
+		case MP_ROAD:
 			switch (GetRoadTileType(tile)) {
 				default:
 				case ROAD_TILE_NORMAL:   return GetRoadBits(tile, rt);
@@ -51,7 +51,7 @@
 	uint32 r;
 
 	/* Don't allow local authorities to build roads through road depots or road stops. */
-	if ((IsTileType(tile, MP_STREET) && IsTileDepotType(tile, TRANSPORT_ROAD)) || (IsTileType(tile, MP_STATION) && !IsDriveThroughStopTile(tile)) || !HASBIT(GetRoadTypes(tile), rt)) {
+	if ((IsTileType(tile, MP_ROAD) && IsTileDepotType(tile, TRANSPORT_ROAD)) || (IsTileType(tile, MP_STATION) && !IsDriveThroughStopTile(tile)) || !HASBIT(GetRoadTypes(tile), rt)) {
 		return TRACK_BIT_NONE;
 	}
 
--- a/src/road_map.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/road_map.h	Fri Aug 03 18:10:15 2007 +0000
@@ -19,7 +19,7 @@
 
 static inline RoadTileType GetRoadTileType(TileIndex t)
 	{
-	assert(IsTileType(t, MP_STREET));
+	assert(IsTileType(t, MP_ROAD));
 	return (RoadTileType)GB(_m[t].m5, 6, 2);
 }
 
@@ -30,7 +30,7 @@
 
 static inline bool IsLevelCrossingTile(TileIndex t)
 {
-	return IsTileType(t, MP_STREET) && IsLevelCrossing(t);
+	return IsTileType(t, MP_ROAD) && IsLevelCrossing(t);
 }
 
 static inline RoadBits GetRoadBits(TileIndex t, RoadType rt)
@@ -62,7 +62,7 @@
 
 static inline RoadTypes GetRoadTypes(TileIndex t)
 {
-	if (IsTileType(t, MP_STREET)) {
+	if (IsTileType(t, MP_ROAD)) {
 		return (RoadTypes)GB(_me[t].m7, 5, 3);
 	} else {
 		return (RoadTypes)GB(_m[t].m3, 0, 3);
@@ -71,7 +71,7 @@
 
 static inline void SetRoadTypes(TileIndex t, RoadTypes rt)
 {
-	if (IsTileType(t, MP_STREET)) {
+	if (IsTileType(t, MP_ROAD)) {
 		SB(_me[t].m7, 5, 3, rt);
 	} else {
 		assert(IsTileType(t, MP_STATION) || IsTileType(t, MP_TUNNELBRIDGE));
@@ -81,7 +81,7 @@
 
 static inline Owner GetRoadOwner(TileIndex t, RoadType rt)
 {
-	if (!IsTileType(t, MP_STREET)) return GetTileOwner(t);
+	if (!IsTileType(t, MP_ROAD)) return GetTileOwner(t);
 
 	switch (GetRoadTileType(t)) {
 		default: NOT_REACHED();
@@ -115,7 +115,7 @@
 
 static inline void SetRoadOwner(TileIndex t, RoadType rt, Owner o)
 {
-	if (!IsTileType(t, MP_STREET)) return SetTileOwner(t, o);
+	if (!IsTileType(t, MP_ROAD)) return SetTileOwner(t, o);
 
 	switch (GetRoadTileType(t)) {
 		default: NOT_REACHED();
@@ -307,7 +307,7 @@
 
 static inline void MakeRoadNormal(TileIndex t, RoadBits bits, RoadTypes rot, TownID town, Owner road, Owner tram, Owner hway)
 {
-	SetTileType(t, MP_STREET);
+	SetTileType(t, MP_ROAD);
 	SetTileOwner(t, road);
 	_m[t].m2 = town;
 	_m[t].m3 = 0;
@@ -321,7 +321,7 @@
 
 static inline void MakeRoadCrossing(TileIndex t, Owner road, Owner tram, Owner hway, Owner rail, Axis roaddir, RailType rat, RoadTypes rot, uint town)
 {
-	SetTileType(t, MP_STREET);
+	SetTileType(t, MP_ROAD);
 	SetTileOwner(t, rail);
 	_m[t].m2 = town;
 	_m[t].m3 = rat;
@@ -335,7 +335,7 @@
 
 static inline void MakeRoadDepot(TileIndex t, Owner owner, DiagDirection dir, RoadType rt)
 {
-	SetTileType(t, MP_STREET);
+	SetTileType(t, MP_ROAD);
 	SetTileOwner(t, owner);
 	_m[t].m2 = 0;
 	_m[t].m3 = 0;
--- a/src/roadveh.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/roadveh.h	Fri Aug 03 18:10:15 2007 +0000
@@ -44,13 +44,13 @@
 }
 
 
-static inline bool IsRoadVehInDepot(const Vehicle* v)
+static inline bool IsRoadVehInDepot(const Vehicle *v)
 {
 	assert(v->type == VEH_ROAD);
 	return v->u.road.state == 254;
 }
 
-static inline bool IsRoadVehInDepotStopped(const Vehicle* v)
+static inline bool IsRoadVehInDepotStopped(const Vehicle *v)
 {
 	return IsRoadVehInDepot(v) && v->vehstatus & VS_STOPPED;
 }
--- a/src/roadveh_cmd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/roadveh_cmd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -395,7 +395,7 @@
 
 	tile += TileOffsByDiagDir(_road_pf_directions[trackdir]);
 
-	if (IsTileType(tile, MP_STREET) &&
+	if (IsTileType(tile, MP_ROAD) &&
 			GetRoadTileType(tile) == ROAD_TILE_DEPOT &&
 			IsTileOwner(tile, rfdd->owner) &&
 			length < rfdd->best_length) {
@@ -543,7 +543,7 @@
 		return CMD_ERROR;
 	}
 
-	if (IsTileType(v->tile, MP_STREET) && GetRoadTileType(v->tile) == ROAD_TILE_NORMAL && GetDisallowedRoadDirections(v->tile) != DRD_NONE) return CMD_ERROR;
+	if (IsTileType(v->tile, MP_ROAD) && GetRoadTileType(v->tile) == ROAD_TILE_NORMAL && GetDisallowedRoadDirections(v->tile) != DRD_NONE) return CMD_ERROR;
 
 	if (IsTunnelTile(v->tile) && DirToDiagDir(v->direction) == GetTunnelDirection(v->tile)) return CMD_ERROR;
 	if (IsBridgeTile(v->tile) && DirToDiagDir(v->direction) == GetBridgeRampDirection(v->tile)) return CMD_ERROR;
@@ -737,7 +737,7 @@
 
 		if (!(v->vehstatus & VS_HIDDEN)) {
 			Vehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE);
-			if (u != NULL) u->u.special.unk0 = v->breakdown_delay * 2;
+			if (u != NULL) u->u.special.animation_state = v->breakdown_delay * 2;
 		}
 	}
 
@@ -1145,7 +1145,7 @@
 	TrackdirBits signal    = (TrackdirBits)GB(r, 16, 16);
 	TrackdirBits trackdirs = (TrackdirBits)GB(r,  0, 16);
 
-	if (IsTileType(tile, MP_STREET)) {
+	if (IsTileType(tile, MP_ROAD)) {
 		if (GetRoadTileType(tile) == ROAD_TILE_DEPOT && (!IsTileOwner(tile, v->owner) || GetRoadDepotDirection(tile) == enterdir || (GetRoadTypes(tile) & v->u.road.compatible_roadtypes) == 0)) {
 			/* Road depot owned by another player or with the wrong orientation */
 			trackdirs = TRACKDIR_BIT_NONE;
@@ -1232,7 +1232,7 @@
 	} else {
 		DiagDirection dir;
 
-		if (IsTileType(desttile, MP_STREET)) {
+		if (IsTileType(desttile, MP_ROAD)) {
 			if (GetRoadTileType(desttile) == ROAD_TILE_DEPOT) {
 				dir = GetRoadDepotDirection(desttile);
 				goto do_it;
@@ -1394,7 +1394,7 @@
 			diag_dir = GetTunnelDirection(tile);
 		} else if (IsBridgeTile(tile)) {
 			diag_dir = GetBridgeRampDirection(tile);
-		} else if (IsTileType(tile, MP_STREET) && GetRoadTileType(tile) == ROAD_TILE_DEPOT) {
+		} else if (IsTileType(tile, MP_ROAD) && GetRoadTileType(tile) == ROAD_TILE_DEPOT) {
 			diag_dir = ReverseDiagDir(GetRoadDepotDirection(tile));
 		}
 
@@ -1481,7 +1481,7 @@
 		(_opt.road_side << RVS_DRIVE_SIDE)) ^ v->u.road.overtaking][v->u.road.frame + 1];
 
 	if (rd.x & RDE_NEXT_TILE) {
-		TileIndex tile = v->tile + TileOffsByDiagDir(rd.x & 3);
+		TileIndex tile = v->tile + TileOffsByDiagDir((DiagDirection)(rd.x & 3));
 		Trackdir dir;
 		uint32 r;
 		Direction newdir;
@@ -1512,12 +1512,12 @@
 					case TRACKDIR_RVREV_SW: needed = ROAD_NE; break;
 					case TRACKDIR_RVREV_NW: needed = ROAD_SE; break;
 				}
-				if (!IsTileType(tile, MP_STREET) || GetRoadTileType(tile) != ROAD_TILE_NORMAL || HasRoadWorks(tile) || (needed & GetRoadBits(tile, ROADTYPE_TRAM)) == ROAD_NONE) {
+				if (!IsTileType(tile, MP_ROAD) || GetRoadTileType(tile) != ROAD_TILE_NORMAL || HasRoadWorks(tile) || (needed & GetRoadBits(tile, ROADTYPE_TRAM)) == ROAD_NONE) {
 					/* The tram cannot turn here */
 					v->cur_speed = 0;
 					return false;
 				}
-			} else if (IsTileType(v->tile, MP_STREET) && GetRoadTileType(v->tile) == ROAD_TILE_NORMAL && GetDisallowedRoadDirections(v->tile) != DRD_NONE) {
+			} else if (IsTileType(v->tile, MP_ROAD) && GetRoadTileType(v->tile) == ROAD_TILE_NORMAL && GetDisallowedRoadDirections(v->tile) != DRD_NONE) {
 				v->cur_speed = 0;
 				return false;
 			} else {
@@ -1625,7 +1625,7 @@
 	 * it's on a depot tile, check if it's time to activate the next vehicle in
 	 * the chain yet. */
 	if (v->next != NULL &&
-			IsTileType(v->tile, MP_STREET) && GetRoadTileType(v->tile) == ROAD_TILE_DEPOT) {
+			IsTileType(v->tile, MP_ROAD) && GetRoadTileType(v->tile) == ROAD_TILE_DEPOT) {
 
 		if (v->u.road.frame == v->u.road.cached_veh_length + RVC_DEPOT_START_FRAME) {
 			RoadVehLeaveDepot(v->next, false);
--- a/src/roadveh_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/roadveh_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -242,7 +242,7 @@
 };
 
 static const WindowDesc _roadveh_details_desc = {
-	WDP_AUTO, WDP_AUTO, 380, 113,
+	WDP_AUTO, WDP_AUTO, 380, 113, 380, 113,
 	WC_VEHICLE_DETAILS,WC_VEHICLE_VIEW,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_roadveh_details_widgets,
@@ -416,7 +416,7 @@
 };
 
 static const WindowDesc _roadveh_view_desc = {
-	WDP_AUTO, WDP_AUTO, 250, 116,
+	WDP_AUTO, WDP_AUTO, 250, 116, 250, 116,
 	WC_VEHICLE_VIEW, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_roadveh_view_widgets,
--- a/src/saveload.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/saveload.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -270,7 +270,8 @@
 }
 
 /** Return how many bytes used to encode a gamma value */
-static inline uint SlGetGammaLength(uint i) {
+static inline uint SlGetGammaLength(uint i)
+{
 	return 1 + (i >= (1 << 7)) + (i >= (1 << 14)) + (i >= (1 << 21));
 }
 
@@ -1551,7 +1552,7 @@
 		uint count = 1 << Savegame_POOL_BLOCK_SIZE_BITS;
 
 		assert(_ts.count == _sl.offs_base);
-		for (i = 0; i != _Savegame_pool.current_blocks - 1; i++) {
+		for (i = 0; i != _Savegame_pool.GetBlockCount() - 1; i++) {
 			_sl.buf = _Savegame_pool.blocks[i];
 			fmt->writer(count);
 		}
--- a/src/settings_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/settings_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -337,7 +337,7 @@
 };
 
 static const WindowDesc _game_options_desc = {
-	WDP_CENTER, WDP_CENTER, 370, 239,
+	WDP_CENTER, WDP_CENTER, 370, 239, 370, 239,
 	WC_GAME_OPTIONS, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_game_options_widgets,
@@ -613,7 +613,7 @@
 };
 
 static const WindowDesc _game_difficulty_desc = {
-	WDP_CENTER, WDP_CENTER, 370, 279,
+	WDP_CENTER, WDP_CENTER, 370, 279, 370, 279,
 	WC_GAME_OPTIONS, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_game_difficulty_widgets,
@@ -994,7 +994,7 @@
 };
 
 static const WindowDesc _patches_selection_desc = {
-	WDP_CENTER, WDP_CENTER, 370, 381,
+	WDP_CENTER, WDP_CENTER, 370, 381, 370, 381,
 	WC_GAME_OPTIONS, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_patches_selection_widgets,
@@ -1214,7 +1214,7 @@
 };
 
 static const WindowDesc _cust_currency_desc = {
-	WDP_CENTER, WDP_CENTER, 230, 120,
+	WDP_CENTER, WDP_CENTER, 230, 120, 230, 120,
 	WC_CUSTOM_CURRENCY, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_cust_currency_widgets,
--- a/src/ship.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/ship.h	Fri Aug 03 18:10:15 2007 +0000
@@ -12,13 +12,13 @@
 void RecalcShipStuff(Vehicle *v);
 void GetShipSpriteSize(EngineID engine, uint &width, uint &height);
 
-static inline bool IsShipInDepot(const Vehicle* v)
+static inline bool IsShipInDepot(const Vehicle *v)
 {
 	assert(v->type == VEH_SHIP);
 	return v->u.ship.state == 0x80;
 }
 
-static inline bool IsShipInDepotStopped(const Vehicle* v)
+static inline bool IsShipInDepotStopped(const Vehicle *v)
 {
 	return IsShipInDepot(v) && v->vehstatus & VS_STOPPED;
 }
--- a/src/ship_cmd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/ship_cmd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -220,7 +220,7 @@
 
 		if (!(v->vehstatus & VS_HIDDEN)) {
 			Vehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE);
-			if (u != NULL) u->u.special.unk0 = v->breakdown_delay * 2;
+			if (u != NULL) u->u.special.animation_state = v->breakdown_delay * 2;
 		}
 	}
 
--- a/src/ship_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/ship_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -156,7 +156,7 @@
 };
 
 static const WindowDesc _ship_details_desc = {
-	WDP_AUTO, WDP_AUTO, 405, 113,
+	WDP_AUTO, WDP_AUTO, 405, 113, 405, 113,
 	WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_ship_details_widgets,
@@ -334,7 +334,7 @@
 };
 
 static const WindowDesc _ship_view_desc = {
-	WDP_AUTO, WDP_AUTO, 250, 116,
+	WDP_AUTO, WDP_AUTO, 250, 116, 250, 116,
 	WC_VEHICLE_VIEW, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_ship_view_widgets,
--- a/src/signs.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/signs.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -13,24 +13,29 @@
 #include "saveload.h"
 #include "command.h"
 #include "variables.h"
+#include "misc/autoptr.hpp"
 
 SignID _new_sign_id;
 uint _total_signs;
 
-/**
- * Called if a new block is added to the sign-pool
- */
-static void SignPoolNewBlock(uint start_item)
+/* Initialize the sign-pool */
+DEFINE_OLD_POOL_GENERIC(Sign, Sign)
+
+Sign::Sign(StringID string)
 {
-	Sign *si;
-
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (si = GetSign(start_item); si != NULL; si = (si->index + 1U < GetSignPoolSize()) ? GetSign(si->index + 1U) : NULL) si->index = start_item++;
+	this->str = string;
 }
 
-/* Initialize the sign-pool */
-DEFINE_OLD_POOL(Sign, Sign, SignPoolNewBlock, NULL)
+Sign::~Sign()
+{
+	this->QuickFree();
+	this->str = STR_NULL;
+}
+
+void Sign::QuickFree()
+{
+	DeleteName(this->str);
+}
 
 /**
  *
@@ -77,45 +82,6 @@
 }
 
 /**
- *
- * Allocates a new sign
- *
- * @return The pointer to the new sign, or NULL if there is no more free space
- */
-static Sign *AllocateSign()
-{
-	Sign *si;
-
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (si = GetSign(0); si != NULL; si = (si->index + 1U < GetSignPoolSize()) ? GetSign(si->index + 1U) : NULL) {
-		if (!IsValidSign(si)) {
-			uint index = si->index;
-
-			memset(si, 0, sizeof(Sign));
-			si->index = index;
-
-			return si;
-		}
-	}
-
-	/* Check if we can add a block to the pool */
-	if (AddBlockToPool(&_Sign_pool))
-		return AllocateSign();
-
-	return NULL;
-}
-
-/**
- * Destroy a sign placed on the map
- * @param si Pointer to the Sign to remove
- */
-void DestroySign(Sign *si)
-{
-	DeleteName(si->str);
-}
-
-/**
  * Place a sign at the given coordinates. Ownership of sign has
  * no effect whatsoever except for the colour the sign gets for easy recognition,
  * but everybody is able to rename/remove it.
@@ -126,18 +92,16 @@
  */
 CommandCost CmdPlaceSign(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 {
-	Sign *si;
-
 	/* Try to locate a new sign */
-	si = AllocateSign();
+	Sign *si = new Sign(STR_280A_SIGN);
 	if (si == NULL) return_cmd_error(STR_2808_TOO_MANY_SIGNS);
+	AutoPtrT<Sign> s_auto_delete = si;
 
 	/* When we execute, really make the sign */
 	if (flags & DC_EXEC) {
 		int x = TileX(tile) * TILE_SIZE;
 		int y = TileY(tile) * TILE_SIZE;
 
-		si->str = STR_280A_SIGN;
 		si->x = x;
 		si->y = y;
 		si->owner = _current_player; // owner of the sign; just eyecandy
@@ -148,6 +112,7 @@
 		_sign_sort_dirty = true;
 		_new_sign_id = si->index;
 		_total_signs++;
+		s_auto_delete.Detach();
 	}
 
 	return CommandCost();
@@ -197,7 +162,7 @@
 			Sign *si = GetSign(p1);
 
 			MarkSignDirty(si);
-			DeleteSign(si);
+			delete si;
 
 			InvalidateWindow(WC_SIGN_LIST, 0);
 			_sign_sort_dirty = true;
@@ -242,8 +207,8 @@
 void InitializeSigns()
 {
 	_total_signs = 0;
-	CleanPool(&_Sign_pool);
-	AddBlockToPool(&_Sign_pool);
+	_Sign_pool.CleanPool();
+	_Sign_pool.AddBlockToPool();
 }
 
 static const SaveLoad _sign_desc[] = {
@@ -282,12 +247,7 @@
 	_total_signs = 0;
 	int index;
 	while ((index = SlIterateArray()) != -1) {
-		Sign *si;
-
-		if (!AddBlockIfNeeded(&_Sign_pool, index))
-			error("Signs: failed loading savegame: too many signs");
-
-		si = GetSign(index);
+		Sign *si = new (index) Sign();
 		SlObject(si, _sign_desc);
 
 		_total_signs++;
--- a/src/signs.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/signs.h	Fri Aug 03 18:10:15 2007 +0000
@@ -7,7 +7,10 @@
 
 #include "oldpool.h"
 
-struct Sign {
+struct Sign;
+DECLARE_OLD_POOL(Sign, Sign, 2, 16000)
+
+struct Sign : PoolItem<Sign, SignID, &_Sign_pool> {
 	StringID     str;
 	ViewportSign sign;
 	int32        x;
@@ -15,7 +18,17 @@
 	byte         z;
 	PlayerByte   owner; // placed by this player. Anyone can delete them though. OWNER_NONE for gray signs from old games.
 
-	SignID       index;
+	/**
+	 * Creates a new sign
+	 */
+	Sign(StringID string = STR_NULL);
+
+	/** Destroy the sign */
+	~Sign();
+
+	bool IsValid() const { return this->str != STR_NULL; }
+
+	void QuickFree();
 };
 
 enum {
@@ -24,7 +37,6 @@
 
 extern SignID _new_sign_id;
 
-DECLARE_OLD_POOL(Sign, Sign, 2, 16000)
 
 static inline SignID GetMaxSignIndex()
 {
@@ -42,28 +54,12 @@
 	return _total_signs;
 }
 
-/**
- * Check if a Sign really exists.
- */
-static inline bool IsValidSign(const Sign *si)
-{
-	return si->str != STR_NULL;
-}
-
 static inline bool IsValidSignID(uint index)
 {
-	return index < GetSignPoolSize() && IsValidSign(GetSign(index));
+	return index < GetSignPoolSize() && GetSign(index)->IsValid();
 }
 
-void DestroySign(Sign *si);
-
-static inline void DeleteSign(Sign *si)
-{
-	DestroySign(si);
-	si->str = STR_NULL;
-}
-
-#define FOR_ALL_SIGNS_FROM(ss, start) for (ss = GetSign(start); ss != NULL; ss = (ss->index + 1U < GetSignPoolSize()) ? GetSign(ss->index + 1U) : NULL) if (IsValidSign(ss))
+#define FOR_ALL_SIGNS_FROM(ss, start) for (ss = GetSign(start); ss != NULL; ss = (ss->index + 1U < GetSignPoolSize()) ? GetSign(ss->index + 1U) : NULL) if (ss->IsValid())
 #define FOR_ALL_SIGNS(ss) FOR_ALL_SIGNS_FROM(ss, 0)
 
 VARDEF bool _sign_sort_dirty;
--- a/src/signs_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/signs_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -133,7 +133,7 @@
 };
 
 static const WindowDesc _sign_list_desc = {
-	WDP_AUTO, WDP_AUTO, 358, 138,
+	WDP_AUTO, WDP_AUTO, 358, 138, 358, 138,
 	WC_SIGN_LIST, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_sign_list_widget,
@@ -296,7 +296,7 @@
 };
 
 static const WindowDesc _query_sign_edit_desc = {
-	190, 170, 260, 42,
+	190, 170, 260, 42, 260, 42,
 	WC_QUERY_STRING, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
 	_query_sign_edit_widgets,
--- a/src/slope.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/slope.h	Fri Aug 03 18:10:15 2007 +0000
@@ -1,43 +1,164 @@
 /* $Id$ */
 
-/** @file slope.h */
+/** @file slope.h Definitions of a slope.
+ * This file defines the enumeration and helper functions for handling
+ * the slope info of a tile.
+ */
 
 #ifndef SLOPE_H
 #define SLOPE_H
 
+/**
+ * Enumeration for the slope-type.
+ *
+ * This enumeration use the chars N,E,S,W corresponding the
+ * direction north, east, south and west. The top corner of a tile
+ * is the north-part of the tile. The whole slope is encoded with
+ * 5 bits, 4 bits for each corner and 1 bit for a steep-flag.
+ */
 enum Slope {
-	SLOPE_FLAT     = 0x00,
-	SLOPE_W        = 0x01,
-	SLOPE_S        = 0x02,
-	SLOPE_E        = 0x04,
-	SLOPE_N        = 0x08,
-	SLOPE_STEEP    = 0x10,
-	SLOPE_NW       = SLOPE_N | SLOPE_W,
-	SLOPE_SW       = SLOPE_S | SLOPE_W,
-	SLOPE_SE       = SLOPE_S | SLOPE_E,
-	SLOPE_NE       = SLOPE_N | SLOPE_E,
-	SLOPE_EW       = SLOPE_E | SLOPE_W,
-	SLOPE_NS       = SLOPE_N | SLOPE_S,
-	SLOPE_ELEVATED = SLOPE_N | SLOPE_E | SLOPE_S | SLOPE_W,
-	SLOPE_NWS      = SLOPE_N | SLOPE_W | SLOPE_S,
-	SLOPE_WSE      = SLOPE_W | SLOPE_S | SLOPE_E,
-	SLOPE_SEN      = SLOPE_S | SLOPE_E | SLOPE_N,
-	SLOPE_ENW      = SLOPE_E | SLOPE_N | SLOPE_W,
-	SLOPE_STEEP_W  = SLOPE_STEEP | SLOPE_NWS,
-	SLOPE_STEEP_S  = SLOPE_STEEP | SLOPE_WSE,
-	SLOPE_STEEP_E  = SLOPE_STEEP | SLOPE_SEN,
-	SLOPE_STEEP_N  = SLOPE_STEEP | SLOPE_ENW
+	SLOPE_FLAT     = 0x00,                                  ///< a flat tile
+	SLOPE_W        = 0x01,                                  ///< the west corner of the tile is raised
+	SLOPE_S        = 0x02,                                  ///< the south corner of the tile is raised
+	SLOPE_E        = 0x04,                                  ///< the east corner of the tile is raised
+	SLOPE_N        = 0x08,                                  ///< the north corner of the tile is raised
+	SLOPE_STEEP    = 0x10,                                  ///< indicates the slope is steep
+	SLOPE_NW       = SLOPE_N | SLOPE_W,                     ///< north and west corner are raised
+	SLOPE_SW       = SLOPE_S | SLOPE_W,                     ///< south and west corner are raised
+	SLOPE_SE       = SLOPE_S | SLOPE_E,                     ///< south and east corner are raised
+	SLOPE_NE       = SLOPE_N | SLOPE_E,                     ///< north and east corner are raised
+	SLOPE_EW       = SLOPE_E | SLOPE_W,                     ///< east and west corner are raised
+	SLOPE_NS       = SLOPE_N | SLOPE_S,                     ///< north and south corner are raised
+	SLOPE_ELEVATED = SLOPE_N | SLOPE_E | SLOPE_S | SLOPE_W, ///< all corner are raised, similar to SLOPE_FLAT
+	SLOPE_NWS      = SLOPE_N | SLOPE_W | SLOPE_S,           ///< north, west and south corner are raised
+	SLOPE_WSE      = SLOPE_W | SLOPE_S | SLOPE_E,           ///< west, south and east corner are raised
+	SLOPE_SEN      = SLOPE_S | SLOPE_E | SLOPE_N,           ///< south, east and north corner are raised
+	SLOPE_ENW      = SLOPE_E | SLOPE_N | SLOPE_W,           ///< east, north and west corner are raised
+	SLOPE_STEEP_W  = SLOPE_STEEP | SLOPE_NWS,               ///< a steep slope falling to east (from west)
+	SLOPE_STEEP_S  = SLOPE_STEEP | SLOPE_WSE,               ///< a steep slope falling to north (from south)
+	SLOPE_STEEP_E  = SLOPE_STEEP | SLOPE_SEN,               ///< a steep slope falling to west (from east)
+	SLOPE_STEEP_N  = SLOPE_STEEP | SLOPE_ENW                ///< a steep slope falling to south (from north)
 };
 
+/**
+ * Checks if a slope is steep.
+ *
+ * @param s The given #Slope.
+ * @return True if the slope is steep, else false.
+ */
 static inline bool IsSteepSlope(Slope s)
 {
 	return (s & SLOPE_STEEP) != 0;
 }
 
+/**
+ * Return the complement of a slope.
+ *
+ * This method returns the complement of a slope. The complement of a
+ * slope is a slope with raised corner which aren't raised in the given
+ * slope.
+ *
+ * @pre The slope must not be steep.
+ * @param s The #Slope to get the complement.
+ * @return a complement Slope of the given slope.
+ */
 static inline Slope ComplementSlope(Slope s)
 {
 	assert(!IsSteepSlope(s));
 	return (Slope)(0xF ^ s);
 }
 
+/**
+ * Returns the highest corner of a slope (one corner raised or a steep slope).
+ *
+ * @pre      The slope must be a slope with one corner raised or a steep slope.
+ * @param s  The #Slope.
+ * @return   Number of the highest corner. (0 west, 1 south, 2 east, 3 north)
+ */
+static inline byte GetHighestSlopeCorner(Slope s)
+{
+	switch (s) {
+		case SLOPE_W:
+		case SLOPE_STEEP_W: return 0;
+		case SLOPE_S:
+		case SLOPE_STEEP_S: return 1;
+		case SLOPE_E:
+		case SLOPE_STEEP_E: return 2;
+		case SLOPE_N:
+		case SLOPE_STEEP_N: return 3;
+		default: NOT_REACHED();
+	}
+}
+
+
+/**
+ * Enumeration for Foundations.
+ */
+enum Foundation {
+	FOUNDATION_NONE,             ///< The tile has no foundation, the slope remains unchanged.
+	FOUNDATION_LEVELED,          ///< The tile is leveled up to a flat slope.
+	FOUNDATION_INCLINED_X,       ///< The tile has an along X-axis inclined foundation.
+	FOUNDATION_INCLINED_Y,       ///< The tile has an along Y-axis inclined foundation.
+	FOUNDATION_STEEP_LOWER,      ///< The tile has a steep slope. The lowerst corner is raised by a foundation to allow building railroad on the lower halftile.
+	FOUNDATION_STEEP_HIGHER,     ///< The tile has a steep slope. Three corners are raised by a foundation to allow building railroad on the higher halftile.
+};
+
+/**
+ * Tests for FOUNDATION_NONE.
+ *
+ * @param f  Maybe a #Foundation.
+ * @return   true iff f is a foundation.
+ */
+static inline bool IsFoundation(Foundation f)
+{
+	return f != FOUNDATION_NONE;
+}
+
+/**
+ * Tests if the foundation is a leveled foundation.
+ *
+ * @param f  The #Foundation.
+ * @return   true iff f is a leveled foundation.
+ */
+static inline bool IsLeveledFoundation(Foundation f)
+{
+	return f == FOUNDATION_LEVELED;
+}
+
+/**
+ * Tests if the foundation is an inclined foundation.
+ *
+ * @param f  The #Foundation.
+ * @return   true iff f is an inclined foundation.
+ */
+static inline bool IsInclinedFoundation(Foundation f)
+{
+	return (f == FOUNDATION_INCLINED_X) || (f == FOUNDATION_INCLINED_Y);
+}
+
+/**
+ * Returns the foundation needed to flatten a slope.
+ * The returned foundation is either FOUNDATION_NONE if the tile was already flat, or FOUNDATION_LEVELED.
+ *
+ * @pre      The slope must not be steep.
+ * @param s  The current #Slope.
+ * @return   The needed #Foundation.
+ */
+static inline Foundation FlatteningFoundation(Slope s)
+{
+	assert(!IsSteepSlope(s));
+	return (s == SLOPE_FLAT ? FOUNDATION_NONE : FOUNDATION_LEVELED);
+}
+
+/**
+ * Returns the along a specific axis inclined foundation.
+ *
+ * @param axis  The #Axis.
+ * @return      The needed #Foundation.
+ */
+static inline Foundation InclinedFoundation(Axis axis)
+{
+	return (axis == AXIS_X ? FOUNDATION_INCLINED_X : FOUNDATION_INCLINED_Y);
+}
+
 #endif /* SLOPE_H */
--- a/src/smallmap_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/smallmap_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -30,21 +30,21 @@
 
 static const Widget _smallmap_widgets[] = {
 {  WWT_CLOSEBOX,   RESIZE_NONE,    13,     0,    10,     0,    13, STR_00C5,                STR_018B_CLOSE_WINDOW},
-{   WWT_CAPTION,  RESIZE_RIGHT,    13,    11,   433,     0,    13, STR_00B0_MAP,            STR_018C_WINDOW_TITLE_DRAG_THIS},
-{ WWT_STICKYBOX,     RESIZE_LR,    13,   434,   445,     0,    13, 0x0,                     STR_STICKY_BUTTON},
-{     WWT_PANEL,     RESIZE_RB,    13,     0,   445,    14,   257, 0x0,                     STR_NULL},
-{     WWT_INSET,     RESIZE_RB,    13,     2,   443,    16,   255, 0x0,                     STR_NULL},
-{    WWT_IMGBTN,   RESIZE_LRTB,    13,   380,   401,   258,   279, SPR_IMG_SHOW_COUNTOURS,  STR_0191_SHOW_LAND_CONTOURS_ON_MAP},
-{    WWT_IMGBTN,   RESIZE_LRTB,    13,   402,   423,   258,   279, SPR_IMG_SHOW_VEHICLES,   STR_0192_SHOW_VEHICLES_ON_MAP},
-{    WWT_IMGBTN,   RESIZE_LRTB,    13,   424,   445,   258,   279, SPR_IMG_INDUSTRY,        STR_0193_SHOW_INDUSTRIES_ON_MAP},
-{    WWT_IMGBTN,   RESIZE_LRTB,    13,   380,   401,   280,   301, SPR_IMG_SHOW_ROUTES,     STR_0194_SHOW_TRANSPORT_ROUTES_ON},
-{    WWT_IMGBTN,   RESIZE_LRTB,    13,   402,   423,   280,   301, SPR_IMG_PLANTTREES,      STR_0195_SHOW_VEGETATION_ON_MAP},
-{    WWT_IMGBTN,   RESIZE_LRTB,    13,   424,   445,   280,   301, SPR_IMG_COMPANY_GENERAL, STR_0196_SHOW_LAND_OWNERS_ON_MAP},
-{    WWT_IMGBTN,   RESIZE_LRTB,    13,   358,   379,   258,   279, SPR_IMG_SMALLMAP,        STR_SMALLMAP_CENTER},
-{    WWT_IMGBTN,   RESIZE_LRTB,    13,   358,   379,   280,   301, SPR_IMG_TOWN,            STR_0197_TOGGLE_TOWN_NAMES_ON_OFF},
-{     WWT_PANEL,    RESIZE_RTB,    13,     0,   357,   258,   301, 0x0,                     STR_NULL},
-{     WWT_PANEL,    RESIZE_RTB,    13,     0,   433,   302,   313, 0x0,                     STR_NULL},
-{ WWT_RESIZEBOX,   RESIZE_LRTB,    13,   434,   445,   302,   313, 0x0,                     STR_RESIZE_BUTTON},
+{   WWT_CAPTION,  RESIZE_RIGHT,    13,    11,   337,     0,    13, STR_00B0_MAP,            STR_018C_WINDOW_TITLE_DRAG_THIS},
+{ WWT_STICKYBOX,     RESIZE_LR,    13,   338,   349,     0,    13, 0x0,                     STR_STICKY_BUTTON},
+{     WWT_PANEL,     RESIZE_RB,    13,     0,   349,    14,   157, 0x0,                     STR_NULL},
+{     WWT_INSET,     RESIZE_RB,    13,     2,   347,    16,   155, 0x0,                     STR_NULL},
+{    WWT_IMGBTN,   RESIZE_LRTB,    13,   284,   305,   158,   179, SPR_IMG_SHOW_COUNTOURS,  STR_0191_SHOW_LAND_CONTOURS_ON_MAP},
+{    WWT_IMGBTN,   RESIZE_LRTB,    13,   306,   327,   158,   179, SPR_IMG_SHOW_VEHICLES,   STR_0192_SHOW_VEHICLES_ON_MAP},
+{    WWT_IMGBTN,   RESIZE_LRTB,    13,   328,   349,   158,   179, SPR_IMG_INDUSTRY,        STR_0193_SHOW_INDUSTRIES_ON_MAP},
+{    WWT_IMGBTN,   RESIZE_LRTB,    13,   284,   307,   180,   201, SPR_IMG_SHOW_ROUTES,     STR_0194_SHOW_TRANSPORT_ROUTES_ON},
+{    WWT_IMGBTN,   RESIZE_LRTB,    13,   306,   327,   180,   201, SPR_IMG_PLANTTREES,      STR_0195_SHOW_VEGETATION_ON_MAP},
+{    WWT_IMGBTN,   RESIZE_LRTB,    13,   328,   349,   180,   201, SPR_IMG_COMPANY_GENERAL, STR_0196_SHOW_LAND_OWNERS_ON_MAP},
+{    WWT_IMGBTN,   RESIZE_LRTB,    13,   262,   283,   158,   179, SPR_IMG_SMALLMAP,        STR_SMALLMAP_CENTER},
+{    WWT_IMGBTN,   RESIZE_LRTB,    13,   262,   283,   180,   201, SPR_IMG_TOWN,            STR_0197_TOGGLE_TOWN_NAMES_ON_OFF},
+{     WWT_PANEL,    RESIZE_RTB,    13,     0,   261,   158,   201, 0x0,                     STR_NULL},
+{     WWT_PANEL,    RESIZE_RTB,    13,     0,   337,   202,   213, 0x0,                     STR_NULL},
+{ WWT_RESIZEBOX,   RESIZE_LRTB,    13,   338,   349,   202,   213, 0x0,                     STR_RESIZE_BUTTON},
 {  WIDGETS_END},
 };
 
@@ -193,8 +193,10 @@
 
 #define MKCOLOR(x) TO_LE32X(x)
 
-/* Height encodings; 16 levels XXX - needs updating for more/finer heights! */
-static const uint32 _map_height_bits[16] = {
+/**
+ * Height encodings; MAX_TILE_HEIGHT + 1 levels, from 0 to MAX_TILE_HEIGHT
+ */
+static const uint32 _map_height_bits[] = {
 	MKCOLOR(0x5A5A5A5A),
 	MKCOLOR(0x5A5B5A5B),
 	MKCOLOR(0x5B5B5B5B),
@@ -212,6 +214,7 @@
 	MKCOLOR(0x27272727),
 	MKCOLOR(0x27272727),
 };
+assert_compile(lengthof(_map_height_bits) == MAX_TILE_HEIGHT + 1);
 
 struct AndOr {
 	uint32 mor;
@@ -315,7 +318,7 @@
 		}
 		switch (tt) {
 			case TRANSPORT_RAIL: t = MP_RAILWAY; break;
-			case TRANSPORT_ROAD: t = MP_STREET;  break;
+			case TRANSPORT_ROAD: t = MP_ROAD;    break;
 			default:             t = MP_WATER;   break;
 		}
 	}
@@ -909,7 +912,7 @@
 }
 
 static const WindowDesc _smallmap_desc = {
-	WDP_AUTO, WDP_AUTO, 446, 314,
+	WDP_AUTO, WDP_AUTO, 350, 214, 446, 314,
 	WC_SMALLMAP, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_smallmap_widgets,
@@ -925,26 +928,24 @@
 
 	LowerWindowWidget(w, _smallmap_type + 5);
 	SetWindowWidgetLoweredState(w, 12, _smallmap_show_towns);
-	w->resize.width = 350;
-	w->resize.height = 250;
 
 	SmallMapCenterOnCurrentPos(w);
 }
 
 /* Extra ViewPort Window Stuff */
 static const Widget _extra_view_port_widgets[] = {
-{   WWT_CLOSEBOX,   RESIZE_NONE,    14,     0,    10,     0,    13, STR_00C5,                         STR_018B_CLOSE_WINDOW},
-{    WWT_CAPTION,  RESIZE_RIGHT,    14,    11,   287,     0,    13, STR_EXTRA_VIEW_PORT_TITLE,        STR_018C_WINDOW_TITLE_DRAG_THIS},
-{  WWT_STICKYBOX,     RESIZE_LR,    14,   288,   299,     0,    13, 0x0,                              STR_STICKY_BUTTON},
-{      WWT_PANEL,     RESIZE_RB,    14,     0,   299,    14,   233, 0x0,                              STR_NULL},
-{      WWT_INSET,     RESIZE_RB,    14,     2,   297,    16,   231, 0x0,                              STR_NULL},
-{ WWT_PUSHIMGBTN,     RESIZE_TB,    14,     0,    21,   234,   255, SPR_IMG_ZOOMIN,                   STR_017F_ZOOM_THE_VIEW_IN},
-{ WWT_PUSHIMGBTN,     RESIZE_TB,    14,    22,    43,   234,   255, SPR_IMG_ZOOMOUT,                  STR_0180_ZOOM_THE_VIEW_OUT},
-{ WWT_PUSHTXTBTN,     RESIZE_TB,    14,    44,   171,   234,   255, STR_EXTRA_VIEW_MOVE_MAIN_TO_VIEW, STR_EXTRA_VIEW_MOVE_MAIN_TO_VIEW_TT},
-{ WWT_PUSHTXTBTN,     RESIZE_TB,    14,   172,   298,   234,   255, STR_EXTRA_VIEW_MOVE_VIEW_TO_MAIN, STR_EXTRA_VIEW_MOVE_VIEW_TO_MAIN_TT},
-{      WWT_PANEL,    RESIZE_RTB,    14,   299,   299,   234,   255, 0x0,                              STR_NULL},
-{      WWT_PANEL,    RESIZE_RTB,    14,     0,   287,   256,   267, 0x0,                              STR_NULL},
-{  WWT_RESIZEBOX,   RESIZE_LRTB,    14,   288,   299,   256,   267, 0x0,                              STR_RESIZE_BUTTON},
+{   WWT_CLOSEBOX,   RESIZE_NONE,    14,     0,    10,    0,   13, STR_00C5,                         STR_018B_CLOSE_WINDOW},
+{    WWT_CAPTION,  RESIZE_RIGHT,    14,    11,   287,    0,   13, STR_EXTRA_VIEW_PORT_TITLE,        STR_018C_WINDOW_TITLE_DRAG_THIS},
+{  WWT_STICKYBOX,     RESIZE_LR,    14,   288,   299,    0,   13, 0x0,                              STR_STICKY_BUTTON},
+{      WWT_PANEL,     RESIZE_RB,    14,     0,   299,   14,   33, 0x0,                              STR_NULL},
+{      WWT_INSET,     RESIZE_RB,    14,     2,   297,   16,   31, 0x0,                              STR_NULL},
+{ WWT_PUSHIMGBTN,     RESIZE_TB,    14,     0,    21,   34,   55, SPR_IMG_ZOOMIN,                   STR_017F_ZOOM_THE_VIEW_IN},
+{ WWT_PUSHIMGBTN,     RESIZE_TB,    14,    22,    43,   34,   55, SPR_IMG_ZOOMOUT,                  STR_0180_ZOOM_THE_VIEW_OUT},
+{ WWT_PUSHTXTBTN,     RESIZE_TB,    14,    44,   171,   34,   55, STR_EXTRA_VIEW_MOVE_MAIN_TO_VIEW, STR_EXTRA_VIEW_MOVE_MAIN_TO_VIEW_TT},
+{ WWT_PUSHTXTBTN,     RESIZE_TB,    14,   172,   298,   34,   55, STR_EXTRA_VIEW_MOVE_VIEW_TO_MAIN, STR_EXTRA_VIEW_MOVE_VIEW_TO_MAIN_TT},
+{      WWT_PANEL,    RESIZE_RTB,    14,   299,   299,   34,   55, 0x0,                              STR_NULL},
+{      WWT_PANEL,    RESIZE_RTB,    14,     0,   287,   56,   67, 0x0,                              STR_NULL},
+{  WWT_RESIZEBOX,   RESIZE_LRTB,    14,   288,   299,   56,   67, 0x0,                              STR_RESIZE_BUTTON},
 {   WIDGETS_END},
 };
 
@@ -952,6 +953,9 @@
 {
 	switch (e->event) {
 	case WE_CREATE: /* Disable zoom in button */
+		/* New viewport start at (zero,zero) */
+		AssignWindowViewport(w, 3, 17, w->widget[4].right - w->widget[4].left - 1, w->widget[4].bottom - w->widget[4].top - 1, 0, ZOOM_LVL_VIEWPORT);
+
 		DisableWindowWidget(w, 5);
 		break;
 
@@ -1024,7 +1028,7 @@
 }
 
 static const WindowDesc _extra_view_port_desc = {
-	WDP_AUTO, WDP_AUTO, 300, 268,
+	WDP_AUTO, WDP_AUTO, 300, 68, 300, 268,
 	WC_EXTRA_VIEW_PORT, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_extra_view_port_widgets,
@@ -1044,14 +1048,12 @@
 		int x, y;
 		/* the main window with the main view */
 		v = FindWindowById(WC_MAIN_WINDOW, 0);
-		/* New viewport start ats (zero,zero) */
-		AssignWindowViewport(w, 3, 17, 294, 214, 0 , ZOOM_LVL_VIEWPORT);
 
 		/* center on same place as main window (zoom is maximum, no adjustment needed) */
 		x = WP(v, vp_d).scrollpos_x;
 		y = WP(v, vp_d).scrollpos_y;
-		WP(w, vp_d).scrollpos_x = x + (v->viewport->virtual_width  - (294)) / 2;
-		WP(w, vp_d).scrollpos_y = y + (v->viewport->virtual_height - (214)) / 2;
+		WP(w, vp_d).scrollpos_x = x + (v->viewport->virtual_width  - (w->widget[4].right - w->widget[4].left) - 1) / 2;
+		WP(w, vp_d).scrollpos_y = y + (v->viewport->virtual_height - (w->widget[4].bottom - w->widget[4].top) - 1) / 2;
 		WP(w, vp_d).dest_scrollpos_x = WP(w, vp_d).scrollpos_x;
 		WP(w, vp_d).dest_scrollpos_y = WP(w, vp_d).scrollpos_y;
 	}
--- a/src/sprite.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/sprite.h	Fri Aug 03 18:10:15 2007 +0000
@@ -24,7 +24,7 @@
 struct DrawTileSprites {
 	SpriteID ground_sprite;
 	SpriteID ground_pal;
-	const DrawTileSeqStruct* seq;
+	const DrawTileSeqStruct *seq;
 };
 
 /**
--- a/src/station.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/station.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -64,7 +64,6 @@
 {
 	DEBUG(station, cDebugCtorLevel, "I-%3d", index);
 
-	DeleteName(string_id);
 	MarkDirty();
 	RebuildStationLists();
 	InvalidateWindowClasses(WC_STATION_LIST);
@@ -77,35 +76,19 @@
 	/* Subsidies need removal as well */
 	DeleteSubsidyWithStation(index);
 
-	free(speclist);
 	xy = 0;
 
 	for (CargoID c = 0; c < NUM_CARGO; c++) {
 		goods[c].cargo.Truncate(0);
 	}
-}
 
-void* Station::operator new(size_t size)
-{
-	Station *st = AllocateRaw();
-	return st;
+	this->QuickFree();
 }
 
-void* Station::operator new(size_t size, int st_idx)
+void Station::QuickFree()
 {
-	if (!AddBlockIfNeeded(&_Station_pool, st_idx))
-		error("Stations: failed loading savegame: too many stations");
-
-	Station *st = GetStation(st_idx);
-	return st;
-}
-
-void Station::operator delete(void *p)
-{
-}
-
-void Station::operator delete(void *p, int st_idx)
-{
+	DeleteName(this->string_id);
+	free(this->speclist);
 }
 
 /** Called when new facility is built on the station. If it is the first facility
@@ -170,30 +153,6 @@
 	return IsTileType(tile, MP_STATION) && GetStationIndex(tile) == index && IsRailwayStation(tile);
 }
 
-/*static*/ Station *Station::AllocateRaw()
-{
-	Station *st = NULL;
-
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (st = GetStation(0); st != NULL; st = (st->index + 1U < GetStationPoolSize()) ? GetStation(st->index + 1U) : NULL) {
-		if (!st->IsValid()) {
-			StationID index = st->index;
-
-			memset(st, 0, sizeof(Station));
-			st->index = index;
-			return st;
-		}
-	}
-
-	/* Check if we can add a block to the pool */
-	if (AddBlockToPool(&_Station_pool)) return AllocateRaw();
-
-	_error_message = STR_3008_TOO_MANY_STATIONS_LOADING;
-	return NULL;
-}
-
-
 /** Obtain the length of a platform
  * @pre tile must be a railway station tile
  * @param tile A tile that contains the platform in question
@@ -420,36 +379,6 @@
 /*                     RoadStop implementation                          */
 /************************************************************************/
 
-/** Allocates a new RoadStop onto the pool, or recycles an unsed one
- *  @return a pointer to the new roadstop
- */
-void *RoadStop::operator new(size_t size)
-{
-	RoadStop *rs = AllocateRaw();
-	return rs;
-}
-
-/** Gets a RoadStop with a given index and allocates it when needed
-  * @return a pointer to the roadstop
-  */
-void *RoadStop::operator new(size_t size, int index)
-{
-	if (!AddBlockIfNeeded(&_RoadStop_pool, index)) {
-		error("RoadStops: failed loading savegame: too many RoadStops");
-	}
-
-	RoadStop *rs = GetRoadStop(index);
-	return rs;
-}
-
-void RoadStop::operator delete(void *p)
-{
-}
-
-void RoadStop::operator delete(void *p, int index)
-{
-}
-
 /** Initializes a RoadStop */
 RoadStop::RoadStop(TileIndex tile) :
 	xy(tile),
@@ -477,38 +406,13 @@
 
 	DEBUG(ms, cDebugCtorLevel , "I- at %d[0x%x]", xy, xy);
 
-	xy = INVALID_TILE;
-}
-
-
-/** Low-level function for allocating a RoadStop on the pool */
-RoadStop *RoadStop::AllocateRaw()
-{
-	RoadStop *rs;
-
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (rs = GetRoadStop(0); rs != NULL; rs = (rs->index + 1U < GetRoadStopPoolSize()) ? GetRoadStop(rs->index + 1U) : NULL) {
-		if (!rs->IsValid()) {
-			RoadStopID index = rs->index;
-
-			memset(rs, 0, sizeof(*rs));
-			rs->index = index;
-
-			return rs;
-		}
-	}
-
-	/* Check if we can add a block to the pool */
-	if (AddBlockToPool(&_RoadStop_pool)) return AllocateRaw();
-
-	return NULL;
+	xy = 0;
 }
 
 /** Determines whether a RoadStop is a valid (i.e. existing) one */
 bool RoadStop::IsValid() const
 {
-	return xy != INVALID_TILE;
+	return xy != 0;
 }
 
 /** Checks whether there is a free bay in this road stop */
--- a/src/station.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/station.h	Fri Aug 03 18:10:15 2007 +0000
@@ -16,6 +16,12 @@
 #include "cargopacket.h"
 #include <list>
 
+struct Station;
+struct RoadStop;
+
+DECLARE_OLD_POOL(Station, Station, 6, 1000)
+DECLARE_OLD_POOL(RoadStop, RoadStop, 5, 2000)
+
 static const byte INITIAL_STATION_RATING = 175;
 
 struct GoodsEntry {
@@ -36,7 +42,7 @@
 };
 
 /** A Stop for a Road Vehicle */
-struct RoadStop {
+struct RoadStop : PoolItem<RoadStop, RoadStopID, &_RoadStop_pool> {
 	/** Types of RoadStops */
 	enum Type {
 		BUS,                                ///< A standard stop for buses
@@ -48,20 +54,12 @@
 	static const uint MAX_BAY_COUNT   =  2;  ///< The maximum number of loading bays
 
 	TileIndex        xy;                    ///< Position on the map
-	RoadStopID       index;                 ///< Global (i.e. pool-wide) index
 	byte             status;                ///< Current status of the Stop. Like which spot is taken. Access using *Bay and *Busy functions.
 	byte             num_vehicles;          ///< Number of vehicles currently slotted to this stop
 	struct RoadStop  *next;                 ///< Next stop of the given type at this station
 
-	RoadStop(TileIndex tile);
-	~RoadStop();
-
-	void *operator new (size_t size);
-	void operator delete(void *rs);
-
-	/* For loading games */
-	void *operator new (size_t size, int index);
-	void operator delete(void *rs, int index);
+	RoadStop(TileIndex tile = 0);
+	virtual ~RoadStop();
 
 	bool IsValid() const;
 
@@ -73,8 +71,6 @@
 	void FreeBay(uint nr);
 	bool IsEntranceBusy() const;
 	void SetEntranceBusy(bool busy);
-protected:
-	static RoadStop *AllocateRaw();
 };
 
 struct StationSpecList {
@@ -112,7 +108,7 @@
 	StationRect& operator = (Rect src);
 };
 
-struct Station {
+struct Station : PoolItem<Station, StationID, &_Station_pool> {
 	public:
 		RoadStop *GetPrimaryRoadStop(RoadStop::Type type) const
 		{
@@ -159,7 +155,6 @@
 	Date build_date;
 
 	FSMblockmap airport_flags;   ///< stores which blocks on the port are taken
-	StationID index;
 
 	byte last_vehicle_type;
 	std::list<Vehicle *> loading_vehicles;
@@ -173,15 +168,9 @@
 	static const int cDebugCtorLevel = 3;
 
 	Station(TileIndex tile = 0);
-	~Station();
+	virtual ~Station();
 
-	/* normal new/delete operators. Used when building/removing station */
-	void* operator new (size_t size);
-	void operator delete(void *p);
-
-	/* new/delete operators accepting station index. Used when loading station from savegame. */
-	void* operator new (size_t size, int st_idx);
-	void operator delete(void *p, int st_idx);
+	void QuickFree();
 
 	void AddFacility(byte new_facility_bit, TileIndex facil_xy);
 	void MarkDirty() const;
@@ -191,9 +180,6 @@
 	uint GetPlatformLength(TileIndex tile) const;
 	bool IsBuoy() const;
 	bool IsValid() const;
-
-protected:
-	static Station *AllocateRaw();
 };
 
 enum StationType {
@@ -243,8 +229,6 @@
 void RebuildStationLists();
 void ResortStationLists();
 
-DECLARE_OLD_POOL(Station, Station, 6, 1000)
-
 static inline StationID GetMaxStationIndex()
 {
 	/* TODO - This isn't the real content of the function, but
@@ -271,8 +255,6 @@
 
 /* Stuff for ROADSTOPS */
 
-DECLARE_OLD_POOL(RoadStop, RoadStop, 5, 2000)
-
 #define FOR_ALL_ROADSTOPS_FROM(rs, start) for (rs = GetRoadStop(start); rs != NULL; rs = (rs->index + 1U < GetRoadStopPoolSize()) ? GetRoadStop(rs->index + 1U) : NULL) if (rs->IsValid())
 #define FOR_ALL_ROADSTOPS(rs) FOR_ALL_ROADSTOPS_FROM(rs, 0)
 
--- a/src/station_cmd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/station_cmd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -46,41 +46,38 @@
 #include "airport_states.h"
 #include "newgrf_fsmports.h"
 
-/**
- * Called if a new block is added to the station-pool
- */
-static void StationPoolNewBlock(uint start_item)
-{
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 *  TODO - This is just a temporary stage, this will be removed. */
-	for (Station *st = GetStation(start_item); st != NULL; st = (st->index + 1U < GetStationPoolSize()) ? GetStation(st->index + 1U) : NULL) st->index = start_item++;
-}
-
-static void StationPoolCleanBlock(uint start_item, uint end_item)
-{
-	for (uint i = start_item; i <= end_item; i++) {
-		Station *st = GetStation(i);
-		if (st->IsValid()) st->~Station();
-	}
-}
+DEFINE_OLD_POOL_GENERIC(Station, Station)
+DEFINE_OLD_POOL_GENERIC(RoadStop, RoadStop)
+
 
 /**
- * Called if a new block is added to the roadstop-pool
+ * Check whether the given tile is a hangar.
+ * @param t the tile to of whether it is a hangar.
+ * @pre IsTileType(t, MP_STATION)
+ * @return true if and only if the tile is a hangar.
  */
-static void RoadStopPoolNewBlock(uint start_item)
+bool IsHangar(TileIndex t)
 {
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (RoadStop *rs = GetRoadStop(start_item); rs != NULL; rs = (rs->index + 1U < GetRoadStopPoolSize()) ? GetRoadStop(rs->index + 1U) : NULL) {
-		rs->xy    = INVALID_TILE;
-		rs->index = start_item++;
+	assert(IsTileType(t, MP_STATION));
+
+	Station *st = GetStationByTile(t);
+	TileIndexDiffC *hangar_list;
+	byte num_depots;
+	if (IsCustomFSMportsSpecIndex(t)) {
+		hangar_list = st->fsmportsspeclist[1].spec->portFSM->airport_depots;
+		num_depots = st->fsmportsspeclist[1].spec->portFSM->nof_depots;
+	} else {
+		hangar_list = st->Airport()->airport_depots;
+		num_depots = st->Airport()->nof_depots;
 	}
+	for (uint i = 0; i < num_depots; i++) {
+		if (st->airport_tile + ToTileIndexDiff(hangar_list[i]) == t) {
+			return true;
+		}
+	}
+	return false;
 }
 
-DEFINE_OLD_POOL(Station, Station, StationPoolNewBlock, StationPoolCleanBlock)
-DEFINE_OLD_POOL(RoadStop, RoadStop, RoadStopPoolNewBlock, NULL)
-
-
 RoadStop* GetRoadStopByTile(TileIndex tile, RoadStop::Type type)
 {
 	const Station* st = GetStationByTile(tile);
@@ -140,6 +137,12 @@
 	return (closest_station == INVALID_STATION) ? NULL : GetStation(closest_station);
 }
 
+/**
+ * Function to check whether the given tile matches some criterion.
+ * @param tile the tile to check
+ * @return true if it matches, false otherwise
+ */
+typedef bool (*CMSAMatcher)(TileIndex tile);
 
 /**
  * Counts the numbers of tiles matching a specific type in the area around
@@ -149,39 +152,85 @@
  *                 in all other cases this parameter is ignored
  * @return the result the noumber of matching tiles around
  */
-static int CountMapSquareAround(TileIndex tile, TileType type, IndustryType industry)
+static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
 {
 	int num = 0;
 
 	for (int dx = -3; dx <= 3; dx++) {
 		for (int dy = -3; dy <= 3; dy++) {
-			TileIndex cur_tile = TILE_MASK(tile + TileDiffXY(dx, dy));
-
-			if (IsTileType(cur_tile, type)) {
-				switch (type) {
-					case MP_INDUSTRY:
-						if (GetIndustryType(cur_tile) == industry)
-							num++;
-						break;
-
-					case MP_WATER:
-						if (!IsWater(cur_tile))
-							break;
-						/* FALL THROUGH WHEN WATER TILE */
-					case MP_TREES:
-						num++;
-						break;
-
-					default:
-						break;
-				}
-			}
+			if (cmp(TILE_MASK(tile + TileDiffXY(dx, dy)))) num++;
 		}
 	}
 
 	return num;
 }
 
+/**
+ * Check whether the tile is a mine.
+ * @param tile the tile to investigate.
+ * @return true if and only if the tile is a mine
+ */
+static bool CMSAMine(TileIndex tile)
+{
+	/* No industry */
+	if (!IsTileType(tile, MP_INDUSTRY)) return false;
+
+	const IndustrySpec *indsp = GetIndustrySpec(GetIndustryByTile(tile)->type);
+
+	/* No extractive industry */
+	if ((indsp->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
+
+	for (uint i = 0; i < lengthof(indsp->produced_cargo); i++) {
+		/* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine */
+		if (indsp->produced_cargo[i] != CT_INVALID && (GetCargo(indsp->produced_cargo[i])->classes & CC_LIQUID) == 0) return true;
+	}
+
+	return false;
+}
+
+/**
+ * Check whether the tile is water.
+ * @param tile the tile to investigate.
+ * @return true if and only if the tile is a mine
+ */
+static bool CMSAWater(TileIndex tile)
+{
+	return IsTileType(tile, MP_WATER) && IsWater(tile);
+}
+
+/**
+ * Check whether the tile is a tree.
+ * @param tile the tile to investigate.
+ * @return true if and only if the tile is a mine
+ */
+static bool CMSATree(TileIndex tile)
+{
+	return IsTileType(tile, MP_TREES);
+}
+
+/**
+ * Check whether the tile is a forest.
+ * @param tile the tile to investigate.
+ * @return true if and only if the tile is a mine
+ */
+static bool CMSAForest(TileIndex tile)
+{
+	/* No industry */
+	if (!IsTileType(tile, MP_INDUSTRY)) return false;
+
+	const IndustrySpec *indsp = GetIndustrySpec(GetIndustryByTile(tile)->type);
+
+	/* No extractive industry */
+	if ((indsp->life_type & INDUSTRYLIFE_ORGANIC) == 0) return false;
+
+	for (uint i = 0; i < lengthof(indsp->produced_cargo); i++) {
+		/* The industry produces wood. */
+		if (indsp->produced_cargo[i] != CT_INVALID && GetCargo(indsp->produced_cargo[i])->label == 'WOOD') return true;
+	}
+
+	return false;
+}
+
 #define M(x) ((x) - STR_SV_STNAME)
 
 static bool GenerateStationName(Station *st, TileIndex tile, int flag)
@@ -224,11 +273,7 @@
 
 	/* check mine? */
 	if (HASBIT(free_names, M(STR_SV_STNAME_MINES))) {
-		if (CountMapSquareAround(tile, MP_INDUSTRY, IT_COAL_MINE) >= 2 ||
-				CountMapSquareAround(tile, MP_INDUSTRY, IT_IRON_MINE) >= 2 ||
-				CountMapSquareAround(tile, MP_INDUSTRY, IT_COPPER_MINE) >= 2 ||
-				CountMapSquareAround(tile, MP_INDUSTRY, IT_GOLD_MINE) >= 2 ||
-				CountMapSquareAround(tile, MP_INDUSTRY, IT_DIAMOND_MINE) >= 2) {
+		if (CountMapSquareAround(tile, CMSAMine) >= 2) {
 			found = M(STR_SV_STNAME_MINES);
 			goto done;
 		}
@@ -246,15 +291,15 @@
 	/* Check lakeside */
 	if (HASBIT(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
 			DistanceFromEdge(tile) < 20 &&
-			CountMapSquareAround(tile, MP_WATER, 0) >= 5) {
+			CountMapSquareAround(tile, CMSAWater) >= 5) {
 		found = M(STR_SV_STNAME_LAKESIDE);
 		goto done;
 	}
 
 	/* Check woods */
 	if (HASBIT(free_names, M(STR_SV_STNAME_WOODS)) && (
-				CountMapSquareAround(tile, MP_TREES, 0) >= 8 ||
-				CountMapSquareAround(tile, MP_INDUSTRY, IT_FOREST) >= 2)
+				CountMapSquareAround(tile, CMSATree) >= 8 ||
+				CountMapSquareAround(tile, CMSAForest) >= 2)
 			) {
 		found = _opt.landscape == LT_TROPIC ?
 			M(STR_SV_STNAME_FOREST) : M(STR_SV_STNAME_WOODS);
@@ -912,7 +957,7 @@
 	} else {
 		/* allocate and initialize new station */
 		st = new Station(tile_org);
-		if (st == NULL) return CMD_ERROR;
+		if (st == NULL) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);
 
 		/* ensure that in case of error (or no DC_EXEC) the station gets deleted upon return */
 		st_auto_delete = st;
@@ -1266,7 +1311,7 @@
 {
 	bool type = HASBIT(p2, 0);
 	bool is_drive_through = HASBIT(p2, 1);
-	bool build_over_road  = is_drive_through && IsTileType(tile, MP_STREET) && GetRoadTileType(tile) == ROAD_TILE_NORMAL;
+	bool build_over_road  = is_drive_through && IsTileType(tile, MP_ROAD) && GetRoadTileType(tile) == ROAD_TILE_NORMAL;
 	bool town_owned_road  = build_over_road && IsTileOwner(tile, OWNER_TOWN);
 	RoadTypes rts = (RoadTypes)GB(p2, 2, 3);
 
@@ -1343,7 +1388,7 @@
 	} else {
 		/* allocate and initialize new station */
 		st = new Station(tile);
-		if (st == NULL) return CMD_ERROR;
+		if (st == NULL) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);
 
 		/* ensure that in case of error (or no DC_EXEC) the new station gets deleted upon return */
 		st_auto_delete = st;
@@ -1584,7 +1629,7 @@
 
 		/* allocate and initialize new station */
 		st = new Station(tile);
-		if (st == NULL) return CMD_ERROR;
+		if (st == NULL) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);
 
 		/* ensure that in case of error (or no DC_EXEC) the station gets deleted upon return */
 		st_auto_delete = st;
@@ -1754,7 +1799,7 @@
 
 	/* allocate and initialize new station */
 	Station *st = new Station(tile);
-	if (st == NULL) return CMD_ERROR;
+	if (st == NULL) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);
 
 	/* ensure that in case of error (or no DC_EXEC) the station gets deleted upon return */
 	AutoPtrT<Station> st_auto_delete(st);
@@ -1919,7 +1964,7 @@
 	} else {
 		/* allocate and initialize new station */
 		st = new Station(tile);
-		if (st == NULL) return CMD_ERROR;
+		if (st == NULL) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);
 
 		/* ensure that in case of error (or no DC_EXEC) the station gets deleted upon return */
 		st_auto_delete = st;
@@ -2022,7 +2067,7 @@
 
 	// don't show foundation for docks
 	if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile))
-		DrawFoundation(ti, ti->tileh);
+		DrawFoundation(ti, FOUNDATION_LEVELED);
 
 	if (IsCustomStationSpecIndex(ti->tile)) {
 		// look for customization
@@ -2103,10 +2148,7 @@
 		}
 
 		SpriteID pal;
-		if (HASBIT(_transparent_opt, TO_BUILDINGS)) {
-			SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
-			pal = PALETTE_TO_TRANSPARENT;
-		} else if (HASBIT(image, PALETTE_MODIFIER_COLOR)) {
+		if (!HASBIT(_transparent_opt, TO_BUILDINGS) && HASBIT(image, PALETTE_MODIFIER_COLOR)) {
 			pal = palette;
 		} else {
 			pal = dtss->pal;
@@ -2117,7 +2159,8 @@
 				image, pal,
 				ti->x + dtss->delta_x, ti->y + dtss->delta_y,
 				dtss->size_x, dtss->size_y,
-				dtss->size_z, ti->z + dtss->delta_z
+				dtss->size_z, ti->z + dtss->delta_z,
+				HASBIT(_transparent_opt, TO_BUILDINGS)
 			);
 		} else {
 			AddChildSpriteScreen(image, pal, dtss->delta_x, dtss->delta_y);
@@ -2150,9 +2193,9 @@
 	return GetTileMaxZ(tile);
 }
 
-static Slope GetSlopeTileh_Station(TileIndex tile, Slope tileh)
+static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
 {
-	return SLOPE_FLAT;
+	return FlatteningFoundation(tileh);
 }
 
 static void GetAcceptedCargo_Station(TileIndex tile, AcceptedCargo ac)
@@ -2854,12 +2897,12 @@
 void InitializeStations()
 {
 	/* Clean the station pool and create 1 block in it */
-	CleanPool(&_Station_pool);
-	AddBlockToPool(&_Station_pool);
+	_Station_pool.CleanPool();
+	_Station_pool.AddBlockToPool();
 
 	/* Clean the roadstop pool and create 1 block in it */
-	CleanPool(&_RoadStop_pool);
-	AddBlockToPool(&_RoadStop_pool);
+	_RoadStop_pool.CleanPool();
+	_RoadStop_pool.AddBlockToPool();
 
 	_station_tick_ctr = 0;
 
@@ -2901,7 +2944,7 @@
 	ChangeTileOwner_Station,    /* change_tile_owner_clear */
 	NULL,                       /* get_produced_cargo_proc */
 	VehicleEnter_Station,       /* vehicle_enter_tile_proc */
-	GetSlopeTileh_Station,      /* get_slope_tileh_proc */
+	GetFoundation_Station,      /* get_foundation_proc */
 };
 
 static const SaveLoad _roadstop_desc[] = {
--- a/src/station_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/station_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -569,7 +569,7 @@
 };
 
 static const WindowDesc _player_stations_desc = {
-	WDP_AUTO, WDP_AUTO, 358, 162,
+	WDP_AUTO, WDP_AUTO, 358, 162, 358, 162,
 	WC_STATION_LIST, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_player_stations_widgets,
@@ -895,7 +895,7 @@
 
 
 static const WindowDesc _station_view_desc = {
-	WDP_AUTO, WDP_AUTO, 249, 110,
+	WDP_AUTO, WDP_AUTO, 249, 110, 249, 110,
 	WC_STATION_VIEW, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON,
 	_station_view_widgets,
--- a/src/station_map.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/station_map.h	Fri Aug 03 18:10:15 2007 +0000
@@ -17,7 +17,7 @@
 	return (StationID)_m[t].m2;
 }
 
-static inline Station* GetStationByTile(TileIndex t)
+static inline Station *GetStationByTile(TileIndex t)
 {
 	return GetStation(GetStationIndex(t));
 }
@@ -42,15 +42,6 @@
 	GFX_WINDSACK_INTERCON_LAST        = 143,
 };
 
-enum HangarTile {
-	HANGAR_TILE_0 = 24,
-	HANGAR_TILE_1 = 57,
-	HANGAR_TILE_2 = 62,
-	HANGAR_TILE_3 = 105, // added for west facing hangar
-	HANGAR_TILE_4 = 106, // added for north facing hangar
-	HANGAR_TILE_5 = 107  // added for east facing hangar
-};
-
 static inline StationType GetStationType(TileIndex t)
 {
 	return (StationType)GB(_m[t].m6, 3, 3);
@@ -89,25 +80,7 @@
 	return GetStationType(t) == STATION_AIRPORT;
 }
 
-static inline bool IsHangar(TileIndex t)
-{
-	Station *st = GetStationByTile(t);
-	TileIndexDiffC *hangar_list;
-	byte num_depots;
-	if (IsCustomFSMportsSpecIndex(t)) {
-		hangar_list = st->fsmportsspeclist[1].spec->portFSM->airport_depots;
-		num_depots = st->fsmportsspeclist[1].spec->portFSM->nof_depots;
-	} else {
-		hangar_list = st->Airport()->airport_depots;
-		num_depots = st->Airport()->nof_depots;
-	}
-	for (uint i = 0; i < num_depots; i++) {
-		if (st->airport_tile + ToTileIndexDiff(hangar_list[i]) == t) {
-			return true;
-		}
-	}
-	return false;
-}
+bool IsHangar(TileIndex t);
 
 static inline bool IsTruckStop(TileIndex t)
 {
--- a/src/strgen/strgen.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/strgen/strgen.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -1019,19 +1019,20 @@
 	out = fopen("tmp.xxx", "w");
 	if (out == NULL) fatal("can't open tmp.xxx");
 
-	fprintf(out, "enum StringIdEnum {");
+	fprintf(out, "/* This file is automatically generated. Do not modify */\n\n");
+	fprintf(out, "#ifndef TABLE_STRINGS_H\n");
+	fprintf(out, "#define TABLE_STRINGS_H\n");
 
 	lastgrp = 0;
 
 	for (i = 0; i != lengthof(_strings); i++) {
 		if (_strings[i] != NULL) {
-			fprintf(out, next == i ? "\t%s,\n" : "\n\t%s = 0x%X,\n", _strings[i]->name, i);
+			if (next != i) fprintf(out, "\n");
+			fprintf(out, "static const StringID %s = 0x%X;\n", _strings[i]->name, i);
 			next = i + 1;
 		}
 	}
 
-	fprintf(out, "};\n");
-
 	fprintf(out,
 		"\nenum {\n"
 		"\tLANGUAGE_PACK_IDENT = 0x474E414C, // Big Endian value for 'LANG' (LE is 0x 4C 41 4E 47)\n"
@@ -1039,6 +1040,8 @@
 		"};\n", (uint)_hash
 	);
 
+	fprintf(out, "\n#endif /* TABLE_STRINGS_H */\n");
+
 	fclose(out);
 
 	if (CompareFiles("tmp.xxx", filename)) {
--- a/src/string.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/string.h	Fri Aug 03 18:10:15 2007 +0000
@@ -24,10 +24,10 @@
  *             if NULL no boundary check is performed
  * @return a pointer to the terminating \0 in the destination buffer
  */
-char* strecat(char* dst, const char* src, const char* last);
-char* strecpy(char* dst, const char* src, const char* last);
+char *strecat(char *dst, const char *src, const char *last);
+char *strecpy(char *dst, const char *src, const char *last);
 
-char* CDECL str_fmt(const char* str, ...);
+char *CDECL str_fmt(const char *str, ...);
 
 /** Scans the string for valid characters and if it finds invalid ones,
  * replaces them with a question mark '?' */
@@ -49,7 +49,7 @@
 void strtolower(char *str);
 
 
-static inline bool StrEmpty(const char* s) { return s[0] == '\0'; }
+static inline bool StrEmpty(const char *s) { return s[0] == '\0'; }
 
 
 /** Get the length of a string, within a limited buffer */
--- a/src/strings.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/strings.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -224,27 +224,14 @@
 	memmove(_decode_parameters + amount, _decode_parameters, sizeof(_decode_parameters) - amount * sizeof(uint64));
 }
 
-static const uint32 _divisor_table[] = {
-	1000000000,
-	100000000,
-	10000000,
-	1000000,
-
-	100000,
-	10000,
-	1000,
-	100,
-	10,
-	1
-};
-
 // TODO
-static char *FormatCommaNumber(char *buff, int32 number, const char* last)
+static char *FormatCommaNumber(char *buff, int64 number, const char *last)
 {
-	uint32 quot,divisor;
+	uint64 divisor = 10000000000000000000ULL;
+	uint64 quot;
 	int i;
-	uint32 tot;
-	uint32 num;
+	uint64 tot;
+	uint64 num;
 
 	if (number < 0) {
 		*buff++ = '-';
@@ -254,17 +241,18 @@
 	num = number;
 
 	tot = 0;
-	for (i = 0; i != 10; i++) {
-		divisor = _divisor_table[i];
+	for (i = 0; i < 20; i++) {
 		quot = 0;
 		if (num >= divisor) {
-			quot = num / _divisor_table[i];
-			num = num % _divisor_table[i];
+			quot = num / divisor;
+			num = num % divisor;
 		}
-		if (tot |= quot || i == 9) {
+		if (tot |= quot || i == 19) {
 			*buff++ = '0' + quot;
-			if (i == 0 || i == 3 || i == 6) *buff++ = ',';
+			if ((i % 3) == 1 && i != 19) *buff++ = ',';
 		}
+
+		divisor /= 10;
 	}
 
 	*buff = '\0';
@@ -273,12 +261,13 @@
 }
 
 // TODO
-static char *FormatNoCommaNumber(char *buff, int32 number, const char* last)
+static char *FormatNoCommaNumber(char *buff, int64 number, const char *last)
 {
-	uint32 quot,divisor;
+	uint64 divisor = 10000000000000000000ULL;
+	uint64 quot;
 	int i;
-	uint32 tot;
-	uint32 num;
+	uint64 tot;
+	uint64 num;
 
 	if (number < 0) {
 		buff = strecpy(buff, "-", last);
@@ -288,16 +277,17 @@
 	num = number;
 
 	tot = 0;
-	for (i = 0; i != 10; i++) {
-		divisor = _divisor_table[i];
+	for (i = 0; i < 20; i++) {
 		quot = 0;
 		if (num >= divisor) {
-			quot = num / _divisor_table[i];
-			num = num % _divisor_table[i];
+			quot = num / divisor;
+			num = num % divisor;
 		}
-		if (tot |= quot || i == 9) {
+		if (tot |= quot || i == 19) {
 			*buff++ = '0' + quot;
 		}
+
+		divisor /= 10;
 	}
 
 	*buff = '\0';
@@ -396,10 +386,11 @@
 	return buff;
 }
 
-static int DeterminePluralForm(int32 n)
+static int DeterminePluralForm(int64 cnt)
 {
+	uint64 n = cnt;
 	/* The absolute value determines plurality */
-	if (n < 0) n = -n;
+	if (cnt < 0) n = -cnt;
 
 	switch (_langpack->plural_form) {
 	/* Two forms, singular used for one only
@@ -665,7 +656,7 @@
 				int64 args[2];
 
 				/* industry not valid anymore? */
-				if (!IsValidIndustry(i)) break;
+				if (!i->IsValid()) break;
 
 				/* First print the town name and the industry type name
 				 * The string STR_INDUSTRY_PATTERN controls the formatting */
@@ -705,7 +696,7 @@
 				 *   8bit   - cargo type
 				 *   16-bit - cargo count */
 				CargoID cargo = GetInt32(&argv);
-				StringID cargo_str = (cargo == CT_INVALID) ? (StringID)STR_8838_N_A : GetCargo(cargo)->quantifier;
+				StringID cargo_str = (cargo == CT_INVALID) ? STR_8838_N_A : GetCargo(cargo)->quantifier;
 				buff = GetStringWithArgs(buff, cargo_str, argv++, last);
 				break;
 			}
@@ -776,7 +767,7 @@
 			}
 
 			case SCC_COMMA: // {COMMA}
-				buff = FormatCommaNumber(buff, GetInt32(&argv), last);
+				buff = FormatCommaNumber(buff, GetInt64(&argv), last);
 				break;
 
 			case SCC_ARG_INDEX: // Move argument pointer
@@ -784,7 +775,7 @@
 				break;
 
 			case SCC_PLURAL_LIST: { // {P}
-				int32 v = argv_orig[(byte)*str++]; // contains the number that determines plural
+				int64 v = argv_orig[(byte)*str++]; // contains the number that determines plural
 				int len;
 				str = ParseStringChoice(str, DeterminePluralForm(v), buff, &len);
 				buff += len;
@@ -792,7 +783,7 @@
 			}
 
 			case SCC_NUM: // {NUM}
-				buff = FormatNoCommaNumber(buff, GetInt32(&argv), last);
+				buff = FormatNoCommaNumber(buff, GetInt64(&argv), last);
 				break;
 
 			case SCC_CURRENCY: // {CURRENCY}
@@ -833,7 +824,7 @@
 				const Town* t = GetTown(GetInt32(&argv));
 				int64 temp[1];
 
-				assert(IsValidTown(t));
+				assert(t->IsValid());
 
 				temp[0] = t->townnameparts;
 				uint32 grfid = t->townnamegrfid;
@@ -858,10 +849,10 @@
 				const Group *g = GetGroup(GetInt32(&argv));
 				int64 args[1];
 
-				assert(IsValidGroup(g));
+				assert(g->IsValid());
 
 				args[0] = g->index;
-				buff = GetStringWithArgs(buff, IsCustomName(g->string_id) ? g->string_id : (StringID)STR_GROUP_NAME_FORMAT, args, last);
+				buff = GetStringWithArgs(buff, IsCustomName(g->string_id) ? g->string_id : STR_GROUP_NAME_FORMAT, args, last);
 
 				break;
 			}
@@ -1226,6 +1217,8 @@
 	return true;
 }
 
+/* Win32 implementation in win32.cpp. */
+#ifndef WIN32
 /** Determine the current charset based on the environment
  * First check some default values, after this one we passed ourselves
  * and if none exist return the value for $LANG
@@ -1249,6 +1242,7 @@
 
 	return getenv("LANG");
 }
+#endif /* ifndef WIN32 */
 
 static int CDECL LanguageCompareFunc(const void *a, const void *b)
 {
--- a/src/strings.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/strings.h	Fri Aug 03 18:10:15 2007 +0000
@@ -6,7 +6,7 @@
 #define STRINGS_H
 
 char *InlineString(char *buf, StringID string);
-char *GetString(char *buffr, StringID string, const char* last);
+char *GetString(char *buffr, StringID string, const char *last);
 
 extern char _userstring[128];
 
--- a/src/subsidy_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/subsidy_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -166,7 +166,7 @@
 };
 
 static const WindowDesc _subsidies_list_desc = {
-	WDP_AUTO, WDP_AUTO, 630, 127,
+	WDP_AUTO, WDP_AUTO, 630, 127, 630, 127,
 	WC_SUBSIDIES_LIST, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
 	_subsidies_list_widgets,
--- a/src/table/ai_rail.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/table/ai_rail.h	Fri Aug 03 18:10:15 2007 +0000
@@ -2,7 +2,7 @@
 
 struct AiDefaultBlockData {
 	byte mode;
-	byte attr;
+	DiagDirection attr;
 	TileIndexDiffC tileoffs;
 };
 
@@ -22,11 +22,11 @@
 
 
 #define MKHDR(a, b, c, d, e) a, b, c, d, e,
-#define MKDEPOT(a, b, c)   {0, a, {b, c}}
-#define MKSTATION(a, b, c) {1, a, {b, c}}
-#define MKRAIL(a, b, c)    {2, a, {b, c}}
-#define MKCLRRAIL(a, b, c) {3, a, {b, c}}
-#define MKEND              {4, 0, {0, 0}}
+#define MKDEPOT(a, b, c)   {0, (DiagDirection)a, {b, c}}
+#define MKSTATION(a, b, c) {1, (DiagDirection)a, {b, c}}
+#define MKRAIL(a, b, c)    {2, (DiagDirection)a, {b, c}}
+#define MKCLRRAIL(a, b, c) {3, (DiagDirection)a, {b, c}}
+#define MKEND              {4, (DiagDirection)0, {0, 0}}
 
 static const AiDefaultBlockData _raildata_ai_0_data[] = {
 	MKDEPOT(2, -1, 1),
@@ -555,38 +555,50 @@
 	NULL
 };
 
-#define MKAIR(a, b, c) {0, a, {b, c}}
+#undef MKHDR
+#undef MKDEPOT
+#undef MKSTATION
+#undef MKRAIL
+#undef MKCLRRAIL
+#undef MKEND
+
+
+#define MKAIR(a, b, c) {0, (DiagDirection)a, {b, c}}
+#define MKEND() {1, (DiagDirection)0, {0, 0}}
 
 static const AiDefaultBlockData _airportdata_ai_0[] = {
 	MKAIR(1, 0, 0),
-	{1, 0, {0, 0}},
+	MKEND(),
 };
 
 static const AiDefaultBlockData _airportdata_ai_1[] = {
 	MKAIR(0, 0, 0),
-	{1, 0, {0, 0}}
+	MKEND(),
 };
 
 static const AiDefaultBlockData _airportdata_ai_3[] = {
 	MKAIR(3, 0, 0),
-	{1, 0, {0, 0}},
+	MKEND(),
 };
 
 static const AiDefaultBlockData _airportdata_ai_4[] = {
 	MKAIR(4, 0, 0),
-	{1, 0, {0, 0}},
+	MKEND(),
 };
 
 static const AiDefaultBlockData _airportdata_ai_5[] = {
 	MKAIR(5, 0, 0),
-	{1, 0, {0, 0}},
+	MKEND(),
 };
 
 static const AiDefaultBlockData _airportdata_ai_7[] = {
 	MKAIR(7, 0, 0),
-	{1, 0, {0, 0}}
+	MKEND(),
 };
 
+#undef MKAIR
+#undef MDEND
+
 static const AiDefaultBlockData * const _airport_default_block_data[] = {
 	_airportdata_ai_7, // intercontinental airport
 	_airportdata_ai_4, // international airport
--- a/src/table/build_industry.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/table/build_industry.h	Fri Aug 03 18:10:15 2007 +0000
@@ -1091,6 +1091,47 @@
 /** Array with... hem... a sound of toyland */
 static const uint8 _plastic_mine_sounds[] = { SND_33_PLASTIC_MINE };
 
+enum {
+	IT_COAL_MINE           =   0,
+	IT_POWER_STATION       =   1,
+	IT_SAWMILL             =   2,
+	IT_FOREST              =   3,
+	IT_OIL_REFINERY        =   4,
+	IT_OIL_RIG             =   5,
+	IT_FACTORY             =   6,
+	IT_PRINTING_WORKS      =   7,
+	IT_STEEL_MILL          =   8,
+	IT_FARM                =   9,
+	IT_COPPER_MINE         =  10,
+	IT_OIL_WELL            =  11,
+	IT_BANK_TEMP           =  12,
+	IT_FOOD_PROCESS        =  13,
+	IT_PAPER_MILL          =  14,
+	IT_GOLD_MINE           =  15,
+	IT_BANK_TROPIC_ARCTIC  =  16,
+	IT_DIAMOND_MINE        =  17,
+	IT_IRON_MINE           =  18,
+	IT_FRUIT_PLANTATION    =  19,
+	IT_RUBBER_PLANTATION   =  20,
+	IT_WATER_SUPPLY        =  21,
+	IT_WATER_TOWER         =  22,
+	IT_FACTORY_2           =  23,
+	IT_FARM_2              =  24,
+	IT_LUMBER_MILL         =  25,
+	IT_COTTON_CANDY        =  26,
+	IT_CANDY_FACTORY       =  27,
+	IT_BATTERY_FARM        =  28,
+	IT_COLA_WELLS          =  29,
+	IT_TOY_SHOP            =  30,
+	IT_TOY_FACTORY         =  31,
+	IT_PLASTIC_FOUNTAINS   =  32,
+	IT_FIZZY_DRINK_FACTORY =  33,
+	IT_BUBBLE_GENERATOR    =  34,
+	IT_TOFFEE_QUARRY       =  35,
+	IT_SUGAR_MINE          =  36,
+	IT_END,
+};
+
 /**
  * Writes the properties of an industry into the IndustrySpec struct.
  * @param tbl  tile table
@@ -1532,7 +1573,7 @@
  * @param a2  next frame of animation
  * @param a3  chooses between animation or construction state
  */
-#define MT(ca1, c1, ca2, c2, ca3, c3, sl, a1, a2, a3) {{c1, c2, c3}, {ca1, ca2, ca3}, sl, a1, a2, a3, 0, 0xFFFF, 2, 0, 0, true, {0, 0, NULL, NULL, 0}}
+#define MT(ca1, c1, ca2, c2, ca3, c3, sl, a1, a2, a3) {{c1, c2, c3}, {ca1, ca2, ca3}, sl, a1, a2, a3, 0, 0xFFFF, 2, 0, 0, true, {0, 0, NULL, NULL, INVALID_INDUSTRYTILE}}
 static const IndustryTileSpec _origin_industry_tile_specs[NEW_INDUSTRYTILEOFFSET] = {
 	/* Coal Mine */
 	MT(0,  CT_INVALID,      0,  CT_INVALID,   0,  CT_INVALID,    SLOPE_STEEP,  INDUSTRYTILE_NOANIM,   INDUSTRYTILE_NOANIM,  false),
--- a/src/table/sprites.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/table/sprites.h	Fri Aug 03 18:10:15 2007 +0000
@@ -50,7 +50,13 @@
 	OPENTTD_SPRITES_COUNT = 112, // number of gfx-sprites in openttd.grf
 	SPR_SIGNALS_BASE  = 4896,
 	SPR_CANALS_BASE   = SPR_SIGNALS_BASE + 486,
-	SPR_SLOPES_BASE   = SPR_CANALS_BASE + 70,
+
+	SPR_SLOPES_BASE                    = SPR_CANALS_BASE + 70,
+	SPR_SLOPES_INCLINED_OFFSET         = 15,
+	SPR_SLOPES_VIRTUAL_BASE            = SPR_SLOPES_BASE - SPR_SLOPES_INCLINED_OFFSET, // The original foundations (see SPR_FOUNDATION_BASE below) are mapped before the additional foundations.
+	SPR_SLOPES_NO_FOUNDATION_NW_OFFSET = 22, // no wall on the NW edge of the tile.
+	SPR_SLOPES_NO_FOUNDATION_NE_OFFSET = 44, // no wall on the NE edge of the tile.
+
 	SPR_AUTORAIL_BASE = SPR_SLOPES_BASE + 78,
 	SPR_ELRAIL_BASE   = SPR_AUTORAIL_BASE + 55,
 	SPR_2CCMAP_BASE   = SPR_ELRAIL_BASE + 53,
@@ -303,6 +309,16 @@
 	OFFSET_TILEH_13             = 19,
 	OFFSET_TILEH_14             = 16,
 
+	/* Track fences */
+	SPR_TRACK_FENCE_FLAT_X    = 1301,
+	SPR_TRACK_FENCE_FLAT_Y    = 1302,
+	SPR_TRACK_FENCE_FLAT_VERT = 1303,
+	SPR_TRACK_FENCE_FLAT_HORZ = 1304,
+	SPR_TRACK_FENCE_SLOPE_SW  = 1305,
+	SPR_TRACK_FENCE_SLOPE_SE  = 1306,
+	SPR_TRACK_FENCE_SLOPE_NE  = 1307,
+	SPR_TRACK_FENCE_SLOPE_NW  = 1308,
+
 	/* Elrail stuff */
 	/* Wires. First identifier is the direction of the track, second is the required placement of the pylon.
 	 * "short" denotes a wire that requires a pylon on each end. Third identifier is the direction of the slope
--- a/src/terraform_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/terraform_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -278,7 +278,7 @@
 };
 
 static const WindowDesc _terraform_desc = {
-	WDP_ALIGN_TBR, 22 + 36, 158, 36,
+	WDP_ALIGN_TBR, 22 + 36, 158, 36, 158, 36,
 	WC_SCEN_LAND_GEN, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
 	_terraform_widgets,
@@ -295,5 +295,7 @@
 		 */
 		w->top = 22;
 		link->left = w->left - link->width;
+
+		SetWindowDirty(link);
 	}
 }
--- a/src/thread.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/thread.h	Fri Aug 03 18:10:15 2007 +0000
@@ -7,10 +7,10 @@
 
 struct OTTDThread;
 
-typedef void* (*OTTDThreadFunc)(void*);
+typedef void * (*OTTDThreadFunc)(void*);
 
-OTTDThread* OTTDCreateThread(OTTDThreadFunc, void*);
-void*       OTTDJoinThread(OTTDThread*);
+OTTDThread *OTTDCreateThread(OTTDThreadFunc, void*);
+void       *OTTDJoinThread(OTTDThread*);
 void        OTTDExitThread();
 
 #endif /* THREAD_H */
--- a/src/tile.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/tile.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -23,11 +23,11 @@
 
 	min = a = TileHeight(tile);
 	b = TileHeight(tile + TileDiffXY(1, 0));
-	if (min >= b) min = b;
+	if (min > b) min = b;
 	c = TileHeight(tile + TileDiffXY(0, 1));
-	if (min >= c) min = c;
+	if (min > c) min = c;
 	d = TileHeight(tile + TileDiffXY(1, 1));
-	if (min >= d) min = d;
+	if (min > d) min = d;
 
 	r = SLOPE_FLAT;
 	if ((a -= min) != 0) r += (--a << 4) + SLOPE_N;
@@ -42,24 +42,25 @@
 
 uint GetTileZ(TileIndex tile)
 {
-	uint h;
-	GetTileSlope(tile, &h);
-	return h;
+	if (TileX(tile) == MapMaxX() || TileY(tile) == MapMaxY()) return 0;
+
+	uint h = TileHeight(tile);
+	h = min(h, TileHeight(tile + TileDiffXY(1, 0)));
+	h = min(h, TileHeight(tile + TileDiffXY(0, 1)));
+	h = min(h, TileHeight(tile + TileDiffXY(1, 1)));
+
+	return h * TILE_HEIGHT;
 }
 
 
 uint GetTileMaxZ(TileIndex t)
 {
-	uint max;
-	uint h;
+	if (TileX(t) == MapMaxX() || TileY(t) == MapMaxY()) return 0;
 
-	h = TileHeight(t);
-	max = h;
-	h = TileHeight(t + TileDiffXY(1, 0));
-	if (h > max) max = h;
-	h = TileHeight(t + TileDiffXY(0, 1));
-	if (h > max) max = h;
-	h = TileHeight(t + TileDiffXY(1, 1));
-	if (h > max) max = h;
-	return max * 8;
+	uint h = TileHeight(t);
+	h = max(h, TileHeight(t + TileDiffXY(1, 0)));
+	h = max(h, TileHeight(t + TileDiffXY(0, 1)));
+	h = max(h, TileHeight(t + TileDiffXY(1, 1)));
+
+	return h * TILE_HEIGHT;
 }
--- a/src/tile.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/tile.h	Fri Aug 03 18:10:15 2007 +0000
@@ -10,54 +10,121 @@
 #include "map.h"
 #include "slope.h"
 
+/** Maximum allowed tile height */
+#define MAX_TILE_HEIGHT 15
+
+/** Maximum allowed snowline height */
+#define MAX_SNOWLINE_HEIGHT (MAX_TILE_HEIGHT - 2)
+
+/**
+ * The different type of a tile.
+ *
+ * Each tile belongs to one type, according whatever is build on it.
+ *
+ * @note A railway with a crossing street is marked as MP_ROAD.
+ */
 enum TileType {
-	MP_CLEAR,
-	MP_RAILWAY,
-	MP_STREET,
-	MP_HOUSE,
-	MP_TREES,
-	MP_STATION,
-	MP_WATER,
-	MP_VOID, // invisible tiles at the SW and SE border
-	MP_INDUSTRY,
-	MP_TUNNELBRIDGE,
-	MP_UNMOVABLE,
+	MP_CLEAR,               ///< A tile without any structures, i.e. grass, rocks, farm fields etc.
+	MP_RAILWAY,             ///< A railway
+	MP_ROAD,                ///< A tile with road (or tram tracks)
+	MP_HOUSE,               ///< A house by a town
+	MP_TREES,               ///< Tile got trees
+	MP_STATION,             ///< A tile of a station
+	MP_WATER,               ///< Water tile
+	MP_VOID,                ///< Invisible tiles at the SW and SE border
+	MP_INDUSTRY,            ///< Part of an industry
+	MP_TUNNELBRIDGE,        ///< Tunnel entry/exit and bridge heads
+	MP_UNMOVABLE,           ///< Contains an object with cannot be removed like transmitters
 };
 
+/**
+ * Additional infos of a tile on a tropic game.
+ *
+ * Each non-water tile in a tropic game is either a rainforest tile or a
+ * desert one.
+ */
 enum TropicZone {
-	TROPICZONE_INVALID    = 0,
-	TROPICZONE_DESERT     = 1,
-	TROPICZONE_RAINFOREST = 2,
+	TROPICZONE_INVALID    = 0,      ///< Invalid tropiczone-type
+	TROPICZONE_DESERT     = 1,      ///< Tile is desert
+	TROPICZONE_RAINFOREST = 2,      ///< Rainforest tile
 };
 
 Slope GetTileSlope(TileIndex tile, uint *h);
 uint GetTileZ(TileIndex tile);
 uint GetTileMaxZ(TileIndex tile);
 
+/**
+ * Returns the height of a tile
+ *
+ * This function returns the height of the northern corner of a tile.
+ * This is saved in the global map-array. It does not take affect by
+ * any slope-data of the tile.
+ *
+ * @param tile The tile to get the height from
+ * @return the height of the tile
+ * @pre tile < MapSize()
+ */
 static inline uint TileHeight(TileIndex tile)
 {
 	assert(tile < MapSize());
 	return GB(_m[tile].type_height, 0, 4);
 }
 
+/**
+ * Sets the height of a tile.
+ *
+ * This function sets the height of the northern corner of a tile.
+ *
+ * @param tile The tile to change the height
+ * @param height The new height value of the tile
+ * @pre tile < MapSize()
+ * @pre heigth <= MAX_TILE_HEIGHT
+ */
 static inline void SetTileHeight(TileIndex tile, uint height)
 {
 	assert(tile < MapSize());
-	assert(height < 16);
+	assert(height <= MAX_TILE_HEIGHT);
 	SB(_m[tile].type_height, 0, 4, height);
 }
 
+/**
+ * Returns the height of a tile in pixels.
+ *
+ * This function returns the height of the northern corner of a tile in pixels.
+ *
+ * @param tile The tile to get the height
+ * @return The height of the tile in pixel
+ */
 static inline uint TilePixelHeight(TileIndex tile)
 {
 	return TileHeight(tile) * TILE_HEIGHT;
 }
 
+/**
+ * Get the tiletype of a given tile.
+ *
+ * @param tile The tile to get the TileType
+ * @return The tiletype of the tile
+ * @pre tile < MapSize()
+ */
 static inline TileType GetTileType(TileIndex tile)
 {
 	assert(tile < MapSize());
 	return (TileType)GB(_m[tile].type_height, 4, 4);
 }
 
+/**
+ * Set the type of a tile
+ *
+ * This functions sets the type of a tile. If the type
+ * MP_VOID is selected the tile must be at the south-west or
+ * south-east edges of the map and vice versa.
+ *
+ * @param tile The tile to save the new type
+ * @param type The type to save
+ * @pre tile < MapSize()
+ * @pre type MP_VOID <=> tile is on the south-east or south-west edge.
+ */
 static inline void SetTileType(TileIndex tile, TileType type)
 {
 	assert(tile < MapSize());
@@ -67,12 +134,32 @@
 	SB(_m[tile].type_height, 4, 4, type);
 }
 
+/**
+ * Checks if a tile is a give tiletype.
+ *
+ * This function checks if a tile got the given tiletype.
+ *
+ * @param tile The tile to check
+ * @param type The type to check agains
+ * @return true If the type matches agains the type of the tile
+ */
 static inline bool IsTileType(TileIndex tile, TileType type)
 {
 	return GetTileType(tile) == type;
 }
 
-
+/**
+ * Returns the owner of a tile
+ *
+ * This function returns the owner of a tile. This cannot used
+ * for tiles which type is one of MP_HOUSE, MP_VOID and MP_INDUSTRY
+ * as no player owned any of these buildings.
+ *
+ * @param tile The tile to check
+ * @return The owner of the tile
+ * @pre tile < MapSize()
+ * @pre The type of the tile must not be MP_HOUSE, MP_VOID and MP_INDUSTRY
+ */
 static inline Owner GetTileOwner(TileIndex tile)
 {
 	assert(tile < MapSize());
@@ -83,6 +170,17 @@
 	return (Owner)_m[tile].m1;
 }
 
+/**
+ * Sets the owner of a tile
+ *
+ * This function sets the owner status of a tile. Note that you cannot
+ * set a owner for tiles of type MP_HOUSE, MP_VOID and MP_INDUSTRY.
+ *
+ * @param tile The tile to change the owner status.
+ * @param owner The new owner.
+ * @pre tile < MapSize()
+ * @pre The type of the tile must not be MP_HOUSE, MP_VOID and MP_INDUSTRY
+ */
 static inline void SetTileOwner(TileIndex tile, Owner owner)
 {
 	assert(tile < MapSize());
@@ -93,6 +191,13 @@
 	_m[tile].m1 = owner;
 }
 
+/**
+ * Checks if a tile belongs to the given owner
+ *
+ * @param tile The tile to check
+ * @param owner The owner to check agains
+ * @return True if a tile belongs the the given owner
+ */
 static inline bool IsTileOwner(TileIndex tile, Owner owner)
 {
 	return GetTileOwner(tile) == owner;
--- a/src/timetable_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/timetable_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -96,6 +96,10 @@
 			SetDParam(2, STR_EMPTY);
 
 			switch (order->type) {
+				case OT_DUMMY:
+					SetDParam(0, STR_INVALID_ORDER);
+					break;
+
 				case OT_GOTO_STATION:
 					SetDParam(0, (order->flags & OF_NON_STOP) ? STR_880C_GO_NON_STOP_TO : STR_8806_GO_TO);
 					SetDParam(1, order->dest);
@@ -137,14 +141,8 @@
 				default: break;
 			}
 
-			byte colour = (i == selected) ? 0xC : 0x10;
-
-			if (order->type != OT_DUMMY) {
-				DrawString(2, y, STR_TIMETABLE_GO_TO, colour);
-			} else {
-				SetDParam(0, STR_INVALID_ORDER);
-				DrawString(2, y, STR_TIMETABLE_GO_TO, colour);
-			}
+			const byte colour = (i == selected) ? 0xC : 0x10;
+			DrawString(2, y, STR_TIMETABLE_GO_TO, colour);
 
 			order_id++;
 
@@ -164,7 +162,7 @@
 				string = STR_TIMETABLE_TRAVEL_FOR;
 			}
 
-			byte colour = (i == selected) ? 0xC : 0x10;
+			const byte colour = (i == selected) ? 0xC : 0x10;
 			DrawString(12, y, string, colour);
 
 			if (final_order) break;
@@ -316,7 +314,7 @@
 };
 
 static const WindowDesc _timetable_desc = {
-	WDP_AUTO, WDP_AUTO, 400, 130,
+	WDP_AUTO, WDP_AUTO, 400, 130, 400, 130,
 	WC_VEHICLE_TIMETABLE, WC_VEHICLE_VIEW,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_timetable_widgets,
--- a/src/town.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/town.h	Fri Aug 03 18:10:15 2007 +0000
@@ -75,7 +75,10 @@
 	uint8 class_count[HOUSE_CLASS_MAX];
 };
 
-struct Town {
+struct Town;
+DECLARE_OLD_POOL(Town, Town, 3, 8000)
+
+struct Town : PoolItem<Town, TownID, &_Town_pool> {
 	TileIndex xy;
 
 	/* Current population of people and amount of houses. */
@@ -139,9 +142,6 @@
 	/* Fund road reconstruction in action? */
 	byte road_build_months;
 
-	/* Index in town array */
-	TownID index;
-
 	/* If this is a larger town, and should grow more quickly. */
 	bool larger_town;
 
@@ -150,6 +150,18 @@
 
 	/* NOSAVE: The number of each type of building in the town. */
 	BuildingCounts building_counts;
+
+	/**
+	 * Creates a new town
+	 */
+	Town(TileIndex tile = 0);
+
+	/** Destroy the town */
+	~Town();
+
+	bool IsValid() const { return this->xy != 0; }
+
+	void QuickFree();
 };
 
 struct HouseSpec {
@@ -270,8 +282,6 @@
 
 VARDEF const Town** _town_sort;
 
-DECLARE_OLD_POOL(Town, Town, 3, 8000)
-
 static inline HouseSpec *GetHouseSpecs(HouseID house_id)
 {
 	assert(house_id < HOUSE_MAX);
@@ -279,23 +289,13 @@
 }
 
 /**
- * Check if a Town really exists.
- * @param town to inquiry
- * @return true if it exists
- */
-static inline bool IsValidTown(const Town* town)
-{
-	return town->xy != 0;
-}
-
-/**
  * Check if a TownID is valid.
  * @param index to inquiry in the pool of town
  * @return true if it exists
  */
 static inline bool IsValidTownID(TownID index)
 {
-	return index < GetTownPoolSize() && IsValidTown(GetTown(index));
+	return index < GetTownPoolSize() && GetTown(index)->IsValid();
 }
 
 VARDEF uint _total_towns;
@@ -337,17 +337,9 @@
 	return GetTown(index);
 }
 
-void DestroyTown(Town *t);
-
-static inline void DeleteTown(Town *t)
-{
-	DestroyTown(t);
-	t->xy = 0;
-}
-
 Town* CalcClosestTownFromTile(TileIndex tile, uint threshold);
 
-#define FOR_ALL_TOWNS_FROM(t, start) for (t = GetTown(start); t != NULL; t = (t->index + 1U < GetTownPoolSize()) ? GetTown(t->index + 1U) : NULL) if (IsValidTown(t))
+#define FOR_ALL_TOWNS_FROM(t, start) for (t = GetTown(start); t != NULL; t = (t->index + 1U < GetTownPoolSize()) ? GetTown(t->index + 1U) : NULL) if (t->IsValid())
 #define FOR_ALL_TOWNS(t) FOR_ALL_TOWNS_FROM(t, 0)
 
 VARDEF bool _town_sort_dirty;
--- a/src/town_cmd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/town_cmd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -40,52 +40,40 @@
 #include "newgrf_house.h"
 #include "newgrf_commons.h"
 #include "newgrf_townname.h"
-
-/**
- * Called if a new block is added to the town-pool
- */
-static void TownPoolNewBlock(uint start_item)
-{
-	Town *t;
-
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (t = GetTown(start_item); t != NULL; t = (t->index + 1U < GetTownPoolSize()) ? GetTown(t->index + 1U) : NULL) t->index = start_item++;
-}
+#include "misc/autoptr.hpp"
 
 /* Initialize the town-pool */
-DEFINE_OLD_POOL(Town, Town, TownPoolNewBlock, NULL)
-
-/**
- * Removes a specific town as well as all industries
- * under its "juridiction"
- * @param t Town to remove
- */
-void DestroyTown(Town *t)
+DEFINE_OLD_POOL_GENERIC(Town, Town)
+
+Town::Town(TileIndex tile)
+{
+	this->xy = tile;
+}
+
+Town::~Town()
 {
 	Industry *i;
-	TileIndex tile;
 
 	/* Delete town authority window
 	 * and remove from list of sorted towns */
-	DeleteWindowById(WC_TOWN_VIEW, t->index);
+	DeleteWindowById(WC_TOWN_VIEW, this->index);
 	_town_sort_dirty = true;
 	_total_towns--;
 
 	/* Delete all industries belonging to the town */
-	FOR_ALL_INDUSTRIES(i) if (i->town == t) DeleteIndustry(i);
+	FOR_ALL_INDUSTRIES(i) if (i->town == this) delete i;
 
 	/* Go through all tiles and delete those belonging to the town */
-	for (tile = 0; tile < MapSize(); ++tile) {
+	for (TileIndex tile = 0; tile < MapSize(); ++tile) {
 		switch (GetTileType(tile)) {
 			case MP_HOUSE:
-				if (GetTownByTile(tile) == t) DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
+				if (GetTownByTile(tile) == this) DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
 				break;
 
-			case MP_STREET:
+			case MP_ROAD:
 			case MP_TUNNELBRIDGE:
 				if (IsTileOwner(tile, OWNER_TOWN) &&
-						ClosestTownFromTile(tile, (uint)-1) == t)
+						ClosestTownFromTile(tile, (uint)-1) == this)
 					DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
 				break;
 
@@ -94,10 +82,17 @@
 		}
 	}
 
-	DeleteName(t->townnametype);
-	DeleteSubsidyWithTown(t->index);
+	DeleteSubsidyWithTown(this->index);
 
 	MarkWholeScreenDirty();
+
+	this->QuickFree();
+	this->xy = 0;
+}
+
+void Town::QuickFree()
+{
+	DeleteName(this->townnametype);
 }
 
 // Local
@@ -154,7 +149,7 @@
 	/* Retrieve pointer to the draw town tile struct */
 	dcts = &_town_draw_tile_data[house_id << 4 | OriginalTileRandomiser(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
 
-	if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, ti->tileh);
+	if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
 
 	image = dcts->ground.sprite;
 	pal   = dcts->ground.pal;
@@ -163,20 +158,14 @@
 	/* Add a house on top of the ground? */
 	image = dcts->building.sprite;
 	if (image != 0) {
-		if (HASBIT(_transparent_opt, TO_HOUSES)) {
-			SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
-			pal = PALETTE_TO_TRANSPARENT;
-		} else {
-			pal = dcts->building.pal;
-		}
-
-		AddSortableSpriteToDraw(image, pal,
+		AddSortableSpriteToDraw(image, dcts->building.pal,
 			ti->x + dcts->subtile_x,
 			ti->y + dcts->subtile_y,
 			dcts->width + 1,
 			dcts->height + 1,
 			dcts->dz,
-			ti->z
+			ti->z,
+			HASBIT(_transparent_opt, TO_HOUSES)
 		);
 
 		if (HASBIT(_transparent_opt, TO_HOUSES)) return;
@@ -194,9 +183,9 @@
 	return GetTileMaxZ(tile);
 }
 
-static Slope GetSlopeTileh_Town(TileIndex tile, Slope tileh)
+static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
 {
-	return SLOPE_FLAT;
+	return FlatteningFoundation(tileh);
 }
 
 /**
@@ -1157,7 +1146,7 @@
 		do block = Random() & 3; while (!HASBIT(mask, block));
 		tile += ToTileIndexDiff(_roadblock_tileadd[block]);
 
-		if (IsTileType(tile, MP_STREET)) {
+		if (IsTileType(tile, MP_ROAD)) {
 			/* Don't allow building over roads of other cities */
 			if (IsTileOwner(tile, OWNER_TOWN) && GetTownByTile(tile) != t) {
 				_grow_town_result = -1;
@@ -1365,10 +1354,6 @@
 	extern int _nb_orig_names;
 	int x, i;
 
-	/* clear the town struct */
-	i = t->index;
-	memset(t, 0, sizeof(Town));
-	t->index = i;
 	_total_towns++;
 
 	t->xy = tile;
@@ -1452,30 +1437,6 @@
 	UpdateTownMaxPass(t);
 }
 
-static Town *AllocateTown()
-{
-	Town *t;
-
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (t = GetTown(0); t != NULL; t = (t->index + 1U < GetTownPoolSize()) ? GetTown(t->index + 1U) : NULL) {
-		if (!IsValidTown(t)) {
-			TownID index = t->index;
-
-			memset(t, 0, sizeof(Town));
-			t->index = index;
-
-			return t;
-		}
-	}
-
-	/* Check if we can add a block to the pool */
-	if (AddBlockToPool(&_Town_pool))
-		return AllocateTown();
-
-	return NULL;
-}
-
 /** Create a new town.
  * This obviously only works in the scenario editor. Function not removed
  * as it might be possible in the future to fund your own town :)
@@ -1486,7 +1447,6 @@
  */
 CommandCost CmdBuildTown(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 {
-	Town *t;
 	uint32 townnameparts;
 
 	/* Only in the scenario editor */
@@ -1513,14 +1473,16 @@
 		return_cmd_error(STR_023A_TOO_MANY_TOWNS);
 
 	/* Allocate town struct */
-	t = AllocateTown();
+	Town *t = new Town(tile);
 	if (t == NULL) return_cmd_error(STR_023A_TOO_MANY_TOWNS);
+	AutoPtrT<Town> t_auto_delete = t;
 
 	/* Create the town */
 	if (flags & DC_EXEC) {
 		_generating_world = true;
 		DoCreateTown(t, tile, townnameparts, (TownSizeMode)p2, p1);
 		_generating_world = false;
+		t_auto_delete.Detach();
 	}
 	return CommandCost();
 }
@@ -1546,7 +1508,7 @@
 		if (!CreateTownName(&townnameparts)) break;
 
 		/* Allocate a town struct */
-		t = AllocateTown();
+		t = new Town(tile);
 		if (t == NULL) break;
 
 		DoCreateTown(t, tile, townnameparts, mode, size);
@@ -2239,7 +2201,7 @@
 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
 {
 	if (IsTileType(tile, MP_HOUSE) || (
-				IsTileType(tile, MP_STREET) &&
+				IsTileType(tile, MP_ROAD) &&
 				GetRoadOwner(tile, ROADTYPE_ROAD) == OWNER_TOWN
 			)) {
 		return GetTownByTile(tile);
@@ -2356,7 +2318,7 @@
 	ChangeTileOwner_Town,    /* change_tile_owner_clear */
 	NULL,                    /* get_produced_cargo_proc */
 	NULL,                    /* vehicle_enter_tile_proc */
-	GetSlopeTileh_Town,      /* get_slope_tileh_proc */
+	GetFoundation_Town,      /* get_foundation_proc */
 };
 
 
@@ -2482,12 +2444,7 @@
 	_total_towns = 0;
 
 	while ((index = SlIterateArray()) != -1) {
-		Town *t;
-
-		if (!AddBlockIfNeeded(&_Town_pool, index))
-			error("Towns: failed loading savegame: too many towns");
-
-		t = GetTown(index);
+		Town *t = new (index) Town();
 		SlObject(t, _town_desc);
 
 		_total_towns++;
--- a/src/town_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/town_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -214,7 +214,7 @@
 }
 
 static const WindowDesc _town_authority_desc = {
-	WDP_AUTO, WDP_AUTO, 317, 222,
+	WDP_AUTO, WDP_AUTO, 317, 222, 317, 222,
 	WC_TOWN_AUTHORITY, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
 	_town_authority_widgets,
@@ -278,7 +278,7 @@
 				break;
 
 			case 10: /* delete town */
-				DeleteTown(t);
+				delete t;
 				break;
 		}
 		break;
@@ -308,7 +308,7 @@
 };
 
 static const WindowDesc _town_view_desc = {
-	WDP_AUTO, WDP_AUTO, 260, 150,
+	WDP_AUTO, WDP_AUTO, 260, 150, 260, 150,
 	WC_TOWN_VIEW, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON,
 	_town_view_widgets,
@@ -331,7 +331,7 @@
 };
 
 static const WindowDesc _town_view_scen_desc = {
-	WDP_AUTO, WDP_AUTO, 260, 150,
+	WDP_AUTO, WDP_AUTO, 260, 150, 260, 150,
 	WC_TOWN_VIEW, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON,
 	_town_view_scen_widgets,
@@ -508,7 +508,7 @@
 }
 
 static const WindowDesc _town_directory_desc = {
-	WDP_AUTO, WDP_AUTO, 208, 202,
+	WDP_AUTO, WDP_AUTO, 208, 202, 208, 202,
 	WC_TOWN_DIRECTORY, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_town_directory_widgets,
--- a/src/town_map.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/town_map.h	Fri Aug 03 18:10:15 2007 +0000
@@ -11,25 +11,25 @@
 /**
  * Get the index of which town this house/street is attached to.
  * @param t the tile
- * @pre IsTileType(t, MP_HOUSE) or IsTileType(t, MP_STREET)
+ * @pre IsTileType(t, MP_HOUSE) or IsTileType(t, MP_ROAD)
  * @return TownID
  */
 static inline TownID GetTownIndex(TileIndex t)
 {
-	assert(IsTileType(t, MP_HOUSE) || IsTileType(t, MP_STREET)); // XXX incomplete
+	assert(IsTileType(t, MP_HOUSE) || IsTileType(t, MP_ROAD)); // XXX incomplete
 	return _m[t].m2;
 }
 
 /**
  * Set the town index for a road or house tile.
  * @param t the tile
- * @pre IsTileType(t, MP_HOUSE) or IsTileType(t, MP_STREET)
+ * @pre IsTileType(t, MP_HOUSE) or IsTileType(t, MP_ROAD)
  * @param index the index of the town
- * @pre IsTileType(t, MP_STREET) || IsTileType(t, MP_HOUSE)
+ * @pre IsTileType(t, MP_ROAD) || IsTileType(t, MP_HOUSE)
  */
 static inline void SetTownIndex(TileIndex t, TownID index)
 {
-	assert(IsTileType(t, MP_HOUSE) || IsTileType(t, MP_STREET));
+	assert(IsTileType(t, MP_HOUSE) || IsTileType(t, MP_ROAD));
 	_m[t].m2 = index;
 }
 
@@ -38,7 +38,7 @@
  * @param t the tile to get the town of
  * @return the town
  */
-static inline Town* GetTownByTile(TileIndex t)
+static inline Town *GetTownByTile(TileIndex t)
 {
 	return GetTown(GetTownIndex(t));
 }
--- a/src/train_cmd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/train_cmd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -2760,7 +2760,16 @@
 	tcc.num = 0;
 
 	/* find colliding vehicles */
-	VehicleFromPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
+	if (v->u.rail.track == TRACK_BIT_WORMHOLE) {
+		VehicleFromPos(v->tile, &tcc, FindTrainCollideEnum);
+		if (IsBridgeTile(v->tile)) {
+			VehicleFromPos(GetOtherBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
+		} else {
+			VehicleFromPos(GetOtherTunnelEnd(v->tile), &tcc, FindTrainCollideEnum);
+		}
+	} else {
+		VehicleFromPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
+	}
 
 	/* any dead -> no crash */
 	if (tcc.num == 0) return;
@@ -3138,7 +3147,7 @@
 
 		if (!(v->vehstatus & VS_HIDDEN)) {
 			Vehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE);
-			if (u != NULL) u->u.special.unk0 = v->breakdown_delay * 2;
+			if (u != NULL) u->u.special.animation_state = v->breakdown_delay * 2;
 		}
 	}
 
--- a/src/train_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/train_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -69,7 +69,8 @@
  * @param len Length measured in 1/8ths of a standard wagon.
  * @return Number of pixels across.
  */
-int WagonLengthToPixels(int len) {
+int WagonLengthToPixels(int len)
+{
 	return (len * _traininfo_vehicle_width) / 8;
 }
 
@@ -308,7 +309,7 @@
 }
 
 static const WindowDesc _train_view_desc = {
-	WDP_AUTO, WDP_AUTO, 250, 134,
+	WDP_AUTO, WDP_AUTO, 250, 134, 250, 134,
 	WC_VEHICLE_VIEW, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_train_view_widgets,
@@ -591,7 +592,7 @@
 
 
 static const WindowDesc _train_details_desc = {
-	WDP_AUTO, WDP_AUTO, 370, 164,
+	WDP_AUTO, WDP_AUTO, 370, 164, 370, 164,
 	WC_VEHICLE_DETAILS,WC_VEHICLE_VIEW,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
 	_train_details_widgets,
--- a/src/transparency_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/transparency_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -78,7 +78,7 @@
 };
 
 static const WindowDesc _transparency_desc = {
-	WDP_ALIGN_TBR, 58+36, 197, 36,
+	WDP_ALIGN_TBR, 58+36, 197, 36, 197, 36,
 	WC_TRANSPARENCY_TOOLBAR, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
 	_transparency_widgets,
--- a/src/tree_cmd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/tree_cmd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -374,13 +374,8 @@
 		i = GetTreeCount(ti->tile) + 1;
 		do {
 			SpriteID image = s[0].sprite + (--i == 0 ? GetTreeGrowth(ti->tile) : 3);
-			SpriteID pal;
-			if (HASBIT(_transparent_opt, TO_TREES)) {
-				SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
-				pal = PALETTE_TO_TRANSPARENT;
-			} else {
-				pal = s[0].pal;
-			}
+			SpriteID pal = s[0].pal;
+
 			te[i].image = image;
 			te[i].pal   = pal;
 			te[i].x = d->x;
@@ -404,7 +399,7 @@
 
 			if (tep == NULL) break;
 
-			AddSortableSpriteToDraw(tep->image, tep->pal, ti->x + tep->x, ti->y + tep->y, 5, 5, 0x10, z);
+			AddSortableSpriteToDraw(tep->image, tep->pal, ti->x + tep->x, ti->y + tep->y, 5, 5, 0x10, z, HASBIT(_transparent_opt, TO_TREES));
 			tep->image = 0;
 		}
 	}
@@ -421,9 +416,9 @@
 	return z + GetPartialZ(x & 0xF, y & 0xF, tileh);
 }
 
-static Slope GetSlopeTileh_Trees(TileIndex tile, Slope tileh)
+static Foundation GetFoundation_Trees(TileIndex tile, Slope tileh)
 {
-	return tileh;
+	return FOUNDATION_NONE;
 }
 
 static CommandCost ClearTile_Trees(TileIndex tile, byte flags)
@@ -560,7 +555,7 @@
 					case 2: { /* add a neighbouring tree */
 						TreeType treetype = GetTreeType(tile);
 
-						tile += TileOffsByDir(Random() & 7);
+						tile += TileOffsByDir((Direction)(Random() & 7));
 
 						if (!IsTileType(tile, MP_CLEAR) || IsBridgeAbove(tile)) return;
 
@@ -675,5 +670,5 @@
 	ChangeTileOwner_Trees,    /* change_tile_owner_clear */
 	NULL,                     /* get_produced_cargo_proc */
 	NULL,                     /* vehicle_enter_tile_proc */
-	GetSlopeTileh_Trees,      /* get_slope_tileh_proc */
+	GetFoundation_Trees,      /* get_foundation_proc */
 };
--- a/src/tunnel_map.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/tunnel_map.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -64,8 +64,6 @@
 bool IsTunnelInWay(TileIndex tile, uint z)
 {
 	return
-		IsTunnelInWayDir(tile, z, DIAGDIR_NE) ||
-		IsTunnelInWayDir(tile, z, DIAGDIR_SE) ||
-		IsTunnelInWayDir(tile, z, DIAGDIR_SW) ||
-		IsTunnelInWayDir(tile, z, DIAGDIR_NW);
+		IsTunnelInWayDir(tile, z, (TileX(tile) > (MapMaxX() / 2)) ? DIAGDIR_NE : DIAGDIR_SW) ||
+		IsTunnelInWayDir(tile, z, (TileY(tile) > (MapMaxY() / 2)) ? DIAGDIR_NW : DIAGDIR_SE);
 }
--- a/src/tunnelbridge_cmd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/tunnelbridge_cmd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -389,7 +389,7 @@
 				if (!IsPlainRailTile(tile)) goto not_valid_below;
 				break;
 
-			case MP_STREET:
+			case MP_ROAD:
 				if (GetRoadTileType(tile) == ROAD_TILE_DEPOT) goto not_valid_below;
 				break;
 
@@ -505,6 +505,8 @@
 	int tiles_coef = 3;
 	/** Number of tiles from start of tunnel */
 	int tiles = 0;
+	/** Number of tiles at which the cost increase coefficient per tile is halved */
+	int tiles_bump = 25;
 
 	for (;;) {
 		end_tile += delta;
@@ -517,7 +519,10 @@
 		}
 
 		tiles++;
-		if (tiles == 25 || tiles == 50 || tiles == 100 || tiles == 200 || tiles == 400 || tiles == 800) tiles_coef++;
+		if (tiles == tiles_bump) {
+			tiles_coef++;
+			tiles_bump *= 2;
+		}
 
 		cost.AddCost(_price.build_tunnel);
 		cost.AddCost(cost.GetCost() >> tiles_coef); // add a multiplier for longer tunnels
@@ -826,7 +831,6 @@
 		int back_height, front_height;
 		int i = z;
 		const byte *p;
-		SpriteID pal;
 
 		static const byte _tileh_bits[4][8] = {
 			{ 2, 1, 8, 4,  16,  2, 0, 9 },
@@ -835,13 +839,6 @@
 			{ 2, 4, 8, 1,   2, 16, 9, 0 }
 		};
 
-		if (HASBIT(_transparent_opt, TO_BRIDGES)) {
-			SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
-			pal = PALETTE_TO_TRANSPARENT;
-		} else {
-			pal = psid->pal;
-		}
-
 		p = _tileh_bits[(image & 1) * 2 + (axis == AXIS_X ? 0 : 1)];
 		front_height = ti->z + (ti->tileh & p[0] ? TILE_HEIGHT : 0);
 		back_height  = ti->z + (ti->tileh & p[1] ? TILE_HEIGHT : 0);
@@ -856,36 +853,21 @@
 			 * sprites is at the top
 			 */
 			if (z >= front_height) { // front facing pillar
-				AddSortableSpriteToDraw(image, pal, x, y, p[4], p[5], 1, z);
+				AddSortableSpriteToDraw(image, psid->pal, x, y, p[4], p[5], 1, z, HASBIT(_transparent_opt, TO_BRIDGES));
 			}
 
 			if (drawfarpillar && z >= back_height && z < i - TILE_HEIGHT) { // back facing pillar
-				AddSortableSpriteToDraw(image, pal, x - p[6], y - p[7], p[4], p[5], 1, z);
+				AddSortableSpriteToDraw(image, psid->pal, x - p[6], y - p[7], p[4], p[5], 1, z, HASBIT(_transparent_opt, TO_BRIDGES));
 			}
 		}
 	}
 }
 
-uint GetBridgeFoundation(Slope tileh, Axis axis)
+Foundation GetBridgeFoundation(Slope tileh, Axis axis)
 {
-	uint i;
-
-	if (HASBIT(BRIDGE_FULL_LEVELED_FOUNDATION, tileh)) return tileh;
-
-	/* inclined sloped building */
-	switch (tileh) {
-		case SLOPE_W:
-		case SLOPE_STEEP_W: i = 0; break;
-		case SLOPE_S:
-		case SLOPE_STEEP_S: i = 2; break;
-		case SLOPE_E:
-		case SLOPE_STEEP_E: i = 4; break;
-		case SLOPE_N:
-		case SLOPE_STEEP_N: i = 6; break;
-		default: return 0;
-	}
-	if (axis != AXIS_X) ++i;
-	return i + 15;
+	if (HASBIT(BRIDGE_NO_FOUNDATION, tileh)) return FOUNDATION_NONE;
+	if (HASBIT(BRIDGE_FULL_LEVELED_FOUNDATION, tileh)) return FlatteningFoundation(tileh);
+	return InclinedFoundation(axis);
 }
 
 /**
@@ -905,20 +887,11 @@
 	static const uint size_x[6] = { 11, 16, 16, 16, 16, 16 };
 	static const uint size_y[6] = { 16, 11, 16, 16, 16, 16 };
 
-	AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + tram_offsets[overlay][offset], PAL_NONE, x, y, size_x[offset], size_y[offset], offset >= 2 ? 1 : 0, z);
+	AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + tram_offsets[overlay][offset], PAL_NONE, x, y, size_x[offset], size_y[offset], offset >= 2 ? 1 : 0, z, HASBIT(_transparent_opt, TO_BRIDGES));
 
-	SpriteID front = SPR_TRAMWAY_BASE + front_offsets[offset];
-	SpriteID back  = SPR_TRAMWAY_BASE + back_offsets[offset];
-	SpriteID pal   = PAL_NONE;
-	if (HASBIT(_transparent_opt, TO_BUILDINGS)) {
-		SETBIT(front, PALETTE_MODIFIER_TRANSPARENT);
-		SETBIT(back,  PALETTE_MODIFIER_TRANSPARENT);
-		pal = PALETTE_TO_TRANSPARENT;
-	}
-
-	AddSortableSpriteToDraw(back,  pal, x, y, size_x[offset], size_y[offset], 0, z);
+	AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + back_offsets[offset],  PAL_NONE, x, y, size_x[offset], size_y[offset], 0, z, HASBIT(_transparent_opt, TO_BUILDINGS));
 	/* For sloped sprites the bounding box needs to be higher, as the pylons stop on a higher point */
-	AddSortableSpriteToDraw(front, pal, x, y, size_x[offset], size_y[offset], offset >= 2 ? 0x30 : 0x10, z);
+	AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + front_offsets[offset], PAL_NONE, x, y, size_x[offset], size_y[offset], offset >= 2 ? 0x30 : 0x10, z, HASBIT(_transparent_opt, TO_BUILDINGS));
 }
 
 /**
@@ -937,7 +910,6 @@
 static void DrawTile_TunnelBridge(TileInfo *ti)
 {
 	SpriteID image;
-	SpriteID pal;
 
 	if (IsTunnel(ti->tile)) {
 		if (GetTunnelTransportType(ti->tile) == TRANSPORT_RAIL) {
@@ -981,10 +953,7 @@
 		/* as the lower 3 bits are used for other stuff, make sure they are clear */
 		assert( (base_offset & 0x07) == 0x00);
 
-		if (!HASBIT(BRIDGE_NO_FOUNDATION, ti->tileh)) {
-			int f = GetBridgeFoundation(ti->tileh, DiagDirToAxis(GetBridgeRampDirection(ti->tile)));
-			if (f != 0) DrawFoundation(ti, f);
-		}
+		DrawFoundation(ti, GetBridgeFoundation(ti->tileh, DiagDirToAxis(GetBridgeRampDirection(ti->tile))));
 
 		/* HACK Wizardry to convert the bridge ramp direction into a sprite offset */
 		base_offset += (6 - GetBridgeRampDirection(ti->tile)) % 4;
@@ -1000,21 +969,13 @@
 			DrawGroundSprite(SPR_FLAT_SNOWY_TILE + _tileh_to_sprite[ti->tileh], PAL_NONE);
 		}
 
-		image = psid->sprite;
-
 		/* draw ramp */
-		if (HASBIT(_transparent_opt, TO_BRIDGES)) {
-			SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
-			pal = PALETTE_TO_TRANSPARENT;
-		} else {
-			pal = psid->pal;
-		}
 
 		/* HACK set the height of the BB of a sloped ramp to 1 so a vehicle on
 		 * it doesn't disappear behind it
 		 */
 		AddSortableSpriteToDraw(
-			image, pal, ti->x, ti->y, 16, 16, ti->tileh == SLOPE_FLAT ? 0 : 8, ti->z
+			psid->sprite, psid->pal, ti->x, ti->y, 16, 16, ti->tileh == SLOPE_FLAT ? 0 : 8, ti->z, HASBIT(_transparent_opt, TO_BRIDGES)
 		);
 
 		if (GetBridgeTransportType(ti->tile) == TRANSPORT_ROAD) {
@@ -1077,8 +1038,6 @@
 void DrawBridgeMiddle(const TileInfo* ti)
 {
 	const PalSpriteID* psid;
-	SpriteID image;
-	SpriteID pal;
 	uint base_offset;
 	TileIndex rampnorth;
 	TileIndex rampsouth;
@@ -1115,28 +1074,13 @@
 	uint bridge_z = GetBridgeHeight(rampsouth);
 	z = bridge_z - 3;
 
-	image = psid->sprite;
-	if (HASBIT(_transparent_opt, TO_BRIDGES)) {
-		SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
-		pal = PALETTE_TO_TRANSPARENT;
+	if (axis == AXIS_X) {
+		AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 11, 1, z, HASBIT(_transparent_opt, TO_BRIDGES));
 	} else {
-		pal = psid->pal;
-	}
-
-	if (axis == AXIS_X) {
-		AddSortableSpriteToDraw(image, pal, x, y, 16, 11, 1, z);
-	} else {
-		AddSortableSpriteToDraw(image, pal, x, y, 11, 16, 1, z);
+		AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 11, 16, 1, z, HASBIT(_transparent_opt, TO_BRIDGES));
 	}
 
 	psid++;
-	image = psid->sprite;
-	if (HASBIT(_transparent_opt, TO_BRIDGES)) {
-		SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
-		pal = PALETTE_TO_TRANSPARENT;
-	} else {
-		pal = psid->pal;
-	}
 
 	if (GetBridgeTransportType(rampsouth) == TRANSPORT_ROAD) {
 		RoadTypes rts = GetRoadTypes(rampsouth);
@@ -1151,22 +1095,21 @@
 	/* draw roof, the component of the bridge which is logically between the vehicle and the camera */
 	if (axis == AXIS_X) {
 		y += 12;
-		if (image & SPRITE_MASK) AddSortableSpriteToDraw(image, pal, x, y, 16, 1, 0x28, z);
+		if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 1, 0x28, z, HASBIT(_transparent_opt, TO_BRIDGES));
 	} else {
 		x += 12;
-		if (image & SPRITE_MASK) AddSortableSpriteToDraw(image, pal, x, y, 1, 16, 0x28, z);
+		if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 1, 16, 0x28, z, HASBIT(_transparent_opt, TO_BRIDGES));
 	}
 
 	psid++;
 	if (ti->z + 5 == z) {
 		/* draw poles below for small bridges */
 		if (psid->sprite != 0) {
-			image = psid->sprite;
+			SpriteID image = psid->sprite;
+			SpriteID pal   = psid->pal;
 			if (HASBIT(_transparent_opt, TO_BRIDGES)) {
 				SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
 				pal = PALETTE_TO_TRANSPARENT;
-			} else {
-				pal = psid->pal;
 			}
 
 			DrawGroundSpriteAt(image, pal, x, y, z);
@@ -1195,14 +1138,14 @@
 		DiagDirection dir = GetBridgeRampDirection(tile);
 		uint pos = (DiagDirToAxis(dir) == AXIS_X ? y : x);
 
+		z += ApplyFoundationToSlope(GetBridgeFoundation(tileh, DiagDirToAxis(dir)), &tileh);
+
 		/* On the bridge ramp? */
 		if (5 <= pos && pos <= 10) {
 			uint delta;
 
-			if (IsSteepSlope(tileh)) return z + TILE_HEIGHT * 2;
 			if (HASBIT(BRIDGE_HORZ_RAMP, tileh)) return z + TILE_HEIGHT;
 
-			if (HASBIT(BRIDGE_FULL_LEVELED_FOUNDATION, tileh)) z += TILE_HEIGHT;
 			switch (dir) {
 				default: NOT_REACHED();
 				case DIAGDIR_NE: delta = (TILE_SIZE - 1 - x) / 2; break;
@@ -1211,38 +1154,15 @@
 				case DIAGDIR_NW: delta = (TILE_SIZE - 1 - y) / 2; break;
 			}
 			return z + 1 + delta;
-		} else {
-			uint f = GetBridgeFoundation(tileh, DiagDirToAxis(dir));
-
-			if (f != 0) {
-				if (IsSteepSlope(tileh)) {
-					z += TILE_HEIGHT;
-				} else if (f < 15) {
-					return z + TILE_HEIGHT;
-				}
-				tileh = (Slope)_inclined_tileh[f - 15];
-			}
 		}
 	}
 
 	return z + GetPartialZ(x, y, tileh);
 }
 
-static Slope GetSlopeTileh_TunnelBridge(TileIndex tile, Slope tileh)
+static Foundation GetFoundation_TunnelBridge(TileIndex tile, Slope tileh)
 {
-	if (IsTunnel(tile)) {
-		return tileh;
-	} else {
-		if (HASBIT(BRIDGE_NO_FOUNDATION, tileh)) {
-			return tileh;
-		} else {
-			uint f = GetBridgeFoundation(tileh, DiagDirToAxis(GetBridgeRampDirection(tile)));
-
-			if (f == 0) return tileh;
-			if (f < 15) return SLOPE_FLAT;
-			return (Slope)_inclined_tileh[f - 15];
-		}
-	}
+	return IsTunnel(tile) ? FOUNDATION_NONE : GetBridgeFoundation(tileh, DiagDirToAxis(GetBridgeRampDirection(tile)));
 }
 
 
@@ -1514,5 +1434,5 @@
 	ChangeTileOwner_TunnelBridge,    /* change_tile_owner_clear */
 	NULL,                            /* get_produced_cargo_proc */
 	VehicleEnter_TunnelBridge,       /* vehicle_enter_tile_proc */
-	GetSlopeTileh_TunnelBridge,      /* get_slope_tileh_proc */
+	GetFoundation_TunnelBridge,      /* get_foundation_proc */
 };
--- a/src/unmovable_cmd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/unmovable_cmd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -112,30 +112,21 @@
 
 static void DrawTile_Unmovable(TileInfo *ti)
 {
-	SpriteID image;
-	SpriteID pal;
 
 	switch (GetUnmovableType(ti->tile)) {
 		case UNMOVABLE_TRANSMITTER:
 		case UNMOVABLE_LIGHTHOUSE: {
 			const DrawTileUnmovableStruct* dtus;
 
-			if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, ti->tileh);
+			if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
 			DrawClearLandTile(ti, 2);
 
 			dtus = &_draw_tile_unmovable_data[GetUnmovableType(ti->tile)];
 
-			image = dtus->image;
-			if (HASBIT(_transparent_opt, TO_STRUCTURES)) {
-				SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
-				pal = PALETTE_TO_TRANSPARENT;
-			} else {
-				pal = PAL_NONE;
-			}
-
 			AddSortableSpriteToDraw(
-				image, pal, ti->x | dtus->subcoord_x, ti->y | dtus->subcoord_y,
-				dtus->width, dtus->height, dtus->z_size, ti->z
+				dtus->image, PAL_NONE, ti->x | dtus->subcoord_x, ti->y | dtus->subcoord_y,
+				dtus->width, dtus->height, dtus->z_size, ti->z,
+				HASBIT(_transparent_opt, TO_STRUCTURES)
 			);
 			break;
 		}
@@ -143,23 +134,14 @@
 		case UNMOVABLE_STATUE:
 			DrawGroundSprite(SPR_CONCRETE_GROUND, PAL_NONE);
 
-			image = SPR_STATUE_COMPANY;
-			if (HASBIT(_transparent_opt, TO_STRUCTURES)) {
-				SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
-				pal = PALETTE_TO_TRANSPARENT;
-			} else {
-				pal = PLAYER_SPRITE_COLOR(GetTileOwner(ti->tile));
-			}
-			AddSortableSpriteToDraw(image, pal, ti->x, ti->y, 16, 16, 25, ti->z);
+			AddSortableSpriteToDraw(SPR_STATUE_COMPANY, PLAYER_SPRITE_COLOR(GetTileOwner(ti->tile)), ti->x, ti->y, 16, 16, 25, ti->z, HASBIT(_transparent_opt, TO_STRUCTURES));
 			break;
 
 		case UNMOVABLE_OWNED_LAND:
 			DrawClearLandTile(ti, 0);
 
-			image = SPR_BOUGHT_LAND;
-			pal = PLAYER_SPRITE_COLOR(GetTileOwner(ti->tile));
 			AddSortableSpriteToDraw(
-				image, pal,
+				SPR_BOUGHT_LAND, PLAYER_SPRITE_COLOR(GetTileOwner(ti->tile)),
 				ti->x + TILE_SIZE / 2, ti->y + TILE_SIZE / 2, 1, 1, 10, GetSlopeZ(ti->x + TILE_SIZE / 2, ti->y + TILE_SIZE / 2)
 			);
 			DrawBridgeMiddle(ti);
@@ -171,7 +153,7 @@
 			SpriteID palette;
 
 			assert(IsCompanyHQ(ti->tile));
-			if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, ti->tileh);
+			if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
 
 			palette = PLAYER_SPRITE_COLOR(GetTileOwner(ti->tile));
 
@@ -179,18 +161,12 @@
 			DrawGroundSprite(t->ground_sprite, palette);
 
 			foreach_draw_tile_seq(dtss, t->seq) {
-				image = dtss->image;
-				if (HASBIT(_transparent_opt, TO_STRUCTURES)) {
-					SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
-					pal = PALETTE_TO_TRANSPARENT;
-				} else {
-					pal = palette;
-				}
 				AddSortableSpriteToDraw(
-					image, pal,
+					dtss->image, palette,
 					ti->x + dtss->delta_x, ti->y + dtss->delta_y,
 					dtss->size_x, dtss->size_y,
-					dtss->size_z, ti->z + dtss->delta_z
+					dtss->size_z, ti->z + dtss->delta_z,
+					HASBIT(_transparent_opt, TO_STRUCTURES)
 				);
 			}
 			break;
@@ -210,9 +186,9 @@
 	}
 }
 
-static Slope GetSlopeTileh_Unmovable(TileIndex tile, Slope tileh)
+static Foundation GetFoundation_Unmovable(TileIndex tile, Slope tileh)
 {
-	return IsOwnedLand(tile) ? tileh : SLOPE_FLAT;
+	return IsOwnedLand(tile) ? FOUNDATION_NONE : FlatteningFoundation(tileh);
 }
 
 static CommandCost ClearTile_Unmovable(TileIndex tile, byte flags)
@@ -435,5 +411,5 @@
 	ChangeTileOwner_Unmovable,      /* change_tile_owner_clear */
 	NULL,                           /* get_produced_cargo_proc */
 	NULL,                           /* vehicle_enter_tile_proc */
-	GetSlopeTileh_Unmovable,        /* get_slope_tileh_proc */
+	GetFoundation_Unmovable,        /* get_foundation_proc */
 };
--- a/src/variables.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/variables.h	Fri Aug 03 18:10:15 2007 +0000
@@ -330,7 +330,6 @@
 
 /* landscape.cpp */
 extern const byte _tileh_to_sprite[32];
-extern const Slope _inclined_tileh[16];
 
 extern const TileTypeProcs * const _tile_type_procs[16];
 
--- a/src/vehicle.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/vehicle.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -332,7 +332,7 @@
 		if (v->index >= (1 << Vehicle_POOL_BLOCK_SIZE_BITS) * BLOCKS_FOR_SPECIAL_VEHICLES)
 			return NULL;
 
-		if (!IsValidVehicle(v)) return InitializeVehicle(v);
+		if (!v->IsValid()) return InitializeVehicle(v);
 	}
 
 	return NULL;
@@ -355,10 +355,10 @@
 
 	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
 	 * @todo - This is just a temporary stage, this will be removed. */
-	if (*skip_vehicles < (_Vehicle_pool.total_items - offset)) { // make sure the offset in the array is not larger than the array itself
+	if (*skip_vehicles < (_Vehicle_pool.GetSize() - offset)) { // make sure the offset in the array is not larger than the array itself
 		for (v = GetVehicle(offset + *skip_vehicles); v != NULL; v = (v->index + 1U < GetVehiclePoolSize()) ? GetVehicle(v->index + 1) : NULL) {
 			(*skip_vehicles)++;
-			if (!IsValidVehicle(v)) return InitializeVehicle(v);
+			if (!v->IsValid()) return InitializeVehicle(v);
 		}
 	}
 
@@ -471,8 +471,8 @@
 	if (remove) {
 		new_hash = NULL;
 	} else {
-		int x = GB(v->x_pos / TILE_SIZE, HASH_RES, HASH_BITS);
-		int y = GB(v->y_pos / TILE_SIZE, HASH_RES, HASH_BITS) << HASH_BITS;
+		int x = GB(TileX(v->tile), HASH_RES, HASH_BITS);
+		int y = GB(TileY(v->tile), HASH_RES, HASH_BITS) << HASH_BITS;
 		new_hash = &_new_vehicle_position_hash[(x + y) & TOTAL_HASH_MASK];
 	}
 
@@ -852,17 +852,14 @@
 	SpriteID image = v->cur_image;
 	SpriteID pal;
 
-	if (v->vehstatus & VS_SHADOW) {
-		SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
-		pal = PALETTE_TO_TRANSPARENT;
-	} else if (v->vehstatus & VS_DEFPAL) {
+	if (v->vehstatus & VS_DEFPAL) {
 		pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
 	} else {
 		pal = PAL_NONE;
 	}
 
 	AddSortableSpriteToDraw(image, pal, v->x_pos + v->x_offs, v->y_pos + v->y_offs,
-		v->sprite_width, v->sprite_height, v->z_height, v->z_pos);
+		v->sprite_width, v->sprite_height, v->z_height, v->z_pos, (v->vehstatus & VS_SHADOW) != 0);
 }
 
 void ViewportAddVehicles(DrawPixelInfo *dpi)
@@ -1116,8 +1113,8 @@
 		EndVehicleMove(v);
 	}
 
-	v->u.special.unk0--;
-	if (v->u.special.unk0 == 0) {
+	v->u.special.animation_state--;
+	if (v->u.special.animation_state == 0) {
 		BeginVehicleMove(v);
 		EndVehicleMove(v);
 		DeleteVehicle(v);
@@ -1150,8 +1147,8 @@
 {
 	v->cur_image = SPR_BULLDOZER_NE;
 	v->progress = 0;
-	v->u.special.unk0 = 0;
-	v->u.special.unk2 = 0;
+	v->u.special.animation_state = 0;
+	v->u.special.animation_substate = 0;
 }
 
 struct BulldozerMovement {
@@ -1197,7 +1194,7 @@
 {
 	v->progress++;
 	if ((v->progress & 7) == 0) {
-		const BulldozerMovement* b = &_bulldozer_movement[v->u.special.unk0];
+		const BulldozerMovement* b = &_bulldozer_movement[v->u.special.animation_state];
 
 		BeginVehicleMove(v);
 
@@ -1206,11 +1203,11 @@
 		v->x_pos += _inc_by_dir[b->direction].x;
 		v->y_pos += _inc_by_dir[b->direction].y;
 
-		v->u.special.unk2++;
-		if (v->u.special.unk2 >= b->duration) {
-			v->u.special.unk2 = 0;
-			v->u.special.unk0++;
-			if (v->u.special.unk0 == lengthof(_bulldozer_movement)) {
+		v->u.special.animation_substate++;
+		if (v->u.special.animation_substate >= b->duration) {
+			v->u.special.animation_substate = 0;
+			v->u.special.animation_state++;
+			if (v->u.special.animation_state == lengthof(_bulldozer_movement)) {
 				EndVehicleMove(v);
 				DeleteVehicle(v);
 				return;
@@ -1402,7 +1399,7 @@
 			EndVehicleMove(v);
 			return;
 		}
-		if (v->u.special.unk2 != 0) {
+		if (v->u.special.animation_substate != 0) {
 			v->spritenum = GB(InteractiveRandom(), 0, 2) + 1;
 		} else {
 			v->spritenum = 6;
@@ -2395,6 +2392,7 @@
 				break;
 
 			case VEH_ROAD:
+				if (!IsRoadVehFront(v)) continue;
 				break;
 
 			case VEH_AIRCRAFT:
@@ -2480,7 +2478,8 @@
 
 static Rect _old_vehicle_coords;
 
-void BeginVehicleMove(Vehicle *v) {
+void BeginVehicleMove(Vehicle *v)
+{
 	_old_vehicle_coords.left = v->left_coord;
 	_old_vehicle_coords.top = v->top_coord;
 	_old_vehicle_coords.right = v->right_coord;
@@ -3044,8 +3043,8 @@
 	    SLE_VAR(Vehicle, progress,      SLE_UINT8),
 	    SLE_VAR(Vehicle, vehstatus,     SLE_UINT8),
 
-	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleSpecial, unk0), SLE_UINT16),
-	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleSpecial, unk2), SLE_UINT8),
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleSpecial, animation_state),    SLE_UINT16),
+	    SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleSpecial, animation_substate), SLE_UINT8),
 
 	/* reserve extra space in savegame here. (currently 16 bytes) */
 	SLE_CONDNULL(16, 2, SL_MAX_VERSION),
@@ -3082,8 +3081,8 @@
 	SLE_CONDVAR(Vehicle, age,           SLE_INT32,                  31, SL_MAX_VERSION),
 	    SLE_VAR(Vehicle, tick_counter,  SLE_UINT8),
 
-	   SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleDisaster, image_override), SLE_UINT16),
-	   SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleDisaster, unk2),           SLE_UINT16),
+	   SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleDisaster, image_override),           SLE_UINT16),
+	   SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleDisaster, big_ufo_destroyer_target), SLE_UINT16),
 
 	/* reserve extra space in savegame here. (currently 16 bytes) */
 	SLE_CONDNULL(16,                                                 2, SL_MAX_VERSION),
--- a/src/vehicle.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/vehicle.h	Fri Aug 03 18:10:15 2007 +0000
@@ -204,13 +204,13 @@
 };
 
 struct VehicleSpecial {
-	uint16 unk0;
-	byte unk2;
+	uint16 animation_state;
+	byte animation_substate;
 };
 
 struct VehicleDisaster {
 	uint16 image_override;
-	uint16 unk2;
+	VehicleID big_ufo_destroyer_target;
 };
 
 struct VehicleShip {
@@ -354,7 +354,7 @@
 	 * @param v    the vehicle to use as 'storage' backend
 	 * @return the memory that is 'allocated'
 	 */
-	void* operator new(size_t size, Vehicle *v) { return v; }
+	void *operator new(size_t size, Vehicle *v) { return v; }
 
 	/**
 	 * 'Free' the memory allocated by the overriden new.
@@ -434,6 +434,8 @@
 	 * Calls the tick handler of the vehicle
 	 */
 	virtual void Tick() = 0;
+
+	bool IsValid() const { return this->type != VEH_INVALID; }
 };
 
 /**
@@ -518,7 +520,7 @@
 Vehicle *GetLastVehicleInChain(Vehicle *v);
 Vehicle *GetPrevVehicleInChain(const Vehicle *v);
 Vehicle *GetFirstVehicleInChain(const Vehicle *v);
-uint CountVehiclesInChain(const Vehicle* v);
+uint CountVehiclesInChain(const Vehicle *v);
 bool IsEngineCountable(const Vehicle *v);
 void DeleteVehicleChain(Vehicle *v);
 void *VehicleFromPos(TileIndex tile, void *data, VehicleFromPosProc *proc);
@@ -594,7 +596,7 @@
 };
 
 struct GetNewVehiclePosResult {
-	int x,y;
+	int x, y;
 	TileIndex old_tile;
 	TileIndex new_tile;
 };
@@ -614,10 +616,10 @@
 
 /* returns true if staying in the same tile */
 GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v);
-Direction GetDirectionTowards(const Vehicle* v, int x, int y);
+Direction GetDirectionTowards(const Vehicle *v, int x, int y);
 
 #define BEGIN_ENUM_WAGONS(v) do {
-#define END_ENUM_WAGONS(v) } while ( (v=v->next) != NULL);
+#define END_ENUM_WAGONS(v) } while ((v = v->next) != NULL);
 
 DECLARE_OLD_POOL(Vehicle, Vehicle, 9, 125)
 
@@ -636,14 +638,6 @@
 	return GetVehiclePoolSize();
 }
 
-/**
- * Check if a Vehicle really exists.
- */
-static inline bool IsValidVehicle(const Vehicle *v)
-{
-	return v->type != VEH_INVALID;
-}
-
 void DestroyVehicle(Vehicle *v);
 
 static inline void DeleteVehicle(Vehicle *v)
@@ -670,7 +664,7 @@
 	return IsPlayerBuildableVehicleType(v->type);
 }
 
-#define FOR_ALL_VEHICLES_FROM(v, start) for (v = GetVehicle(start); v != NULL; v = (v->index + 1U < GetVehiclePoolSize()) ? GetVehicle(v->index + 1) : NULL) if (IsValidVehicle(v))
+#define FOR_ALL_VEHICLES_FROM(v, start) for (v = GetVehicle(start); v != NULL; v = (v->index + 1U < GetVehiclePoolSize()) ? GetVehicle(v->index + 1) : NULL) if (v->IsValid())
 #define FOR_ALL_VEHICLES(v) FOR_ALL_VEHICLES_FROM(v, 0)
 
 /**
@@ -680,7 +674,7 @@
  */
 static inline bool IsValidVehicleID(uint index)
 {
-	return index < GetVehiclePoolSize() && IsValidVehicle(GetVehicle(index));
+	return index < GetVehiclePoolSize() && GetVehicle(index)->IsValid();
 }
 
 /* Returns order 'index' of a vehicle or NULL when it doesn't exists */
--- a/src/vehicle_gui.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/vehicle_gui.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -409,7 +409,7 @@
 };
 
 static const WindowDesc _vehicle_refit_desc = {
-	WDP_AUTO, WDP_AUTO, 240, 174,
+	WDP_AUTO, WDP_AUTO, 240, 174, 240, 174,
 	WC_VEHICLE_REFIT, WC_VEHICLE_VIEW,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
 	_vehicle_refit_widgets,
@@ -1184,7 +1184,7 @@
 }
 
 static const WindowDesc _player_vehicle_list_train_desc = {
-	WDP_AUTO, WDP_AUTO, 260, 182,
+	WDP_AUTO, WDP_AUTO, 260, 182, 260, 182,
 	WC_TRAINS_LIST, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_vehicle_list_widgets,
@@ -1192,7 +1192,7 @@
 };
 
 static const WindowDesc _player_vehicle_list_road_veh_desc = {
-	WDP_AUTO, WDP_AUTO, 260, 182,
+	WDP_AUTO, WDP_AUTO, 260, 182, 260, 182,
 	WC_ROADVEH_LIST, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_vehicle_list_widgets,
@@ -1200,7 +1200,7 @@
 };
 
 static const WindowDesc _player_vehicle_list_ship_desc = {
-	WDP_AUTO, WDP_AUTO, 260, 182,
+	WDP_AUTO, WDP_AUTO, 260, 182, 260, 182,
 	WC_SHIPS_LIST, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_vehicle_list_widgets,
@@ -1208,7 +1208,7 @@
 };
 
 static const WindowDesc _player_vehicle_list_aircraft_desc = {
-	WDP_AUTO, WDP_AUTO, 260, 182,
+	WDP_AUTO, WDP_AUTO, 260, 182, 260, 182,
 	WC_AIRCRAFT_LIST, WC_NONE,
 	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
 	_vehicle_list_widgets,
--- a/src/video/cocoa_v.mm	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/video/cocoa_v.mm	Fri Aug 03 18:10:15 2007 +0000
@@ -237,8 +237,7 @@
 	AS(QZ_BACKQUOTE,  WKC_BACKQUOTE), // key left of '1'
 	AS(QZ_BACKQUOTE2, WKC_BACKQUOTE), // some keyboards have it on another scancode
 
-	// Pageup stuff + up/down
-	//AM(SDLK_PAGEUP, SDLK_PAGEDOWN, WKC_PAGEUP, WKC_PAGEDOWN),  <==== Does this include HOME/END?
+	/* Pageup stuff + up/down */
 	AS(QZ_PAGEUP,   WKC_PAGEUP),
 	AS(QZ_PAGEDOWN, WKC_PAGEDOWN),
 
@@ -253,7 +252,7 @@
 	AS(QZ_INSERT, WKC_INSERT),
 	AS(QZ_DELETE, WKC_DELETE),
 
-	// Letters. QZ_[a-z] is not in numerical order so we can't use AM(...)
+	/* Letters. QZ_[a-z] is not in numerical order so we can't use AM(...) */
 	AS(QZ_a, 'A'),
 	AS(QZ_b, 'B'),
 	AS(QZ_c, 'C'),
@@ -280,7 +279,7 @@
 	AS(QZ_x, 'X'),
 	AS(QZ_y, 'Y'),
 	AS(QZ_z, 'Z'),
-	// Same thing for digits
+	/* Same thing for digits */
 	AS(QZ_0, '0'),
 	AS(QZ_1, '1'),
 	AS(QZ_2, '2'),
@@ -300,7 +299,7 @@
 	AS(QZ_RETURN, WKC_RETURN),
 	AS(QZ_TAB,    WKC_TAB),
 
-	// Function keys
+	/* Function keys */
 	AS(QZ_F1,  WKC_F1),
 	AS(QZ_F2,  WKC_F2),
 	AS(QZ_F3,  WKC_F3),
@@ -314,7 +313,7 @@
 	AS(QZ_F11, WKC_F11),
 	AS(QZ_F12, WKC_F12),
 
-	// Numeric part.
+	/* Numeric part */
 	AS(QZ_KP0,         WKC_NUM_0),
 	AS(QZ_KP1,         WKC_NUM_1),
 	AS(QZ_KP2,         WKC_NUM_2),
@@ -330,7 +329,20 @@
 	AS(QZ_KP_MINUS,    WKC_NUM_MINUS),
 	AS(QZ_KP_PLUS,     WKC_NUM_PLUS),
 	AS(QZ_KP_ENTER,    WKC_NUM_ENTER),
-	AS(QZ_KP_PERIOD,   WKC_NUM_DECIMAL)
+	AS(QZ_KP_PERIOD,   WKC_NUM_DECIMAL),
+
+	/* Other non-letter keys */
+	AS(QZ_SLASH,        WKC_SLASH),
+	AS(QZ_SEMICOLON,    WKC_SEMICOLON),
+	AS(QZ_EQUALS,       WKC_EQUALS),
+	AS(QZ_LEFTBRACKET,  WKC_L_BRACKET),
+	AS(QZ_BACKSLASH,    WKC_BACKSLASH),
+	AS(QZ_RIGHTBRACKET, WKC_R_BRACKET),
+
+	AS(QZ_QUOTE,   WKC_SINGLEQUOTE),
+	AS(QZ_COMMA,   WKC_COMMA),
+	AS(QZ_MINUS,   WKC_MINUS),
+	AS(QZ_PERIOD,  WKC_PERIOD)
 };
 
 
--- a/src/video/sdl_v.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/video/sdl_v.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -240,7 +240,7 @@
 #define AM(x, y, z, w) {x, y - x, z}
 
 static const VkMapping _vk_mapping[] = {
-	// Pageup stuff + up/down
+	/* Pageup stuff + up/down */
 	AM(SDLK_PAGEUP, SDLK_PAGEDOWN, WKC_PAGEUP, WKC_PAGEDOWN),
 	AS(SDLK_UP,     WKC_UP),
 	AS(SDLK_DOWN,   WKC_DOWN),
@@ -253,7 +253,7 @@
 	AS(SDLK_INSERT, WKC_INSERT),
 	AS(SDLK_DELETE, WKC_DELETE),
 
-	// Map letters & digits
+	/* Map letters & digits */
 	AM(SDLK_a, SDLK_z, 'A', 'Z'),
 	AM(SDLK_0, SDLK_9, '0', '9'),
 
@@ -265,18 +265,30 @@
 	AS(SDLK_RETURN,    WKC_RETURN),
 	AS(SDLK_TAB,       WKC_TAB),
 
-	// Function keys
+	/* Function keys */
 	AM(SDLK_F1, SDLK_F12, WKC_F1, WKC_F12),
 
-	// Numeric part.
-	// What is the virtual keycode for numeric enter??
+	/* Numeric part. */
 	AM(SDLK_KP0, SDLK_KP9, WKC_NUM_0, WKC_NUM_9),
 	AS(SDLK_KP_DIVIDE,   WKC_NUM_DIV),
 	AS(SDLK_KP_MULTIPLY, WKC_NUM_MUL),
 	AS(SDLK_KP_MINUS,    WKC_NUM_MINUS),
 	AS(SDLK_KP_PLUS,     WKC_NUM_PLUS),
 	AS(SDLK_KP_ENTER,    WKC_NUM_ENTER),
-	AS(SDLK_KP_PERIOD,   WKC_NUM_DECIMAL)
+	AS(SDLK_KP_PERIOD,   WKC_NUM_DECIMAL),
+
+	/* Other non-letter keys */
+	AS(SDLK_SLASH,        WKC_SLASH),
+	AS(SDLK_SEMICOLON,    WKC_SEMICOLON),
+	AS(SDLK_EQUALS,       WKC_EQUALS),
+	AS(SDLK_LEFTBRACKET,  WKC_L_BRACKET),
+	AS(SDLK_BACKSLASH,    WKC_BACKSLASH),
+	AS(SDLK_RIGHTBRACKET, WKC_R_BRACKET),
+
+	AS(SDLK_QUOTE,   WKC_SINGLEQUOTE),
+	AS(SDLK_COMMA,   WKC_COMMA),
+	AS(SDLK_MINUS,   WKC_MINUS),
+	AS(SDLK_PERIOD,  WKC_PERIOD)
 };
 
 static uint32 ConvertSdlKeyIntoMy(SDL_keysym *sym)
--- a/src/video/win32_v.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/video/win32_v.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -83,9 +83,9 @@
 #define AM(x, y, z, w) {x, y - x, z}
 
 static const VkMapping _vk_mapping[] = {
-	// Pageup stuff + up/down
+	/* Pageup stuff + up/down */
 	AM(VK_PRIOR,VK_DOWN, WKC_PAGEUP, WKC_DOWN),
-	// Map letters & digits
+	/* Map letters & digits */
 	AM('A','Z','A','Z'),
 	AM('0','9','0','9'),
 
@@ -98,17 +98,29 @@
 	AS(VK_RETURN,   WKC_RETURN),
 	AS(VK_TAB,      WKC_TAB),
 
-	// Function keys
+	/* Function keys */
 	AM(VK_F1, VK_F12, WKC_F1, WKC_F12),
 
-	// Numeric part.
-	// What is the virtual keycode for numeric enter??
+	/* Numeric part */
 	AM(VK_NUMPAD0, VK_NUMPAD9, WKC_NUM_0, WKC_NUM_9),
 	AS(VK_DIVIDE,   WKC_NUM_DIV),
 	AS(VK_MULTIPLY, WKC_NUM_MUL),
 	AS(VK_SUBTRACT, WKC_NUM_MINUS),
 	AS(VK_ADD,      WKC_NUM_PLUS),
-	AS(VK_DECIMAL,  WKC_NUM_DECIMAL)
+	AS(VK_DECIMAL,  WKC_NUM_DECIMAL),
+
+	/* Other non-letter keys */
+	AS(0xBF,  WKC_SLASH),
+	AS(0xBA,  WKC_SEMICOLON),
+	AS(0xBB,  WKC_EQUALS),
+	AS(0xDB,  WKC_L_BRACKET),
+	AS(0xDC,  WKC_BACKSLASH),
+	AS(0xDD,  WKC_R_BRACKET),
+
+	AS(0xDE,  WKC_SINGLEQUOTE),
+	AS(0xBC,  WKC_COMMA),
+	AS(0xBD,  WKC_MINUS),
+	AS(0xBE,  WKC_PERIOD)
 };
 
 static uint MapWindowsKey(uint sym)
@@ -137,7 +149,7 @@
 	if (AllocateDibSection(w, h)) {
 		// mark all palette colors dirty
 		_pal_first_dirty = 0;
-		_pal_count_dirty = 255;
+		_pal_count_dirty = 256;
 		GameSizeChanged();
 
 		// redraw screen
--- a/src/viewport.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/viewport.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -135,7 +135,8 @@
 	return p;
 }
 
-void InitViewports() {
+void InitViewports()
+{
 	memset(_viewports, 0, sizeof(_viewports));
 	_active_viewports = 0;
 }
@@ -478,8 +479,18 @@
 	AddChildSpriteScreen(image, pal, pt.x - vd->parent_list[-1]->left, pt.y - vd->parent_list[-1]->top);
 }
 
-
-void AddSortableSpriteToDraw(SpriteID image, SpriteID pal, int x, int y, int w, int h, byte dz, byte z)
+/** Draw a (transparent) sprite at given coordinates
+ * @param image the image to combine and draw,
+ * @param pal the provided palette,
+ * @param x position x of the sprite,
+ * @param y position y of the sprite,
+ * @param w width of the sprite,
+ * @param h height of the sprite,
+ * @param dz delta z, difference of elevation between sprite and parent sprite,
+ * @param z elevation of the sprite,
+ * @param transparent if true, switch the palette between the provided palette and the transparent palette
+ */
+void AddSortableSpriteToDraw(SpriteID image, SpriteID pal, int x, int y, int w, int h, byte dz, byte z, bool transparent)
 {
 	ViewportDrawer *vd = _cur_vd;
 	ParentSpriteToDraw *ps;
@@ -488,6 +499,12 @@
 
 	assert((image & SPRITE_MASK) < MAX_SPRITES);
 
+	/* make the sprites transparent with the right palette */
+	if (transparent) {
+		SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
+		pal = PALETTE_TO_TRANSPARENT;
+	}
+
 	if (vd->combine_sprites == 2) {
 		AddCombinedSprite(image, pal, x, y, z);
 		return;
--- a/src/viewport.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/viewport.h	Fri Aug 03 18:10:15 2007 +0000
@@ -41,14 +41,14 @@
 
 static inline void MaxZoomInOut(int how, Window *w)
 {
-	while (DoZoomInOutWindow(how, w) ) {};
+	while (DoZoomInOutWindow(how, w)) {};
 }
 
 void OffsetGroundSprite(int x, int y);
 
 void DrawGroundSprite(SpriteID image, SpriteID pal);
 void DrawGroundSpriteAt(SpriteID image, SpriteID pal, int32 x, int32 y, byte z);
-void AddSortableSpriteToDraw(SpriteID image, SpriteID pal, int x, int y, int w, int h, byte dz, byte z);
+void AddSortableSpriteToDraw(SpriteID image, SpriteID pal, int x, int y, int w, int h, byte dz, byte z, bool transparent = false);
 void *AddStringToDraw(int x, int y, StringID string, uint64 params_1, uint64 params_2);
 void AddChildSpriteScreen(SpriteID image, SpriteID pal, int x, int y);
 
--- a/src/water_cmd.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/water_cmd.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -28,6 +28,7 @@
 #include "water_map.h"
 #include "newgrf.h"
 #include "newgrf_canal.h"
+#include "misc/autoptr.hpp"
 
 static const SpriteID _water_shore_sprites[] = {
 	0,
@@ -62,7 +63,6 @@
 	TileIndex tile2;
 
 	CommandCost cost, ret;
-	Depot *depot;
 
 	SET_EXPENSES_TYPE(EXPENSES_CONSTRUCTION);
 
@@ -83,17 +83,18 @@
 	ret = DoCommand(tile2, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
 	if (CmdFailed(ret)) return CMD_ERROR;
 
-	depot = AllocateDepot();
+	Depot *depot = new Depot(tile);
 	if (depot == NULL) return CMD_ERROR;
+	AutoPtrT<Depot> d_auto_delete = depot;
 
 	if (flags & DC_EXEC) {
-		depot->xy = tile;
 		depot->town_index = ClosestTownFromTile(tile, (uint)-1)->index;
 
 		MakeShipDepot(tile,  _current_player, DEPOT_NORTH, axis);
 		MakeShipDepot(tile2, _current_player, DEPOT_SOUTH, axis);
 		MarkTileDirtyByTile(tile);
 		MarkTileDirtyByTile(tile2);
+		d_auto_delete.Detach();
 	}
 
 	return cost.AddCost(_price.build_ship_depot);
@@ -113,7 +114,7 @@
 
 	if (flags & DC_EXEC) {
 		/* Kill the depot, which is registered at the northernmost tile. Use that one */
-		DeleteDepot(GetDepotByTile(tile2 < tile ? tile2 : tile));
+		delete GetDepotByTile(tile2 < tile ? tile2 : tile);
 
 		MakeWater(tile);
 		MakeWater(tile2);
@@ -441,23 +442,11 @@
 	DrawGroundSprite(image, PAL_NONE);
 
 	for (; wdts->delta_x != 0x80; wdts++) {
-		SpriteID image = wdts->image;
-		SpriteID pal;
-
-		if (image < 24) image += locks_base;
-		image += base;
-
-		if (HASBIT(_transparent_opt, TO_BUILDINGS)) {
-			SETBIT(image, PALETTE_MODIFIER_TRANSPARENT);
-			pal = PALETTE_TO_TRANSPARENT;
-		} else {
-			pal = palette;
-		}
-
-		AddSortableSpriteToDraw(image, pal,
+		AddSortableSpriteToDraw(wdts->image + base + ((wdts->image < 24) ? locks_base : 0), palette,
 			ti->x + wdts->delta_x, ti->y + wdts->delta_y,
 			wdts->width, wdts->height,
-			wdts->unk, ti->z + wdts->delta_z);
+			wdts->unk, ti->z + wdts->delta_z,
+			HASBIT(_transparent_opt, TO_BUILDINGS));
 	}
 }
 
@@ -512,9 +501,9 @@
 	return z + GetPartialZ(x & 0xF, y & 0xF, tileh);
 }
 
-static Slope GetSlopeTileh_Water(TileIndex tile, Slope tileh)
+static Foundation GetFoundation_Water(TileIndex tile, Slope tileh)
 {
-	return tileh;
+	return FOUNDATION_NONE;
 }
 
 static void GetAcceptedCargo_Water(TileIndex tile, AcceptedCargo ac)
@@ -824,5 +813,5 @@
 	ChangeTileOwner_Water,    /* change_tile_owner_clear */
 	NULL,                     /* get_produced_cargo_proc */
 	VehicleEnter_Water,       /* vehicle_enter_tile_proc */
-	GetSlopeTileh_Water,      /* get_slope_tileh_proc */
+	GetFoundation_Water,      /* get_foundation_proc */
 };
--- a/src/waypoint.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/waypoint.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -26,50 +26,14 @@
 #include "newgrf.h"
 #include "string.h"
 #include "strings.h"
+#include "misc/autoptr.hpp"
 
 enum {
 	MAX_WAYPOINTS_PER_TOWN = 64,
 };
 
-/**
- * Called if a new block is added to the waypoint-pool
- */
-static void WaypointPoolNewBlock(uint start_item)
-{
-	Waypoint *wp;
-
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (wp = GetWaypoint(start_item); wp != NULL; wp = (wp->index + 1U < GetWaypointPoolSize()) ? GetWaypoint(wp->index + 1U) : NULL) wp->index = start_item++;
-}
-
-DEFINE_OLD_POOL(Waypoint, Waypoint, WaypointPoolNewBlock, NULL)
+DEFINE_OLD_POOL_GENERIC(Waypoint, Waypoint)
 
-/**
- * Create a new waypoint
- * @return a pointer to the newly created Waypoint */
-static Waypoint* AllocateWaypoint()
-{
-	Waypoint *wp;
-
-	/* We don't use FOR_ALL here, because FOR_ALL skips invalid items.
-	 * TODO - This is just a temporary stage, this will be removed. */
-	for (wp = GetWaypoint(0); wp != NULL; wp = (wp->index + 1U < GetWaypointPoolSize()) ? GetWaypoint(wp->index + 1U) : NULL) {
-		if (!IsValidWaypoint(wp)) {
-			uint index = wp->index;
-
-			memset(wp, 0, sizeof(*wp));
-			wp->index = index;
-
-			return wp;
-		}
-	}
-
-	/* Check if we can add a block to the pool */
-	if (AddBlockToPool(&_Waypoint_pool)) return AllocateWaypoint();
-
-	return NULL;
-}
 
 /**
  * Update the sign for the waypoint
@@ -106,19 +70,6 @@
 }
 
 /**
- * Internal handler to delete a waypoint
- * @param wp Waypoint to delete
- */
-void DestroyWaypoint(Waypoint *wp)
-{
-	RemoveOrderFromAllVehicles(OT_GOTO_WAYPOINT, wp->index);
-
-	if (wp->string != STR_NULL) DeleteName(wp->string);
-
-	RedrawWaypointSign(wp);
-}
-
-/**
  * Set the default name for a waypoint
  * @param wp Waypoint to work on
  */
@@ -206,6 +157,7 @@
 CommandCost CmdBuildTrainWaypoint(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 {
 	Waypoint *wp;
+	AutoPtrT<Waypoint> wp_auto_delete;
 	Slope tileh;
 	Axis axis;
 
@@ -236,9 +188,11 @@
 	/* Check if there is an already existing, deleted, waypoint close to us that we can reuse. */
 	wp = FindDeletedWaypointCloseTo(tile);
 	if (wp == NULL) {
-		wp = AllocateWaypoint();
+		wp = new Waypoint(tile);
 		if (wp == NULL) return CMD_ERROR;
 
+		wp_auto_delete = wp;
+
 		wp->town_index = 0;
 		wp->string = STR_NULL;
 		wp->town_cn = 0;
@@ -264,7 +218,6 @@
 		}
 
 		wp->deleted = 0;
-		wp->xy = tile;
 		wp->build_date = _date;
 
 		if (wp->town_index == 0) MakeDefaultWaypointName(wp);
@@ -272,6 +225,7 @@
 		UpdateWaypointSign(wp);
 		RedrawWaypointSign(wp);
 		YapfNotifyTrackLayoutChange(tile, AxisToTrack(axis));
+		wp_auto_delete.Detach();
 	}
 
 	return CommandCost(_price.build_train_depot);
@@ -443,6 +397,32 @@
 	}
 }
 
+Waypoint::Waypoint(TileIndex tile)
+{
+	this->xy = tile;
+}
+
+Waypoint::~Waypoint()
+{
+	RemoveOrderFromAllVehicles(OT_GOTO_WAYPOINT, this->index);
+
+	RedrawWaypointSign(this);
+	this->xy = 0;
+
+	this->QuickFree();
+}
+
+void Waypoint::QuickFree()
+{
+	if (this->string != STR_NULL) DeleteName(this->string);
+}
+
+bool Waypoint::IsValid() const
+{
+	return this->xy != 0;
+}
+
+
 /**
  * Fix savegames which stored waypoints in their old format
  */
@@ -463,8 +443,8 @@
 
 void InitializeWaypoints()
 {
-	CleanPool(&_Waypoint_pool);
-	AddBlockToPool(&_Waypoint_pool);
+	_Waypoint_pool.CleanPool();
+	_Waypoint_pool.AddBlockToPool();
 }
 
 static const SaveLoad _waypoint_desc[] = {
@@ -498,12 +478,7 @@
 	int index;
 
 	while ((index = SlIterateArray()) != -1) {
-		Waypoint *wp;
-
-		if (!AddBlockIfNeeded(&_Waypoint_pool, index))
-			error("Waypoints: failed loading savegame: too many waypoints");
-
-		wp = GetWaypoint(index);
+		Waypoint *wp = new (index) Waypoint();
 		SlObject(wp, _waypoint_desc);
 	}
 }
--- a/src/waypoint.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/waypoint.h	Fri Aug 03 18:10:15 2007 +0000
@@ -8,9 +8,11 @@
 #include "oldpool.h"
 #include "rail_map.h"
 
-struct Waypoint {
+struct Waypoint;
+DECLARE_OLD_POOL(Waypoint, Waypoint, 3, 8000)
+
+struct Waypoint : PoolItem<Waypoint, WaypointID, &_Waypoint_pool> {
 	TileIndex xy;      ///< Tile of waypoint
-	WaypointID index;  ///< Index of waypoint
 
 	TownID town_index; ///< Town associated with the waypoint
 	byte town_cn;      ///< The Nth waypoint for this town (consecutive number)
@@ -24,34 +26,26 @@
 	byte localidx;     ///< Index of station within GRF file
 
 	byte deleted;      ///< Delete counter. If greater than 0 then it is decremented until it reaches 0; the waypoint is then is deleted.
-};
-
-DECLARE_OLD_POOL(Waypoint, Waypoint, 3, 8000)
 
-/**
- * Check if a Waypoint really exists.
- * @param wp Waypoint to query
- * @return the validity of the waypoint
- */
-static inline bool IsValidWaypoint(const Waypoint *wp)
-{
-	return wp->xy != 0;
-}
+	Waypoint(TileIndex tile = 0);
+	~Waypoint();
+
+	void QuickFree();
+
+	bool IsValid() const;
+};
 
 static inline bool IsValidWaypointID(WaypointID index)
 {
-	return index < GetWaypointPoolSize() && IsValidWaypoint(GetWaypoint(index));
+	return index < GetWaypointPoolSize() && GetWaypoint(index)->IsValid();
 }
 
-void DestroyWaypoint(Waypoint *wp);
-
 static inline void DeleteWaypoint(Waypoint *wp)
 {
-	DestroyWaypoint(wp);
-	wp->xy = 0;
+	wp->~Waypoint();
 }
 
-#define FOR_ALL_WAYPOINTS_FROM(wp, start) for (wp = GetWaypoint(start); wp != NULL; wp = (wp->index + 1U < GetWaypointPoolSize()) ? GetWaypoint(wp->index + 1U) : NULL) if (IsValidWaypoint(wp))
+#define FOR_ALL_WAYPOINTS_FROM(wp, start) for (wp = GetWaypoint(start); wp != NULL; wp = (wp->index + 1U < GetWaypointPoolSize()) ? GetWaypoint(wp->index + 1U) : NULL) if (wp->IsValid())
 #define FOR_ALL_WAYPOINTS(wp) FOR_ALL_WAYPOINTS_FROM(wp, 0)
 
 
@@ -69,7 +63,7 @@
 CommandCost RemoveTrainWaypoint(TileIndex tile, uint32 flags, bool justremove);
 Station *ComposeWaypointStation(TileIndex tile);
 void ShowRenameWaypointWindow(const Waypoint *cp);
-void DrawWaypointSprite(int x, int y, int image, RailType railtype);
+void DrawWaypointSprite(int x, int y, int stat_id, RailType railtype);
 void FixOldWaypoints();
 void UpdateAllWaypointSigns();
 void AfterLoadWaypoints();
--- a/src/win32.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/win32.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -110,7 +110,8 @@
 
 static uint32 *_crc_table;
 
-static void MakeCRCTable(uint32 *table) {
+static void MakeCRCTable(uint32 *table)
+{
 	uint32 crc, poly = 0xEDB88320L;
 	int i;
 	int j;
@@ -126,7 +127,8 @@
 	}
 }
 
-static uint32 CalcCRC(byte *data, uint size, uint32 crc) {
+static uint32 CalcCRC(byte *data, uint size, uint32 crc)
+{
 	for (; size > 0; size--) {
 		crc = ((crc >> 8) & 0x00FFFFFF) ^ _crc_table[(crc ^ *data++) & 0xFF];
 	}
@@ -1014,7 +1016,7 @@
  * and append this up to the maximum length (either absolute or screenlength). If maxlength
  * is zero, we don't care about the screenlength but only about the physical length of the string
  * @param tb Textbuf type to be changed
- * @return true on successfull change of Textbuf, or false otherwise
+ * @return true on successful change of Textbuf, or false otherwise
  */
 bool InsertTextBufferClipboard(Textbuf *tb)
 {
@@ -1262,3 +1264,17 @@
 
 	return E_INVALIDARG;
 }
+
+/** Determine the current user's locale. */
+const char *GetCurrentLocale(const char *)
+{
+	char lang[9], country[9];
+	if (GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME, lang, lengthof(lang)) == 0 ||
+	    GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO3166CTRYNAME, country, lengthof(country)) == 0) {
+		/* Unable to retrieve the locale. */
+		return NULL;
+	}
+	/* Format it as 'en_us'. */
+	static char retbuf[6] = {lang[0], lang[1], '_', country[0], country[1], 0};
+	return retbuf;
+}
--- a/src/window.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/window.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -590,16 +590,19 @@
  * Only addition here is window_number, which is the window_number being assigned to the new window
  * @param x offset in pixels from the left of the screen
  * @param y offset in pixels from the top of the screen
- * @param width width in pixels of the window
- * @param height height in pixels of the window
+ * @param min_width minimum width in pixels of the window
+ * @param min_height minimum height in pixels of the window
+ * @param def_width default width in pixels of the window
+ * @param def_height default height in pixels of the window
  * @param *proc see WindowProc function to call when any messages/updates happen to the window
  * @param cls see WindowClass class of the window, used for identification and grouping
  * @param *widget see Widget pointer to the window layout and various elements
  * @param window_number number being assigned to the new window
+ * @param data the data to be given during the WE_CREATE message
  * @return Window pointer of the newly created window */
 static Window *LocalAllocateWindow(
-							int x, int y, int width, int height,
-							WindowProc *proc, WindowClass cls, const Widget *widget, int window_number)
+							int x, int y, int min_width, int min_height, int def_width, int def_height,
+							WindowProc *proc, WindowClass cls, const Widget *widget, int window_number, void *data)
 {
 	Window *w = FindFreeWindow();
 
@@ -617,12 +620,12 @@
 	w->caption_color = 0xFF;
 	w->left = x;
 	w->top = y;
-	w->width = width;
-	w->height = height;
+	w->width = min_width;
+	w->height = min_height;
 	w->wndproc = proc;
 	AssignWidgetToWindow(w, widget);
-	w->resize.width = width;
-	w->resize.height = height;
+	w->resize.width = min_width;
+	w->resize.height = min_height;
 	w->resize.step_width = 1;
 	w->resize.step_height = 1;
 	w->window_number = window_number;
@@ -652,7 +655,50 @@
 		_last_z_window++;
 	}
 
-	CallWindowEventNP(w, WE_CREATE);
+	WindowEvent e;
+	e.event = WE_CREATE;
+	e.we.create.data = data;
+	w->wndproc(w, &e);
+
+	/* Try to make windows smaller when our window is too small.
+	 * w->(width|height) is normally the same as min_(width|height),
+	 * but this way the GUIs can be made a little more dynamic;
+	 * one can use the same spec for multiple windows and those
+	 * can then determine the real minimum size of the window. */
+	if (w->width != def_width || w->height != def_height) {
+		/* Think about the overlapping toolbars when determining the minimum window size */
+		int free_height = _screen.height;
+		const Window *wt = FindWindowById(WC_STATUS_BAR, 0);
+		if (wt != NULL) free_height -= wt->height;
+		wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
+		if (wt != NULL) free_height -= wt->height;
+
+		int enlarge_x = max(min(def_width  - w->width,  _screen.width - w->width),  0);
+		int enlarge_y = max(min(def_height - w->height, free_height   - w->height), 0);
+
+		/* X and Y has to go by step.. calculate it.
+		 * The cast to int is necessary else x/y are implicitly casted to
+		 * unsigned int, which won't work. */
+		if (w->resize.step_width  > 1) enlarge_x -= enlarge_x % (int)w->resize.step_width;
+		if (w->resize.step_height > 1) enlarge_y -= enlarge_y % (int)w->resize.step_height;
+
+		ResizeWindow(w, enlarge_x, enlarge_y);
+
+		WindowEvent e;
+		e.event = WE_RESIZE;
+		e.we.sizing.size.x = w->width;
+		e.we.sizing.size.y = w->height;
+		e.we.sizing.diff.x = enlarge_x;
+		e.we.sizing.diff.y = enlarge_y;
+		w->wndproc(w, &e);
+	}
+
+	if (w->left + w->width > _screen.width) w->left -= (w->left + w->width - _screen.width);
+
+	const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
+	w->top  = max(w->top, (wt == NULL || w == wt || y == 0) ? 0 : wt->height);
+	w->left = max(w->left, 0);
+
 	SetWindowDirty(w);
 
 	return w;
@@ -673,9 +719,9 @@
  * @return Window pointer of the newly created window */
 Window *AllocateWindow(
 							int x, int y, int width, int height,
-							WindowProc *proc, WindowClass cls, const Widget *widget)
+							WindowProc *proc, WindowClass cls, const Widget *widget, void *data)
 {
-	return LocalAllocateWindow(x, y, width, height, proc, cls, widget, 0);
+	return LocalAllocateWindow(x, y, width, height, width, height, proc, cls, widget, 0, data);
 }
 
 struct SizeRect {
@@ -787,7 +833,7 @@
 	}
 }
 
-static Window *LocalAllocateWindowDesc(const WindowDesc *desc, int window_number)
+static Window *LocalAllocateWindowDesc(const WindowDesc *desc, int window_number, void *data)
 {
 	Point pt;
 	Window *w;
@@ -800,24 +846,24 @@
 			w->left < _screen.width - 20 && w->left > -60 && w->top < _screen.height - 20) {
 
 		pt.x = w->left + 10;
-		if (pt.x > _screen.width + 10 - desc->width) {
-			pt.x = (_screen.width + 10 - desc->width) - 20;
+		if (pt.x > _screen.width + 10 - desc->default_width) {
+			pt.x = (_screen.width + 10 - desc->default_width) - 20;
 		}
 		pt.y = w->top + 10;
 	} else {
 		switch (desc->left) {
 			case WDP_ALIGN_TBR: { /* Align the right side with the top toolbar */
 				w = FindWindowById(WC_MAIN_TOOLBAR, 0);
-				pt.x = (w->left + w->width) - desc->width;
+				pt.x = (w->left + w->width) - desc->default_width;
 			} break;
 			case WDP_ALIGN_TBL: /* Align the left side with the top toolbar */
 				pt.x = FindWindowById(WC_MAIN_TOOLBAR, 0)->left;
 				break;
 			case WDP_AUTO: /* Find a good automatic position for the window */
-				pt = GetAutoPlacePosition(desc->width, desc->height);
+				pt = GetAutoPlacePosition(desc->default_width, desc->default_height);
 				goto allocate_window;
 			case WDP_CENTER: /* Centre the window horizontally */
-				pt.x = (_screen.width - desc->width) / 2;
+				pt.x = (_screen.width - desc->default_width) / 2;
 				break;
 			default:
 				pt.x = desc->left;
@@ -826,7 +872,7 @@
 
 		switch (desc->top) {
 			case WDP_CENTER: /* Centre the window vertically */
-				pt.y = (_screen.height - desc->height) / 2;
+				pt.y = (_screen.height - desc->default_height) / 2;
 				break;
 			/* WDP_AUTO sets the position at once and is controlled by desc->left.
 			 * Both left and top must be set to WDP_AUTO */
@@ -842,7 +888,7 @@
 	}
 
 allocate_window:
-	w = LocalAllocateWindow(pt.x, pt.y, desc->width, desc->height, desc->proc, desc->cls, desc->widgets, window_number);
+	w = LocalAllocateWindow(pt.x, pt.y, desc->minimum_width, desc->minimum_height, desc->default_width, desc->default_height, desc->proc, desc->cls, desc->widgets, window_number, data);
 	w->desc_flags = desc->flags;
 	return w;
 }
@@ -850,25 +896,27 @@
 /**
  * Open a new window.
  * @param *desc The pointer to the WindowDesc to be created
+ * @param data arbitrary data that is send with the WE_CREATE message
  * @return Window pointer of the newly created window
  */
-Window *AllocateWindowDesc(const WindowDesc *desc)
+Window *AllocateWindowDesc(const WindowDesc *desc, void *data)
 {
-	return LocalAllocateWindowDesc(desc, 0);
+	return LocalAllocateWindowDesc(desc, 0, data);
 }
 
 /**
  * Open a new window.
  * @param *desc The pointer to the WindowDesc to be created
  * @param window_number the window number of the new window
+ * @param data arbitrary data that is send with the WE_CREATE message
  * @return see Window pointer of the newly created window
  */
-Window *AllocateWindowDescFront(const WindowDesc *desc, int window_number)
+Window *AllocateWindowDescFront(const WindowDesc *desc, int window_number, void *data)
 {
 	Window *w;
 
 	if (BringWindowToFrontById(desc->cls, window_number)) return NULL;
-	w = LocalAllocateWindowDesc(desc, window_number);
+	w = LocalAllocateWindowDesc(desc, window_number, data);
 	return w;
 }
 
@@ -2007,6 +2055,18 @@
 		 * in a 'backup'-desc that the window should always be centred. */
 		switch (w->window_class) {
 			case WC_MAIN_TOOLBAR:
+				if (neww - w->width != 0) {
+					ResizeWindow(w, min(neww, 640) - w->width, 0);
+
+					WindowEvent e;
+					e.event = WE_RESIZE;
+					e.we.sizing.size.x = w->width;
+					e.we.sizing.size.y = w->height;
+					e.we.sizing.diff.x = neww - w->width;
+					e.we.sizing.diff.y = 0;
+					w->wndproc(w, &e);
+				}
+
 				top = w->top;
 				left = PositionMainToolbar(w); // changes toolbar orientation
 				break;
@@ -2024,11 +2084,13 @@
 				break;
 
 			case WC_STATUS_BAR:
+				ResizeWindow(w, clamp(neww, 320, 640) - w->width, 0);
 				top = newh - w->height;
 				left = (neww - w->width) >> 1;
 				break;
 
 			case WC_SEND_NETWORK_MSG:
+				ResizeWindow(w, clamp(neww, 320, 640) - w->width, 0);
 				top = (newh - 26); // 26 = height of status bar + height of chat bar
 				left = (neww - w->width) >> 1;
 				break;
--- a/src/window.h	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/window.h	Fri Aug 03 18:10:15 2007 +0000
@@ -127,7 +127,11 @@
 struct WindowEvent {
 	byte event;
 	union {
-		struct{
+		struct {
+			void *data;
+		} create;
+
+		struct {
 			Point pt;
 			int widget;
 		} click;
@@ -191,7 +195,7 @@
 };
 
 struct WindowDesc {
-	int16 left, top, width, height;
+	int16 left, top, minimum_width, minimum_height, default_width, default_height;
 	WindowClass cls;
 	WindowClass parent_cls;
 	uint32 flags;
@@ -581,10 +585,11 @@
 							int height,
 							WindowProc *proc,
 							WindowClass cls,
-							const Widget *widget);
+							const Widget *widget,
+							void *data = NULL);
 
-Window *AllocateWindowDesc(const WindowDesc *desc);
-Window *AllocateWindowDescFront(const WindowDesc *desc, int window_number);
+Window *AllocateWindowDesc(const WindowDesc *desc, void *data = NULL);
+Window *AllocateWindowDescFront(const WindowDesc *desc, int window_number, void *data = NULL);
 
 void DrawWindowViewport(const Window *w);
 void ResizeWindow(Window *w, int x, int y);
--- a/src/yapf/yapf_costrail.hpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/yapf/yapf_costrail.hpp	Fri Aug 03 18:10:15 2007 +0000
@@ -112,7 +112,7 @@
 		if (IsDiagonalTrackdir(trackdir)) {
 			cost += YAPF_TILE_LENGTH;
 			switch (GetTileType(tile)) {
-				case MP_STREET:
+				case MP_ROAD:
 					/* Increase the cost for level crossings */
 					if (IsLevelCrossing(tile))
 						cost += Yapf().PfGetSettings().rail_crossing_penalty;
--- a/src/yapf/yapf_road.cpp	Tue Jul 31 23:31:45 2007 +0000
+++ b/src/yapf/yapf_road.cpp	Fri Aug 03 18:10:15 2007 +0000
@@ -48,7 +48,7 @@
 		if (IsDiagonalTrackdir(trackdir)) {
 			cost += YAPF_TILE_LENGTH;
 			switch (GetTileType(tile)) {
-				case MP_STREET:
+				case MP_ROAD:
 					/* Increase the cost for level crossings */
 					if (IsLevelCrossing(tile))
 						cost += Yapf().PfGetSettings().road_crossing_penalty;
@@ -442,7 +442,7 @@
 		return NULL;
 
 	// handle the case when our vehicle is already in the depot tile
-	if (IsTileType(tile, MP_STREET) && IsTileDepotType(tile, TRANSPORT_ROAD)) {
+	if (IsTileType(tile, MP_ROAD) && IsTileDepotType(tile, TRANSPORT_ROAD)) {
 		// only what we need to return is the Depot*
 		return GetDepotByTile(tile);
 	}