(svn r8149) [cbh] - Sync with -r8038:8038 from trunk (the cpp merge) custombridgeheads
authorcelestar
Mon, 15 Jan 2007 20:14:06 +0000
branchcustombridgeheads
changeset 5650 aefc131bf5ce
parent 5649 55c8267c933f
child 5651 335d9bd345b0
(svn r8149) [cbh] - Sync with -r8038:8038 from trunk (the cpp merge)
Makefile.lang.in
Makefile.src.in
config.lib
projects/langs.vcproj
projects/langs_vs80.vcproj
projects/openttd.vcproj
projects/openttd_vs80.vcproj
projects/strgen.vcproj
projects/strgen_vs80.vcproj
src/ai/ai.cpp
src/ai/default/default.cpp
src/ai/trolly/pathfinder.cpp
src/ai/trolly/trolly.cpp
src/aircraft_cmd.cpp
src/airport.cpp
src/airport.h
src/airport_gui.cpp
src/airport_movement.h
src/aystar.cpp
src/aystar.h
src/bmp.cpp
src/bridge_cmd.cpp
src/bridge_map.cpp
src/build_vehicle_gui.cpp
src/clear_cmd.cpp
src/clear_map.h
src/command.cpp
src/console.cpp
src/console_cmds.cpp
src/debug.h
src/depot.cpp
src/direction.h
src/disaster_cmd.cpp
src/dock_gui.cpp
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/fios.cpp
src/fontcache.cpp
src/functions.h
src/genworld.cpp
src/genworld.h
src/genworld_gui.cpp
src/gfx.cpp
src/gfx.h
src/gfxinit.cpp
src/graph_gui.cpp
src/gui.h
src/hal.h
src/heightmap.cpp
src/helpers.cpp
src/helpers.hpp
src/industry.h
src/industry_cmd.cpp
src/industry_gui.cpp
src/landscape.cpp
src/livery.h
src/macros.h
src/main_gui.cpp
src/map.cpp
src/map.h
src/misc.cpp
src/misc_cmd.cpp
src/misc_gui.cpp
src/mixer.cpp
src/music/dmusic.cpp
src/music_gui.cpp
src/network/core/packet.cpp
src/network/core/tcp.cpp
src/network/core/udp.cpp
src/network/network.cpp
src/network/network.h
src/network/network_client.cpp
src/network/network_data.cpp
src/network/network_data.h
src/network/network_gamelist.cpp
src/network/network_gui.cpp
src/network/network_gui.h
src/network/network_server.cpp
src/network/network_udp.cpp
src/newgrf.cpp
src/newgrf.h
src/newgrf_config.cpp
src/newgrf_engine.cpp
src/newgrf_gui.cpp
src/newgrf_sound.cpp
src/newgrf_spritegroup.cpp
src/newgrf_station.cpp
src/newgrf_station.h
src/newgrf_text.cpp
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/os/macosx/macos.h
src/os/macosx/macos.m
src/os/macosx/splash.h
src/pathfind.cpp
src/pathfind.h
src/player.h
src/player_gui.cpp
src/players.cpp
src/queue.cpp
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/roadveh_cmd.cpp
src/saveload.cpp
src/saveload.h
src/screenshot.cpp
src/settings.cpp
src/settings.h
src/settings_gui.cpp
src/ship_cmd.cpp
src/signs.cpp
src/signs.h
src/sound.cpp
src/sound.h
src/sound/win32_s.cpp
src/spritecache.cpp
src/spritecache.h
src/station.h
src/station_cmd.cpp
src/station_gui.cpp
src/stdafx.h
src/strgen/strgen.cpp
src/string.cpp
src/strings.cpp
src/table/ai_rail.h
src/table/engines.h
src/table/namegen.h
src/table/sprites.h
src/table/station_land.h
src/table/track_land.h
src/table/unmovable_land.h
src/texteff.cpp
src/tgp.cpp
src/thread.cpp
src/tile.cpp
src/tile.h
src/town.h
src/town_cmd.cpp
src/town_gui.cpp
src/train_cmd.cpp
src/tree_cmd.cpp
src/tree_map.h
src/tunnel_cmd.cpp
src/unix.cpp
src/unmovable_cmd.cpp
src/unmovable_map.h
src/variables.h
src/vehicle.cpp
src/vehicle.h
src/vehicle_gui.cpp
src/video/cocoa_v.h
src/video/cocoa_v.m
src/video/dedicated_v.cpp
src/video/null_v.cpp
src/video/sdl_v.cpp
src/video/win32_v.cpp
src/viewport.cpp
src/viewport.h
src/water_cmd.cpp
src/waypoint.cpp
src/widget.cpp
src/win32.cpp
src/window.cpp
src/window.h
src/yapf/follow_track.hpp
src/yapf/track_dir.hpp
src/yapf/yapf.hpp
src/yapf/yapf_base.hpp
src/yapf/yapf_common.hpp
src/yapf/yapf_costrail.hpp
--- a/Makefile.lang.in	Thu Jan 11 13:41:16 2007 +0000
+++ b/Makefile.lang.in	Mon Jan 15 20:14:06 2007 +0000
@@ -7,7 +7,7 @@
 BIN_DIR      = !!BIN_DIR!!
 LANGS_SRC    = $(shell ls $(LANG_DIR)/*.txt)
 LANGS        = $(LANGS_SRC:$(LANG_DIR)/%.txt=%.lng)
-CC_BUILD     = !!CC_BUILD!!
+CXX_BUILD    = !!CXX_BUILD!!
 CFLAGS_BUILD = !!CFLAGS_BUILD!!
 STRGEN_FLAGS = !!STRGEN_FLAGS!!
 STAGE        = !!STAGE!!
@@ -36,13 +36,13 @@
 
 all: table/strings.h $(LANGS)
 
-strgen.o: $(SRC_DIR)/strgen/strgen.c endian_host.h
-	$(E) '$(STAGE) Compiling $(<:$(SRC_DIR)/%.c=%.c)'
-	$(Q)$(CC_BUILD) $(CFLAGS_BUILD) -DSTRGEN -c -o $@ $<
+strgen.o: $(SRC_DIR)/strgen/strgen.cpp endian_host.h
+	$(E) '$(STAGE) Compiling $(<:$(SRC_DIR)/%.cpp=%.cpp)'
+	$(Q)$(CXX_BUILD) $(CFLAGS_BUILD) -DSTRGEN -c -o $@ $<
 
-string.o: $(SRC_DIR)/string.c endian_host.h
-	$(E) '$(STAGE) Compiling $(<:$(SRC_DIR)/%.c=%.c)'
-	$(Q)$(CC_BUILD) $(CFLAGS_BUILD) -DSTRGEN -c -o $@ $<
+string.o: $(SRC_DIR)/string.cpp endian_host.h
+	$(E) '$(STAGE) Compiling $(<:$(SRC_DIR)/%.cpp=%.cpp)'
+	$(Q)$(CXX_BUILD) $(CFLAGS_BUILD) -DSTRGEN -c -o $@ $<
 
 lang/english.txt: $(LANG_DIR)/english.txt
 	$(Q)mkdir -p lang
@@ -50,7 +50,7 @@
 
 $(STRGEN): string.o strgen.o
 	$(E) '$(STAGE) Compiling and Linking $@'
-	$(Q)$(CC_BUILD) string.o strgen.o -o $@
+	$(Q)$(CXX_BUILD) string.o strgen.o -o $@
 
 table/strings.h: lang/english.txt $(STRGEN)
 	$(E) '$(STAGE) Generating $@'
@@ -67,9 +67,9 @@
 	$(E) '$(STAGE) Testing endianness for host'
 	$(Q)./$(ENDIAN_CHECK) > $@
 
-$(ENDIAN_CHECK): $(SRC_DIR)/endian_check.c
+$(ENDIAN_CHECK): $(SRC_DIR)/endian_check.cpp
 	$(E) '$(STAGE) Compiling and Linking $@'
-	$(Q)$(CC_BUILD) $(CFLAGS_BUILD) $< -o $@
+	$(Q)$(CXX_BUILD) $(CFLAGS_BUILD) $< -o $@
 
 depend:
 
--- a/Makefile.src.in	Thu Jan 11 13:41:16 2007 +0000
+++ b/Makefile.src.in	Mon Jan 15 20:14:06 2007 +0000
@@ -3,6 +3,7 @@
 CC_HOST      = !!CC_HOST!!
 CXX_HOST     = !!CXX_HOST!!
 CC_BUILD     = !!CC_BUILD!!
+CXX_BUILD    = !!CXX_BUILD!!
 WINDRES      = !!WINDRES!!
 STRIP        = !!STRIP!!
 CC_CFLAGS    = !!CC_CFLAGS!!
@@ -96,7 +97,7 @@
 
 # If there is a change in the source-file-list, make sure we recheck the deps
 RES := $(shell if [ "`cat $(CONFIG_CACHE_SOURCE) 2>/dev/null`" != "$(SRCS)" ]; then echo "$(SRCS)" > $(CONFIG_CACHE_SOURCE); fi )
-# If there is a change in the revision, make sure we recompile rev.c
+# If there is a change in the revision, make sure we recompile rev.cpp
 RES := $(shell if [ "`cat $(CONFIG_CACHE_VERSION) 2>/dev/null`" != "$(REV)" ]; then echo "$(REV)" > $(CONFIG_CACHE_VERSION); fi )
 
 ifndef MAKEDEPEND
@@ -232,25 +233,25 @@
 	$(E) '$(STAGE) Testing endianness for target'
 	$(Q)./$(ENDIAN_CHECK) $(ENDIAN_FORCE) > $@
 
-$(ENDIAN_CHECK): $(SRC_DIR)/endian_check.c
+$(ENDIAN_CHECK): $(SRC_DIR)/endian_check.cpp
 	$(E) '$(STAGE) Compiling and Linking $@'
-	$(Q)$(CC_BUILD) $(CFLAGS_BUILD) $< -o $@
+	$(Q)$(CXX_BUILD) $(CFLAGS_BUILD) $< -o $@
 
 # Revision files
 
-rev.c: $(CONFIG_CACHE_VERSION)
+rev.cpp: $(CONFIG_CACHE_VERSION)
 # setting the revision number in a place, there the binary can read it
-	@echo 'const char _openttd_revision[] = "$(REV)";' > rev.c
+	@echo 'extern const char _openttd_revision[] = "$(REV)";' > rev.cpp
 # Some additions for MorphOS versions tag
 ifeq ($(OS),MORPHOS)
-	@echo '#ifdef __MORPHOS__' >> rev.c
-	@echo 'const char morphos_versions_tag[] = "\\0$$VER: OpenTTD $(REV) ('`date +%d.%m.%y`') (C) OpenTTD Team [MorphOS, PowerPC]";' >> rev.c
-	@echo '#endif' >> rev.c
+	@echo '#ifdef __MORPHOS__' >> rev.cpp
+	@echo 'extern const char morphos_versions_tag[] = "\\0$$VER: OpenTTD $(REV) ('`date +%d.%m.%y`') (C) OpenTTD Team [MorphOS, PowerPC]";' >> rev.cpp
+	@echo '#endif' >> rev.cpp
 endif
 
-rev.o: rev.c $(FILE_DEP)
-	$(E) '$(STAGE) Compiling $(<:$(SRC_DIR)/%.c=%.c)'
-	$(Q)$(CC_HOST) $(CC_CFLAGS) $(CFLAGS) -c -o $@ $<
+rev.o: rev.cpp $(FILE_DEP)
+	$(E) '$(STAGE) Compiling $(<:$(SRC_DIR)/%.cpp=%.cpp)'
+	$(Q)$(CXX_HOST) $(CFLAGS) -c -o $@ $<
 
 FORCE:
 
@@ -261,7 +262,7 @@
 	$(Q)rm -f $(DEPS) $(OBJS) $(TTD) $(TTD:%=$(BIN_DIR)/%) $(CONFIG_CACHE_COMPILER) $(CONFIG_CACHE_LINKER) $(CONFIG_CACHE_ENDIAN) $(CONFIG_CACHE_SOURCE) $(ENDIAN_TARGETS) rev.o
 
 mrproper: clean
-	$(Q)rm -f rev.c
+	$(Q)rm -f rev.cpp
 
 %.o:
 	@echo '$(STAGE) No such source-file: $(@:%.o=%).[c|cpp|m|rc]'
--- a/config.lib	Thu Jan 11 13:41:16 2007 +0000
+++ b/config.lib	Mon Jan 15 20:14:06 2007 +0000
@@ -12,6 +12,7 @@
 	host=""
 	cc_build=""
 	cc_host=""
+	cxx_build=""
 	cxx_host=""
 	windres=""
 	strip=""
@@ -54,7 +55,7 @@
 	with_freetype="1"
 	with_fontconfig="1"
 
-	save_params_array="build host cc_build cc_host cxx_host windres strip lipo os revision endian config_log prefix_dir binary_dir data_dir icon_dir personal_dir install_dir custom_lang_dir second_data_dir enable_install enable_debug enable_profiling enable_dedicated enable_network enable_static enable_translator enable_assert enable_strip with_osx_sysroot enable_universal enable_osx_g5 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_freetype with_fontconfig CC CXX CFLAGS LDFLAGS"
+	save_params_array="build host cc_build cc_host cxx_build cxx_host windres strip lipo os revision endian config_log prefix_dir binary_dir data_dir icon_dir personal_dir install_dir custom_lang_dir second_data_dir enable_install enable_debug enable_profiling enable_dedicated enable_network enable_static enable_translator enable_assert enable_strip with_osx_sysroot enable_universal enable_osx_g5 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_freetype with_fontconfig CC CXX CFLAGS LDFLAGS"
 }
 
 detect_params() {
@@ -90,6 +91,8 @@
 			--cc-build=*)                 cc_build="$optarg";;
 			--cc-host)                    prevp_p="cc_host";;
 			--cc-host=*)                  cc_host="$optarg";;
+			--cxx-build)                  prevp_p="cxx_build";;
+			--cxx-build=*)                cxx_build="$optarg";;
 			--cxx-host)                   prevp_p="cxx_host";;
 			--cxx-host=*)                 cxx_host="$optarg";;
 			--windres)                    prevp_p="windres";;
@@ -320,7 +323,8 @@
 	log 1 "checking for build gcc... $cc_build"
 	log 1 "checking for host gcc... $cc_host"
 
-	check_cxx
+	check_cxx_build
+	check_cxx_host
 	check_windres
 	check_strip
 	check_lipo
@@ -535,7 +539,7 @@
 			native=`LC_ALL=C uname | tr [:upper:] [:lower:] | grep darwin`
 			# If $host doesn't match $build , we are cross-compiling
 			if [ -n "$native" ] && [ "$build" != "$host" ]; then
-				$cc_build $SRC_DIR/os/macosx/G5_detector.c -o G5_detector
+				$cc_build $SRC_DIR/os/macosx/G5_detector.cpp -o G5_detector
 				res=`./G5_detector`
 				rm -f G5_detector
 				if [ -n "$res" ]; then
@@ -981,7 +985,13 @@
 	check_compiler "host system type" "cc_host" "$host" "$cc_host" "$CC" "gcc" "cc" "0" "-dumpmachine"
 }
 
-check_cxx() {
+check_cxx_build() {
+	check_compiler "build g++" "cxx_build" "$build" "$cxx_build" "$CXX" "g++" "c++" 1 "-dumpmachine"
+}
+
+check_cxx_host() {
+	# By default the host is the build
+	if [ -z "$host" ]; then host="$build"; fi
 	check_compiler "host g++" "cxx_host" "$host" "$cxx_host" "$CXX" "g++" "c++" 1 "-dumpmachine"
 }
 
@@ -1584,6 +1594,7 @@
 		s#!!CC_HOST!!#$cc_host#g;
 		s#!!CXX_HOST!!#$cxx_host#g;
 		s#!!CC_BUILD!!#$cc_build#g;
+		s#!!CXX_BUILD!!#$cxx_build#g;
 		s#!!WINDRES!!#$windres#g;
 		s#!!STRIP!!#$strip $strip_arg#g;
 		s#!!LIPO!!#$lipo#g;
--- a/projects/langs.vcproj	Thu Jan 11 13:41:16 2007 +0000
+++ b/projects/langs.vcproj	Mon Jan 15 20:14:06 2007 +0000
@@ -389,6 +389,20 @@
 			</FileConfiguration>
 		</File>
 		<File
+			RelativePath="..\src\lang\slovenian.txt"
+			>
+			<FileConfiguration
+				Name="Debug|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					Description="Generating slovenian language file"
+					CommandLine="..\objs\strgen\strgen.exe -s ..\src\lang -d ..\bin\lang &quot;$(InputPath)&quot;&#x0D;&#x0A;"
+					AdditionalDependencies=""
+					Outputs="..\bin\lang\slovenian.lng"
+				/>
+			</FileConfiguration>
+		</File>
+		<File
 			RelativePath="..\src\lang\spanish.txt"
 			>
 			<FileConfiguration
--- a/projects/langs_vs80.vcproj	Thu Jan 11 13:41:16 2007 +0000
+++ b/projects/langs_vs80.vcproj	Mon Jan 15 20:14:06 2007 +0000
@@ -397,6 +397,20 @@
 			</FileConfiguration>
 		</File>
 		<File
+			RelativePath="..\src\lang\slovenian.txt"
+			>
+			<FileConfiguration
+				Name="Debug|Win32">
+				<Tool
+					Name="VCCustomBuildTool"
+					Description="Generating slovenian language file"
+					CommandLine="..\objs\strgen\strgen.exe -s ..\src\lang -d ..\bin\lang &quot;$(InputPath)&quot;&#x0D;&#x0A;"
+					AdditionalDependencies=""
+					Outputs="..\bin\lang\slovenian.lng"
+				/>
+			</FileConfiguration>
+		</File>
+		<File
 			RelativePath="..\src\lang\spanish.txt"
 			>
 			<FileConfiguration
--- a/projects/openttd.vcproj	Thu Jan 11 13:41:16 2007 +0000
+++ b/projects/openttd.vcproj	Mon Jan 15 20:14:06 2007 +0000
@@ -161,220 +161,220 @@
 			Name="Source Files"
 			Filter="">
 			<File
-				RelativePath=".\..\src\airport.c">
-			</File>
-			<File
-				RelativePath=".\..\src\aystar.c">
-			</File>
-			<File
-				RelativePath=".\..\src\bmp.c">
-			</File>
-			<File
-				RelativePath=".\..\src\callback_table.c">
-			</File>
-			<File
-				RelativePath=".\..\src\command.c">
-			</File>
-			<File
-				RelativePath=".\..\src\console.c">
-			</File>
-			<File
-				RelativePath=".\..\src\console_cmds.c">
-			</File>
-			<File
-				RelativePath=".\..\src\currency.c">
-			</File>
-			<File
-				RelativePath=".\..\src\date.c">
-			</File>
-			<File
-				RelativePath=".\..\src\debug.c">
-			</File>
-			<File
-				RelativePath=".\..\src\dedicated.c">
+				RelativePath=".\..\src\airport.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\depot.c">
-			</File>
-			<File
-				RelativePath=".\..\src\driver.c">
-			</File>
-			<File
-				RelativePath=".\..\src\economy.c">
-			</File>
-			<File
-				RelativePath=".\..\src\elrail.c">
-			</File>
-			<File
-				RelativePath=".\..\src\engine.c">
+				RelativePath=".\..\src\aystar.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\fileio.c">
-			</File>
-			<File
-				RelativePath=".\..\src\fios.c">
-			</File>
-			<File
-				RelativePath=".\..\src\fontcache.c">
+				RelativePath=".\..\src\bmp.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\genworld.c">
+				RelativePath=".\..\src\callback_table.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\gfx.c">
+				RelativePath=".\..\src\command.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\gfxinit.c">
+				RelativePath=".\..\src\console.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\heightmap.c">
+				RelativePath=".\..\src\console_cmds.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\currency.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\date.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\debug.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\dedicated.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\depot.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\driver.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\economy.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\elrail.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\engine.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\fileio.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\fios.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\fontcache.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\genworld.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\gfx.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\gfxinit.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\heightmap.cpp">
 			</File>
 			<File
 				RelativePath=".\..\src\helpers.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\landscape.c">
-			</File>
-			<File
-				RelativePath=".\..\src\map.c">
-			</File>
-			<File
-				RelativePath=".\..\src\md5.c">
-			</File>
-			<File
-				RelativePath=".\..\src\mersenne.c">
-			</File>
-			<File
-				RelativePath=".\..\src\minilzo.c">
-			</File>
-			<File
-				RelativePath=".\..\src\misc.c">
-			</File>
-			<File
-				RelativePath=".\..\src\mixer.c">
-			</File>
-			<File
-				RelativePath=".\..\src\music.c">
-			</File>
-			<File
-				RelativePath=".\..\src\namegen.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\core\core.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\core\packet.c">
+				RelativePath=".\..\src\landscape.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\network\core\tcp.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\core\udp.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\network.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\network_client.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\network_data.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\network_gamelist.c">
+				RelativePath=".\..\src\map.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\network\network_server.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\network_udp.c">
-			</File>
-			<File
-				RelativePath=".\..\src\npf.c">
+				RelativePath=".\..\src\md5.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\oldloader.c">
+				RelativePath=".\..\src\mersenne.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\oldpool.c">
+				RelativePath=".\..\src\minilzo.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\openttd.c">
+				RelativePath=".\..\src\misc.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\os_timer.c">
+				RelativePath=".\..\src\mixer.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\music.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\namegen.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\core\core.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\core\packet.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\core\tcp.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\core\udp.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\network.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\network_client.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\network_data.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\network_gamelist.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\network_server.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\network_udp.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\npf.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\oldloader.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\oldpool.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\openttd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\os_timer.cpp">
 			</File>
 			<File
 				RelativePath=".\..\src\ottdres.rc">
 			</File>
 			<File
-				RelativePath=".\..\src\pathfind.c">
-			</File>
-			<File
-				RelativePath=".\..\src\players.c">
-			</File>
-			<File
-				RelativePath=".\..\src\queue.c">
-			</File>
-			<File
-				RelativePath=".\..\src\rail.c">
-			</File>
-			<File
-				RelativePath=".\..\src\saveload.c">
-			</File>
-			<File
-				RelativePath=".\..\src\screenshot.c">
-			</File>
-			<File
-				RelativePath=".\..\src\sdl.c">
-			</File>
-			<File
-				RelativePath=".\..\src\settings.c">
-			</File>
-			<File
-				RelativePath=".\..\src\signs.c">
-			</File>
-			<File
-				RelativePath=".\..\src\sound.c">
-			</File>
-			<File
-				RelativePath=".\..\src\spritecache.c">
+				RelativePath=".\..\src\pathfind.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\string.c">
-			</File>
-			<File
-				RelativePath=".\..\src\strings.c">
-			</File>
-			<File
-				RelativePath=".\..\src\texteff.c">
-			</File>
-			<File
-				RelativePath=".\..\src\tgp.c">
-			</File>
-			<File
-				RelativePath=".\..\src\thread.c">
+				RelativePath=".\..\src\players.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\tile.c">
-			</File>
-			<File
-				RelativePath=".\..\src\vehicle.c">
-			</File>
-			<File
-				RelativePath=".\..\src\viewport.c">
+				RelativePath=".\..\src\queue.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\waypoint.c">
+				RelativePath=".\..\src\rail.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\widget.c">
+				RelativePath=".\..\src\saveload.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\win32.c">
+				RelativePath=".\..\src\screenshot.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\window.c">
+				RelativePath=".\..\src\sdl.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\settings.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\signs.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\sound.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\spritecache.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\string.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\strings.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\texteff.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\tgp.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\thread.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\tile.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\vehicle.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\viewport.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\waypoint.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\widget.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\win32.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\window.cpp">
 			</File>
 		</Filter>
 		<Filter
@@ -664,158 +664,158 @@
 			Name="GUI Source Code"
 			Filter="">
 			<File
-				RelativePath=".\..\src\aircraft_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\airport_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\bridge_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\build_vehicle_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\depot_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\dock_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\engine_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\genworld_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\graph_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\industry_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\intro_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\main_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\misc_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\music_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\network_gui.c">
+				RelativePath=".\..\src\aircraft_gui.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\newgrf_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\news_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\order_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\player_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\rail_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\road_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\roadveh_gui.c">
+				RelativePath=".\..\src\airport_gui.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\settings_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\ship_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\smallmap_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\station_gui.c">
+				RelativePath=".\..\src\bridge_gui.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\subsidy_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\terraform_gui.c">
+				RelativePath=".\..\src\build_vehicle_gui.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\town_gui.c">
+				RelativePath=".\..\src\depot_gui.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\train_gui.c">
+				RelativePath=".\..\src\dock_gui.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\vehicle_gui.c">
+				RelativePath=".\..\src\engine_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\genworld_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\graph_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\industry_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\intro_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\main_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\misc_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\music_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\network_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\newgrf_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\news_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\order_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\player_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\rail_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\road_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\roadveh_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\settings_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\ship_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\smallmap_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\station_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\subsidy_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\terraform_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\town_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\train_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\vehicle_gui.cpp">
 			</File>
 		</Filter>
 		<Filter
 			Name="Landscape"
 			Filter="">
 			<File
-				RelativePath=".\..\src\aircraft_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\clear_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\bridge_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\disaster_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\dummy_land.c">
-			</File>
-			<File
-				RelativePath=".\..\src\industry_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\misc_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\order_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\rail_cmd.c">
+				RelativePath=".\..\src\aircraft_cmd.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\road_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\roadveh_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\ship_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\station_cmd.c">
+				RelativePath=".\..\src\clear_cmd.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\town_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\train_cmd.c">
+				RelativePath=".\..\src\bridge_cmd.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\tree_cmd.c">
+				RelativePath=".\..\src\disaster_cmd.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\tunnel_cmd.c">
+				RelativePath=".\..\src\dummy_land.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\unmovable_cmd.c">
+				RelativePath=".\..\src\industry_cmd.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\water_cmd.c">
+				RelativePath=".\..\src\misc_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\order_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\rail_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\road_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\roadveh_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\ship_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\station_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\town_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\train_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\tree_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\tunnel_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\unmovable_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\water_cmd.cpp">
 			</File>
 		</Filter>
 		<Filter
@@ -904,57 +904,57 @@
 			Name="AI Files"
 			Filter="">
 			<File
-				RelativePath=".\..\src\ai\ai.c">
-			</File>
-			<File
-				RelativePath=".\..\src\ai\default\default.c">
+				RelativePath=".\..\src\ai\ai.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\ai\trolly\build.c">
+				RelativePath=".\..\src\ai\default\default.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\ai\trolly\pathfinder.c">
+				RelativePath=".\..\src\ai\trolly\build.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\ai\trolly\shared.c">
+				RelativePath=".\..\src\ai\trolly\pathfinder.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\ai\trolly\trolly.c">
+				RelativePath=".\..\src\ai\trolly\shared.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\ai\trolly\trolly.cpp">
 			</File>
 		</Filter>
 		<Filter
 			Name="NewGRF"
 			Filter="">
 			<File
-				RelativePath=".\..\src\newgrf.c">
-			</File>
-			<File
-				RelativePath=".\..\src\newgrf_cargo.c">
-			</File>
-			<File
-				RelativePath=".\..\src\newgrf_config.c">
+				RelativePath=".\..\src\newgrf.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\newgrf_engine.c">
-			</File>
-			<File
-				RelativePath=".\..\src\newgrf_sound.c">
+				RelativePath=".\..\src\newgrf_cargo.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\newgrf_spritegroup.c">
+				RelativePath=".\..\src\newgrf_config.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\newgrf_station.c">
+				RelativePath=".\..\src\newgrf_engine.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\newgrf_text.c">
+				RelativePath=".\..\src\newgrf_sound.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\newgrf_spritegroup.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\newgrf_station.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\newgrf_text.cpp">
 			</File>
 		</Filter>
 		<Filter
 			Name="Map Accessors"
 			Filter="">
 			<File
-				RelativePath=".\..\src\bridge_map.c">
+				RelativePath=".\..\src\bridge_map.cpp">
 			</File>
 			<File
 				RelativePath=".\..\src\bridge_map.h">
@@ -969,13 +969,13 @@
 				RelativePath=".\..\src\rail_map.h">
 			</File>
 			<File
-				RelativePath=".\..\src\road_map.c">
+				RelativePath=".\..\src\road_map.cpp">
 			</File>
 			<File
 				RelativePath=".\..\src\road_map.h">
 			</File>
 			<File
-				RelativePath=".\..\src\station_map.c">
+				RelativePath=".\..\src\station_map.cpp">
 			</File>
 			<File
 				RelativePath=".\..\src\station_map.h">
@@ -987,7 +987,7 @@
 				RelativePath=".\..\src\tree_map.h">
 			</File>
 			<File
-				RelativePath=".\..\src\tunnel_map.c">
+				RelativePath=".\..\src\tunnel_map.cpp">
 			</File>
 			<File
 				RelativePath=".\..\src\tunnel_map.h">
@@ -1094,16 +1094,16 @@
 			Name="Video"
 			Filter="">
 			<File
-				RelativePath=".\..\src\video\dedicated_v.c">
+				RelativePath=".\..\src\video\dedicated_v.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\video\null_v.c">
+				RelativePath=".\..\src\video\null_v.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\video\sdl_v.c">
+				RelativePath=".\..\src\video\sdl_v.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\video\win32_v.c">
+				RelativePath=".\..\src\video\win32_v.cpp">
 			</File>
 		</Filter>
 		<Filter
@@ -1113,23 +1113,23 @@
 				RelativePath=".\..\src\music\dmusic.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\music\null_m.c">
+				RelativePath=".\..\src\music\null_m.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\music\win32_m.c">
+				RelativePath=".\..\src\music\win32_m.cpp">
 			</File>
 		</Filter>
 		<Filter
 			Name="Sound"
 			Filter="">
 			<File
-				RelativePath=".\..\src\sound\null_s.c">
+				RelativePath=".\..\src\sound\null_s.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\sound\sdl_s.c">
+				RelativePath=".\..\src\sound\sdl_s.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\sound\win32_s.c">
+				RelativePath=".\..\src\sound\win32_s.cpp">
 			</File>
 		</Filter>
 		<File
--- a/projects/openttd_vs80.vcproj	Thu Jan 11 13:41:16 2007 +0000
+++ b/projects/openttd_vs80.vcproj	Mon Jan 15 20:14:06 2007 +0000
@@ -444,220 +444,220 @@
 			Name="Source Files"
 			Filter="">
 			<File
-				RelativePath=".\..\src\airport.c">
-			</File>
-			<File
-				RelativePath=".\..\src\aystar.c">
-			</File>
-			<File
-				RelativePath=".\..\src\bmp.c">
-			</File>
-			<File
-				RelativePath=".\..\src\callback_table.c">
-			</File>
-			<File
-				RelativePath=".\..\src\command.c">
-			</File>
-			<File
-				RelativePath=".\..\src\console.c">
-			</File>
-			<File
-				RelativePath=".\..\src\console_cmds.c">
-			</File>
-			<File
-				RelativePath=".\..\src\currency.c">
-			</File>
-			<File
-				RelativePath=".\..\src\date.c">
-			</File>
-			<File
-				RelativePath=".\..\src\debug.c">
-			</File>
-			<File
-				RelativePath=".\..\src\dedicated.c">
+				RelativePath=".\..\src\airport.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\depot.c">
-			</File>
-			<File
-				RelativePath=".\..\src\driver.c">
-			</File>
-			<File
-				RelativePath=".\..\src\economy.c">
-			</File>
-			<File
-				RelativePath=".\..\src\elrail.c">
-			</File>
-			<File
-				RelativePath=".\..\src\engine.c">
+				RelativePath=".\..\src\aystar.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\fileio.c">
-			</File>
-			<File
-				RelativePath=".\..\src\fios.c">
-			</File>
-			<File
-				RelativePath=".\..\src\fontcache.c">
+				RelativePath=".\..\src\bmp.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\genworld.c">
+				RelativePath=".\..\src\callback_table.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\gfx.c">
+				RelativePath=".\..\src\command.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\gfxinit.c">
+				RelativePath=".\..\src\console.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\heightmap.c">
+				RelativePath=".\..\src\console_cmds.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\currency.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\date.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\debug.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\dedicated.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\depot.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\driver.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\economy.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\elrail.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\engine.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\fileio.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\fios.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\fontcache.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\genworld.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\gfx.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\gfxinit.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\heightmap.cpp">
 			</File>
 			<File
 				RelativePath=".\..\src\helpers.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\landscape.c">
-			</File>
-			<File
-				RelativePath=".\..\src\map.c">
-			</File>
-			<File
-				RelativePath=".\..\src\md5.c">
-			</File>
-			<File
-				RelativePath=".\..\src\mersenne.c">
-			</File>
-			<File
-				RelativePath=".\..\src\minilzo.c">
-			</File>
-			<File
-				RelativePath=".\..\src\misc.c">
-			</File>
-			<File
-				RelativePath=".\..\src\mixer.c">
-			</File>
-			<File
-				RelativePath=".\..\src\music.c">
-			</File>
-			<File
-				RelativePath=".\..\src\namegen.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\core\core.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\core\packet.c">
+				RelativePath=".\..\src\landscape.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\network\core\tcp.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\core\udp.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\network.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\network_client.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\network_data.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\network_gamelist.c">
+				RelativePath=".\..\src\map.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\network\network_server.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\network_udp.c">
-			</File>
-			<File
-				RelativePath=".\..\src\npf.c">
+				RelativePath=".\..\src\md5.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\oldloader.c">
+				RelativePath=".\..\src\mersenne.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\oldpool.c">
+				RelativePath=".\..\src\minilzo.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\openttd.c">
+				RelativePath=".\..\src\misc.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\os_timer.c">
+				RelativePath=".\..\src\mixer.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\music.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\namegen.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\core\core.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\core\packet.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\core\tcp.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\core\udp.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\network.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\network_client.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\network_data.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\network_gamelist.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\network_server.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\network_udp.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\npf.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\oldloader.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\oldpool.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\openttd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\os_timer.cpp">
 			</File>
 			<File
 				RelativePath=".\..\src\ottdres.rc">
 			</File>
 			<File
-				RelativePath=".\..\src\pathfind.c">
-			</File>
-			<File
-				RelativePath=".\..\src\players.c">
-			</File>
-			<File
-				RelativePath=".\..\src\queue.c">
-			</File>
-			<File
-				RelativePath=".\..\src\rail.c">
-			</File>
-			<File
-				RelativePath=".\..\src\saveload.c">
-			</File>
-			<File
-				RelativePath=".\..\src\screenshot.c">
-			</File>
-			<File
-				RelativePath=".\..\src\sdl.c">
-			</File>
-			<File
-				RelativePath=".\..\src\settings.c">
-			</File>
-			<File
-				RelativePath=".\..\src\signs.c">
-			</File>
-			<File
-				RelativePath=".\..\src\sound.c">
-			</File>
-			<File
-				RelativePath=".\..\src\spritecache.c">
+				RelativePath=".\..\src\pathfind.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\string.c">
-			</File>
-			<File
-				RelativePath=".\..\src\strings.c">
-			</File>
-			<File
-				RelativePath=".\..\src\texteff.c">
-			</File>
-			<File
-				RelativePath=".\..\src\tgp.c">
-			</File>
-			<File
-				RelativePath=".\..\src\thread.c">
+				RelativePath=".\..\src\players.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\tile.c">
-			</File>
-			<File
-				RelativePath=".\..\src\vehicle.c">
-			</File>
-			<File
-				RelativePath=".\..\src\viewport.c">
+				RelativePath=".\..\src\queue.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\waypoint.c">
+				RelativePath=".\..\src\rail.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\widget.c">
+				RelativePath=".\..\src\saveload.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\win32.c">
+				RelativePath=".\..\src\screenshot.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\window.c">
+				RelativePath=".\..\src\sdl.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\settings.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\signs.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\sound.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\spritecache.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\string.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\strings.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\texteff.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\tgp.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\thread.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\tile.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\vehicle.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\viewport.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\waypoint.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\widget.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\win32.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\window.cpp">
 			</File>
 		</Filter>
 		<Filter
@@ -947,158 +947,158 @@
 			Name="GUI Source Code"
 			Filter="">
 			<File
-				RelativePath=".\..\src\aircraft_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\airport_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\bridge_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\build_vehicle_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\depot_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\dock_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\engine_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\genworld_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\graph_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\industry_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\intro_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\main_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\misc_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\music_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\network\network_gui.c">
+				RelativePath=".\..\src\aircraft_gui.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\newgrf_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\news_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\order_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\player_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\rail_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\road_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\roadveh_gui.c">
+				RelativePath=".\..\src\airport_gui.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\settings_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\ship_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\smallmap_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\station_gui.c">
+				RelativePath=".\..\src\bridge_gui.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\subsidy_gui.c">
-			</File>
-			<File
-				RelativePath=".\..\src\terraform_gui.c">
+				RelativePath=".\..\src\build_vehicle_gui.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\town_gui.c">
+				RelativePath=".\..\src\depot_gui.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\train_gui.c">
+				RelativePath=".\..\src\dock_gui.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\vehicle_gui.c">
+				RelativePath=".\..\src\engine_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\genworld_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\graph_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\industry_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\intro_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\main_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\misc_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\music_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\network\network_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\newgrf_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\news_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\order_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\player_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\rail_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\road_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\roadveh_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\settings_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\ship_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\smallmap_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\station_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\subsidy_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\terraform_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\town_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\train_gui.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\vehicle_gui.cpp">
 			</File>
 		</Filter>
 		<Filter
 			Name="Landscape"
 			Filter="">
 			<File
-				RelativePath=".\..\src\aircraft_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\clear_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\bridge_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\disaster_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\dummy_land.c">
-			</File>
-			<File
-				RelativePath=".\..\src\industry_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\misc_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\order_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\rail_cmd.c">
+				RelativePath=".\..\src\aircraft_cmd.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\road_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\roadveh_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\ship_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\station_cmd.c">
+				RelativePath=".\..\src\clear_cmd.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\town_cmd.c">
-			</File>
-			<File
-				RelativePath=".\..\src\train_cmd.c">
+				RelativePath=".\..\src\bridge_cmd.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\tree_cmd.c">
+				RelativePath=".\..\src\disaster_cmd.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\tunnel_cmd.c">
+				RelativePath=".\..\src\dummy_land.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\unmovable_cmd.c">
+				RelativePath=".\..\src\industry_cmd.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\water_cmd.c">
+				RelativePath=".\..\src\misc_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\order_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\rail_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\road_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\roadveh_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\ship_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\station_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\town_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\train_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\tree_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\tunnel_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\unmovable_cmd.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\water_cmd.cpp">
 			</File>
 		</Filter>
 		<Filter
@@ -1187,57 +1187,57 @@
 			Name="AI Files"
 			Filter="">
 			<File
-				RelativePath=".\..\src\ai\ai.c">
-			</File>
-			<File
-				RelativePath=".\..\src\ai\default\default.c">
+				RelativePath=".\..\src\ai\ai.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\ai\trolly\build.c">
+				RelativePath=".\..\src\ai\default\default.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\ai\trolly\pathfinder.c">
+				RelativePath=".\..\src\ai\trolly\build.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\ai\trolly\shared.c">
+				RelativePath=".\..\src\ai\trolly\pathfinder.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\ai\trolly\trolly.c">
+				RelativePath=".\..\src\ai\trolly\shared.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\ai\trolly\trolly.cpp">
 			</File>
 		</Filter>
 		<Filter
 			Name="NewGRF"
 			Filter="">
 			<File
-				RelativePath=".\..\src\newgrf.c">
-			</File>
-			<File
-				RelativePath=".\..\src\newgrf_cargo.c">
-			</File>
-			<File
-				RelativePath=".\..\src\newgrf_config.c">
+				RelativePath=".\..\src\newgrf.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\newgrf_engine.c">
-			</File>
-			<File
-				RelativePath=".\..\src\newgrf_sound.c">
+				RelativePath=".\..\src\newgrf_cargo.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\newgrf_spritegroup.c">
+				RelativePath=".\..\src\newgrf_config.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\newgrf_station.c">
+				RelativePath=".\..\src\newgrf_engine.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\newgrf_text.c">
+				RelativePath=".\..\src\newgrf_sound.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\newgrf_spritegroup.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\newgrf_station.cpp">
+			</File>
+			<File
+				RelativePath=".\..\src\newgrf_text.cpp">
 			</File>
 		</Filter>
 		<Filter
 			Name="Map Accessors"
 			Filter="">
 			<File
-				RelativePath=".\..\src\bridge_map.c">
+				RelativePath=".\..\src\bridge_map.cpp">
 			</File>
 			<File
 				RelativePath=".\..\src\bridge_map.h">
@@ -1252,13 +1252,13 @@
 				RelativePath=".\..\src\rail_map.h">
 			</File>
 			<File
-				RelativePath=".\..\src\road_map.c">
+				RelativePath=".\..\src\road_map.cpp">
 			</File>
 			<File
 				RelativePath=".\..\src\road_map.h">
 			</File>
 			<File
-				RelativePath=".\..\src\station_map.c">
+				RelativePath=".\..\src\station_map.cpp">
 			</File>
 			<File
 				RelativePath=".\..\src\station_map.h">
@@ -1270,7 +1270,7 @@
 				RelativePath=".\..\src\tree_map.h">
 			</File>
 			<File
-				RelativePath=".\..\src\tunnel_map.c">
+				RelativePath=".\..\src\tunnel_map.cpp">
 			</File>
 			<File
 				RelativePath=".\..\src\tunnel_map.h">
@@ -1377,16 +1377,16 @@
 			Name="Video"
 			Filter="">
 			<File
-				RelativePath=".\..\src\video\dedicated_v.c">
+				RelativePath=".\..\src\video\dedicated_v.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\video\null_v.c">
+				RelativePath=".\..\src\video\null_v.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\video\sdl_v.c">
+				RelativePath=".\..\src\video\sdl_v.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\video\win32_v.c">
+				RelativePath=".\..\src\video\win32_v.cpp">
 			</File>
 		</Filter>
 		<Filter
@@ -1396,23 +1396,23 @@
 				RelativePath=".\..\src\music\dmusic.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\music\null_m.c">
+				RelativePath=".\..\src\music\null_m.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\music\win32_m.c">
+				RelativePath=".\..\src\music\win32_m.cpp">
 			</File>
 		</Filter>
 		<Filter
 			Name="Sound"
 			Filter="">
 			<File
-				RelativePath=".\..\src\sound\null_s.c">
+				RelativePath=".\..\src\sound\null_s.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\sound\sdl_s.c">
+				RelativePath=".\..\src\sound\sdl_s.cpp">
 			</File>
 			<File
-				RelativePath=".\..\src\sound\win32_s.c">
+				RelativePath=".\..\src\sound\win32_s.cpp">
 			</File>
 		</Filter>
 		<Filter
--- a/projects/strgen.vcproj	Thu Jan 11 13:41:16 2007 +0000
+++ b/projects/strgen.vcproj	Mon Jan 15 20:14:06 2007 +0000
@@ -80,10 +80,10 @@
 			Name="Source Files"
 			Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
 			<File
-				RelativePath="..\src\strgen\strgen.c">
+				RelativePath="..\src\strgen\strgen.cpp">
 			</File>
 			<File
-				RelativePath="..\src\string.c">
+				RelativePath="..\src\string.cpp">
 				<FileConfiguration
 					Name="Release|Win32">
 					<Tool
--- a/projects/strgen_vs80.vcproj	Thu Jan 11 13:41:16 2007 +0000
+++ b/projects/strgen_vs80.vcproj	Mon Jan 15 20:14:06 2007 +0000
@@ -114,11 +114,11 @@
 			Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
 			>
 			<File
-				RelativePath="..\src\strgen\strgen.c"
+				RelativePath="..\src\strgen\strgen.cpp"
 				>
 			</File>
 			<File
-				RelativePath="..\src\string.c"
+				RelativePath="..\src\string.cpp"
 				>
 				<FileConfiguration
 					Name="Release|Win32">
--- a/src/ai/ai.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/ai/ai.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -5,6 +5,7 @@
 #include "../variables.h"
 #include "../command.h"
 #include "../network/network.h"
+#include "../helpers.hpp"
 #include "ai.h"
 #include "default/default.h"
 
@@ -50,11 +51,11 @@
 
 	if (_ai_player[player].queue_tail == NULL) {
 		/* There is no item in the queue yet, create the queue */
-		_ai_player[player].queue = malloc(sizeof(AICommand));
+		MallocT(&_ai_player[player].queue, 1);
 		_ai_player[player].queue_tail = _ai_player[player].queue;
 	} else {
 		/* Add an item at the end */
-		_ai_player[player].queue_tail->next = malloc(sizeof(AICommand));
+		MallocT(&_ai_player[player].queue_tail->next, 1);
 		_ai_player[player].queue_tail = _ai_player[player].queue_tail->next;
 	}
 
--- a/src/ai/default/default.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/ai/default/default.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -26,6 +26,7 @@
 #include "../../variables.h"
 #include "../../bridge.h"
 #include "../../date.h"
+#include "../../helpers.hpp"
 #include "default.h"
 
 // remove some day perhaps?
@@ -63,10 +64,10 @@
 
 #include "../../table/ai_rail.h"
 
-static byte GetRailTrackStatus(TileIndex tile)
+static TrackBits GetRailTrackStatus(TileIndex tile)
 {
 	uint32 r = GetTileTrackStatus(tile, TRANSPORT_RAIL);
-	return (byte) (r | r >> 8);
+	return (TrackBits)(byte) (r | r >> 8);
 }
 
 
@@ -644,8 +645,8 @@
 	}
 
 	if (fr->cargo == CT_PASSENGERS || fr->cargo == CT_MAIL) {
-		const Town* from = fr->from;
-		const Town* to   = fr->to;
+		const Town* from = (const Town*)fr->from;
+		const Town* to   = (const Town*)fr->to;
 
 		if (from->pct_pass_transported > 0x99 ||
 				to->pct_pass_transported > 0x99) {
@@ -783,7 +784,7 @@
 	p->ai.order_list_blocks[2] = 255;
 
 	p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
-	p->ai.state_mode = -1;
+	p->ai.state_mode = UCHAR_MAX;
 	p->ai.state_counter = 0;
 	p->ai.timeout_counter = 0;
 }
@@ -851,7 +852,7 @@
 	p->ai.order_list_blocks[1] = 1;
 	p->ai.order_list_blocks[2] = 255;
 	p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
-	p->ai.state_mode = -1;
+	p->ai.state_mode = UCHAR_MAX;
 	p->ai.state_counter = 0;
 	p->ai.timeout_counter = 0;
 }
@@ -919,7 +920,7 @@
 	p->ai.order_list_blocks[1] = 1;
 	p->ai.order_list_blocks[2] = 255;
 	p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
-	p->ai.state_mode = -1;
+	p->ai.state_mode = UCHAR_MAX;
 	p->ai.state_counter = 0;
 	p->ai.timeout_counter = 0;
 }
@@ -1020,7 +1021,7 @@
 	p->ai.order_list_blocks[1] = 1;
 	p->ai.order_list_blocks[2] = 255;
 	p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
-	p->ai.state_mode = -1;
+	p->ai.state_mode = UCHAR_MAX;
 	p->ai.state_counter = 0;
 	p->ai.timeout_counter = 0;
 }
@@ -1089,7 +1090,7 @@
 	p->ai.order_list_blocks[1] = 1;
 	p->ai.order_list_blocks[2] = 255;
 	p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
-	p->ai.state_mode = -1;
+	p->ai.state_mode = UCHAR_MAX;
 	p->ai.state_counter = 0;
 	p->ai.timeout_counter = 0;
 }
@@ -1164,7 +1165,7 @@
 	p->ai.order_list_blocks[2] = 255;
 
 	p->ai.state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
-	p->ai.state_mode = -1;
+	p->ai.state_mode = UCHAR_MAX;
 	p->ai.state_counter = 0;
 	p->ai.timeout_counter = 0;
 }
@@ -1220,7 +1221,7 @@
 	p->ai.order_list_blocks[2] = 255;
 
 	p->ai.state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
-	p->ai.state_mode = -1;
+	p->ai.state_mode = UCHAR_MAX;
 	p->ai.state_counter = 0;
 	p->ai.timeout_counter = 0;
 }
@@ -1278,7 +1279,7 @@
 	p->ai.order_list_blocks[2] = 255;
 
 	p->ai.state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
-	p->ai.state_mode = -1;
+	p->ai.state_mode = UCHAR_MAX;
 	p->ai.state_counter = 0;
 	p->ai.timeout_counter = 0;
 }
@@ -1334,7 +1335,7 @@
 	p->ai.order_list_blocks[2] = 255;
 
 	p->ai.state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
-	p->ai.state_mode = -1;
+	p->ai.state_mode = UCHAR_MAX;
 	p->ai.state_counter = 0;
 	p->ai.timeout_counter = 0;
 }
@@ -1852,7 +1853,7 @@
 	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, p->ai.cur_dir_a^2,
+	FollowTrack(p->ai.cur_tile_a + TileOffsByDiagDir(p->ai.cur_dir_a), 0x2000 | TRANSPORT_RAIL, (DiagDirection)(p->ai.cur_dir_a^2),
 		(TPFEnumProc*)AiEnumFollowTrack, NULL, &arpfd);
 	return arpfd.count > 8;
 }
@@ -1941,7 +1942,7 @@
 		}
 	}
 	arf->recursive_mode = 0;
-	arf->cur_best_dist = (uint)-1;
+	arf->cur_best_dist = UINT_MAX;
 	arf->cur_best_depth = 0xff;
 
 	return better;
@@ -2186,7 +2187,7 @@
 	if (IsTileType(tile, MP_STREET_BRIDGE) || IsTileType(tile, MP_RAILWAY_BRIDGE)) {
 		// Check if the bridge points in the right direction.
 		// This is not really needed the first place AiRemoveTileAndGoForward is called.
-		if (DiagDirToAxis(GetBridgeRampDirection(tile)) != (p->ai.cur_dir_a & 1U)) return false;
+		if (DiagDirToAxis(GetBridgeRampDirection(tile)) != (p->ai.cur_dir_a & 1)) return false;
 
 		tile = GetOtherBridgeEnd(tile);
 
@@ -2820,7 +2821,7 @@
 	are.best_dist = (uint)-1;
 
 	for_each_bit(i, bits) {
-		FollowTrack(tile, 0x3000 | TRANSPORT_ROAD, _dir_by_track[i], (TPFEnumProc*)AiEnumFollowRoad, NULL, &are);
+		FollowTrack(tile, 0x3000 | TRANSPORT_ROAD, (DiagDirection)_dir_by_track[i], (TPFEnumProc*)AiEnumFollowRoad, NULL, &are);
 	}
 
 	if (DistanceManhattan(tile, are.dest) <= are.best_dist) return false;
@@ -3583,7 +3584,7 @@
 	p->ai.state = AIS_1;
 
 	// Get a list of all stations that are in use by a vehicle
-	in_use = malloc(GetMaxStationIndex() + 1);
+	MallocT(&in_use, GetMaxStationIndex() + 1);
 	memset(in_use, 0, GetMaxStationIndex() + 1);
 	FOR_ALL_ORDERS(ord) {
 		if (ord->type == OT_GOTO_STATION) in_use[ord->dest] = 1;
@@ -3703,7 +3704,7 @@
 	} else if (IsTileType(tile, MP_RAILWAY_BRIDGE)) {
 		if (!IsTileOwner(tile, _current_player)) return;
 
-		rails = 0;
+		rails = TRACK_BIT_NONE;
 
 		switch (GetBridgeRampDirection(tile)) {
 			default:
@@ -3798,7 +3799,6 @@
 		uint asked = p->bankrupt_asked;
 		Player *pp, *best_pl = NULL;
 		int32 best_val = -1;
-		uint old_p;
 
 		// Ask the guy with the highest performance hist.
 		FOR_ALL_PLAYERS(pp) {
@@ -3830,7 +3830,7 @@
 		// Too little money for computer to buy it?
 		if (best_pl->player_money >> 1 >= p->bankrupt_value) {
 			// Computer wants to buy it.
-			old_p = _current_player;
+			PlayerID old_p = _current_player;
 			_current_player = p->index;
 			DoCommand(0, old_p, 0, DC_EXEC, CMD_BUY_COMPANY);
 			_current_player = old_p;
--- a/src/ai/trolly/pathfinder.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/ai/trolly/pathfinder.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -11,6 +11,7 @@
 #include "../../depot.h"
 #include "../../tunnel_map.h"
 #include "../../bridge.h"
+#include "../../road.h"
 #include "../ai.h"
 
 #define TEST_STATION_NO_DIR 0xFF
@@ -54,7 +55,7 @@
 // Check if the current tile is in our end-area
 static int32 AyStar_AiPathFinder_EndNodeCheck(AyStar *aystar, OpenListNode *current)
 {
-	const Ai_PathFinderInfo* PathFinderInfo = aystar->user_target;
+	const Ai_PathFinderInfo* PathFinderInfo = (Ai_PathFinderInfo*)aystar->user_target;
 
 	// It is not allowed to have a station on the end of a bridge or tunnel ;)
 	if (current->path.node.user_data[0] != 0) return AYSTAR_DONE;
@@ -79,7 +80,7 @@
 static void AyStar_AiPathFinder_Free(AyStar *aystar)
 {
 	AyStarMain_Free(aystar);
-	free(aystar);
+	delete aystar;
 }
 
 
@@ -96,7 +97,7 @@
 	uint x;
 	uint y;
 	// Create AyStar
-	AyStar *result = malloc(sizeof(AyStar));
+	AyStar *result = new AyStar();
 	init_AyStar(result, AiPathFinder_Hash, 1 << 10);
 	// Set the function pointers
 	result->CalculateG = AyStar_AiPathFinder_CalculateG;
@@ -167,7 +168,7 @@
 // The h-value, simple calculation
 static int32 AyStar_AiPathFinder_CalculateH(AyStar *aystar, AyStarNode *current, OpenListNode *parent)
 {
-	const Ai_PathFinderInfo* PathFinderInfo = aystar->user_target;
+	const Ai_PathFinderInfo* PathFinderInfo = (Ai_PathFinderInfo*)aystar->user_target;
 	int r, r2;
 
 	if (PathFinderInfo->end_direction != AI_PATHFINDER_NO_DIRECTION) {
@@ -211,7 +212,6 @@
 // What tiles are around us.
 static void AyStar_AiPathFinder_GetNeighbours(AyStar *aystar, OpenListNode *current)
 {
-	uint i;
 	int ret;
 	int dir;
 
@@ -220,7 +220,7 @@
 	aystar->num_neighbours = 0;
 
 	// Go through all surrounding tiles and check if they are within the limits
-	for (i = 0; i < 4; i++) {
+	for (DiagDirection i = DIAGDIR_BEGIN; i < DIAGDIR_END; i++) {
 		TileIndex ctile = current->path.node.tile; // Current tile
 		TileIndex atile = ctile + TileOffsByDiagDir(i); // Adjacent tile
 
@@ -234,14 +234,14 @@
 				if (IsTileType(atile, MP_TUNNEL) && GetTunnelDirection(atile) != i) continue;
 
 				if (IsTileType(atile, MP_STREET_BRIDGE) || IsTileType(atile, MP_RAILWAY_BRIDGE)) {
-					if ((_m[atile].m5 & 1U) != DiagDirToAxis(i)) continue;
+					if ((_m[atile].m5 & 1) != DiagDirToAxis(i)) continue;
 				}
 			}
 			// But also if we are on a bridge, we can only move a certain direction
 			if (!PathFinderInfo->rail_or_road && IsRoad(ctile)) {
 				if (IsTileType(ctile, MP_TUNNEL) || IsTileType(ctile, MP_RAILWAY_BRIDGE) || IsTileType(ctile, MP_STREET_BRIDGE)) {
 					// An existing bridge/tunnel... let's test the direction ;)
-					if ((_m[ctile].m5 & 1U) != (i & 1)) continue;
+					if ((_m[ctile].m5 & 1) != (i & 1)) continue;
 				}
 			}
 
@@ -249,7 +249,7 @@
 					(AI_PATHFINDER_FLAG_TUNNEL & current->path.node.user_data[0]) != 0) {
 				// We are a bridge/tunnel, how cool!!
 				//  This means we can only point forward.. get the direction from the user_data
-				if (i != (current->path.node.user_data[0] >> 8)) continue;
+				if ((uint)i != (current->path.node.user_data[0] >> 8)) continue;
 			}
 			dir = 0;
 
@@ -366,7 +366,7 @@
 
 
 extern uint GetRailFoundation(Slope tileh, TrackBits bits); // XXX function declaration in .c
-extern uint GetRoadFoundation(Slope tileh, uint 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
 enum {
 	BRIDGE_NO_FOUNDATION = 1 << 0 | 1 << 3 | 1 << 6 | 1 << 9 | 1 << 12,
@@ -412,7 +412,7 @@
 		// 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, 1 << AiNew_GetRailDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile));
+				r = 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))) {
 					res += AI_PATHFINDER_TILE_GOES_UP_PENALTY;
@@ -421,7 +421,7 @@
 				}
 			} else {
 				if (!IsRoad(parent->path.node.tile) || !(IsTileType(parent->path.node.tile, MP_TUNNEL) || IsTileType(parent->path.node.tile, MP_STREET_BRIDGE) || IsTileType(parent->path.node.tile, MP_RAILWAY_BRIDGE))) {
-					r = GetRoadFoundation(parent_tileh, AiNew_GetRoadDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile));
+					r = GetRoadFoundation(parent_tileh, (RoadBits)AiNew_GetRoadDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile));
 					if (r >= 15 || r == 0) {
 						res += AI_PATHFINDER_TILE_GOES_UP_PENALTY;
 					} else {
@@ -447,13 +447,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, (current->user_data[0] >> 8) & 1) < 15) {
+			if (GetBridgeFoundation(parent_tileh, (Axis)((current->user_data[0] >> 8) & 1)) < 15) {
 				res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
 			}
 		}
 		// Second for the end point
 		if (!HASBIT(BRIDGE_NO_FOUNDATION, tileh)) {
-			if (GetBridgeFoundation(tileh, (current->user_data[0] >> 8) & 1) < 15) {
+			if (GetBridgeFoundation(tileh, (Axis)((current->user_data[0] >> 8) & 1)) < 15) {
 				res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
 			}
 		}
--- a/src/ai/trolly/trolly.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/ai/trolly/trolly.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -794,7 +794,7 @@
 
 	for (i=2;i<p->ainew.path_info.route_length-2;i++) {
 		tile = p->ainew.path_info.route[i];
-		for (j = 0; j < 4; j++) {
+		for (j = DIAGDIR_BEGIN; j < DIAGDIR_END; j++) {
 			TileIndex t = tile + TileOffsByDiagDir(j);
 
 			if (IsTileType(t, MP_STREET) &&
@@ -825,7 +825,7 @@
 
 		tile = p->ainew.path_info.route[i];
 
-		for (j = 0; j < 4; j++) {
+		for (j = DIAGDIR_BEGIN; j < DIAGDIR_END; j++) {
 			TileIndex t = tile + TileOffsByDiagDir(j);
 
 			// It may not be placed on the road/rail itself
@@ -903,7 +903,8 @@
 		}
 
 		// This is because moving 60% is more than we can dream of!
-		max_cargo *= 0.6;
+		max_cargo *= 6;
+		max_cargo /= 10;
 		// We want all the cargo to be gone in a month.. so, we know the cargo it delivers
 		//  we know what the vehicle takes with him, and we know the time it takes him
 		//  to get back here.. now let's do some math!
@@ -1053,7 +1054,7 @@
 					dir3 = p->ainew.to_direction;
 				}
 
-				ret = AI_DoCommand(tile, DiagDirToRoadBits(ReverseDiagDir(dir1)), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
+				ret = AI_DoCommand(tile, DiagDirToRoadBits(ReverseDiagDir((DiagDirection)dir1)), 0, DC_EXEC | DC_NO_WATER, CMD_BUILD_ROAD);
 				if (!CmdFailed(ret)) {
 					dir1 = TileOffsByDiagDir(dir1);
 					if (IsTileType(tile + dir1, MP_CLEAR) || IsTileType(tile + dir1, MP_TREES)) {
@@ -1065,7 +1066,7 @@
 					}
 				}
 
-				ret = AI_DoCommand(tile, DiagDirToRoadBits(ReverseDiagDir(dir2)), 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);
 				if (!CmdFailed(ret)) {
 					dir2 = TileOffsByDiagDir(dir2);
 					if (IsTileType(tile + dir2, MP_CLEAR) || IsTileType(tile + dir2, MP_TREES)) {
@@ -1077,7 +1078,7 @@
 					}
 				}
 
-				ret = AI_DoCommand(tile, DiagDirToRoadBits(dir3), 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);
 				if (!CmdFailed(ret)) {
 					dir3 = TileOffsByDiagDir(dir3);
 					if (IsTileType(tile + dir3, MP_CLEAR) || IsTileType(tile + dir3, MP_TREES)) {
--- a/src/aircraft_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/aircraft_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -246,7 +246,7 @@
 
 		v->unitnumber = unit_num;
 		v->type = u->type = VEH_Aircraft;
-		v->direction = 3;
+		v->direction = DIR_SE;
 
 		v->owner = u->owner = _current_player;
 
@@ -382,7 +382,7 @@
 			u->next = w;
 
 			w->type = VEH_Aircraft;
-			w->direction = 0;
+			w->direction = DIR_N;
 			w->owner = _current_player;
 			w->x_pos = v->x_pos;
 			w->y_pos = v->y_pos;
@@ -907,7 +907,8 @@
 	Station *st;
 	const AirportMovingData *amd;
 	Vehicle *u;
-	byte z,newdir,maxz,curz;
+	byte z, maxz, curz;
+	Direction newdir;
 	GetNewVehiclePosResult gp;
 	uint dist;
 	int x,y;
@@ -1419,7 +1420,7 @@
 	v->cur_speed = 0;
 	v->subspeed = 0;
 	v->progress = 0;
-	v->direction = 3;
+	v->direction = DIR_SE;
 	v->vehstatus &= ~VS_HIDDEN;
 	{
 		Vehicle *u = v->next;
--- a/src/airport.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/airport.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -9,6 +9,7 @@
 #include "variables.h"
 #include "airport_movement.h"
 #include "date.h"
+#include "helpers.hpp"
 
 /* Uncomment this to print out a full report of the airport-structure
  * You should either use
@@ -30,7 +31,7 @@
 
 static void AirportFTAClass_Constructor(AirportFTAClass *apc,
 	const byte *terminals, const byte *helipads,
-	const byte entry_point,  const byte acc_planes,
+	const byte entry_point,  const AcceptPlanes acc_planes,
 	const AirportFTAbuildup *apFA,
 	const TileIndexDiffC *depots, const byte nof_depots,
 	uint size_x, uint size_y
@@ -49,7 +50,7 @@
 void InitializeAirports(void)
 {
 	// country airport
-	CountryAirport = malloc(sizeof(AirportFTAClass));
+	MallocT(&CountryAirport, 1);
 
 	AirportFTAClass_Constructor(
 		CountryAirport,
@@ -64,7 +65,7 @@
 	);
 
 	// city airport
-	CityAirport = malloc(sizeof(AirportFTAClass));
+	MallocT(&CityAirport, 1);
 
 	AirportFTAClass_Constructor(
 		CityAirport,
@@ -79,7 +80,7 @@
 	);
 
 	// metropolitan airport
-	MetropolitanAirport = malloc(sizeof(AirportFTAClass));
+	MallocT(&MetropolitanAirport, 1);
 
 	AirportFTAClass_Constructor(
 		MetropolitanAirport,
@@ -94,7 +95,7 @@
 	);
 
 	// international airport
-	InternationalAirport = (AirportFTAClass *)malloc(sizeof(AirportFTAClass));
+	MallocT(&InternationalAirport, 1);
 
 	AirportFTAClass_Constructor(
 		InternationalAirport,
@@ -109,7 +110,7 @@
 	);
 
 	// intercontintental airport
-	IntercontinentalAirport = (AirportFTAClass *)malloc(sizeof(AirportFTAClass));
+	MallocT(&IntercontinentalAirport, 1);
 
 	AirportFTAClass_Constructor(
 		IntercontinentalAirport,
@@ -124,7 +125,7 @@
 	);
 
 	// heliport, oilrig
-	Heliport = (AirportFTAClass *)malloc(sizeof(AirportFTAClass));
+	MallocT(&Heliport, 1);
 
 	AirportFTAClass_Constructor(
 		Heliport,
@@ -141,7 +142,7 @@
 	Oilrig = Heliport;  // exactly the same structure for heliport/oilrig, so share state machine
 
 	// commuter airport
-	CommuterAirport = malloc(sizeof(AirportFTAClass));
+	MallocT(&CommuterAirport, 1);
 
 	AirportFTAClass_Constructor(
 		CommuterAirport,
@@ -156,7 +157,7 @@
 	);
 
 	// helidepot airport
-	HeliDepot = malloc(sizeof(AirportFTAClass));
+	MallocT(&HeliDepot, 1);
 
 	AirportFTAClass_Constructor(
 		HeliDepot,
@@ -171,7 +172,7 @@
 	);
 
 	// helistation airport
-	HeliStation = malloc(sizeof(AirportFTAClass));
+	MallocT(&HeliStation, 1);
 
 	AirportFTAClass_Constructor(
 		HeliStation,
@@ -202,7 +203,7 @@
 
 static void AirportFTAClass_Constructor(AirportFTAClass *apc,
 	const byte *terminals, const byte *helipads,
-	const byte entry_point, const byte acc_planes,
+	const byte entry_point, const AcceptPlanes acc_planes,
 	const AirportFTAbuildup *apFA,
 	const TileIndexDiffC *depots, const byte nof_depots,
 	uint size_x, uint size_y
@@ -323,7 +324,8 @@
 static void AirportBuildAutomata(AirportFTAClass *apc, const AirportFTAbuildup *apFA)
 {
 	AirportFTA *current;
-	AirportFTA *FAutomata = malloc(sizeof(AirportFTA) * apc->nofelements);
+	AirportFTA *FAutomata;
+	MallocT(&FAutomata, apc->nofelements);
 	uint16 internalcounter = 0;
 	uint16 i;
 
@@ -337,7 +339,8 @@
 
 		// outgoing nodes from the same position, create linked list
 		while (current->position == apFA[internalcounter + 1].position) {
-			AirportFTA *newNode = malloc(sizeof(AirportFTA));
+			AirportFTA *newNode;
+			MallocT(&newNode, 1);
 
 			newNode->position      = apFA[internalcounter + 1].position;
 			newNode->heading       = apFA[internalcounter + 1].heading;
--- a/src/airport.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/airport.h	Mon Jan 15 20:14:06 2007 +0000
@@ -3,6 +3,8 @@
 #ifndef AIRPORT_H
 #define AIRPORT_H
 
+#include "direction.h"
+
 enum {MAX_TERMINALS =  10};
 enum {MAX_HELIPADS  =   4};
 enum {MAX_ELEMENTS  = 255};
@@ -23,12 +25,18 @@
 };
 
 // do not change unless you change v->subtype too. This aligns perfectly with its current setting
-enum {
+enum AcceptPlanes {
+	ACC_BEGIN        = 0,
 	AIRCRAFT_ONLY    = 0,
 	ALL              = 1,
 	HELICOPTERS_ONLY = 2,
+	ACC_END
 };
 
+/** Define basic enum properties */
+template <> struct EnumPropsT<AcceptPlanes> : MakeEnumPropsT<AcceptPlanes, byte, ACC_BEGIN, ACC_END, ACC_END> {};
+typedef TinyEnumT<AcceptPlanes> AcceptPlanesByte;
+
 enum {
 	AMED_NOSPDCLAMP = 1 << 0,
 	AMED_TAKEOFF    = 1 << 1,
@@ -122,7 +130,7 @@
 typedef struct AirportMovingData {
 	int x,y;
 	byte flag;
-	byte direction;
+	DirectionByte direction;
 } AirportMovingData;
 
 // Finite sTate mAchine --> FTA
@@ -131,7 +139,7 @@
 	const byte *terminals;
 	const byte *helipads;
 	byte entry_point;                     // when an airplane arrives at this airport, enter it at position entry_point
-	byte acc_planes;                      // accept airplanes or helicopters or both
+	AcceptPlanesByte acc_planes;                      // accept airplanes or helicopters or both
 	const TileIndexDiffC *airport_depots; // gives the position of the depots on the airports
 	byte nof_depots;                      // number of depots this airport has
 	struct AirportFTA *layout;            // state machine for airport
--- a/src/airport_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/airport_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -216,7 +216,7 @@
 			SetWindowDirty(w);
 			break;
 		case 16: case 17:
-			_station_show_coverage = e->we.click.widget - 16;
+			_station_show_coverage = (e->we.click.widget != 16);
 			SetWindowWidgetLoweredState(w, 16, !_station_show_coverage);
 			SetWindowWidgetLoweredState(w, 17, _station_show_coverage);
 			SndPlayFx(SND_15_BEEP);
--- a/src/airport_movement.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/airport_movement.h	Mon Jan 15 20:14:06 2007 +0000
@@ -17,354 +17,354 @@
 /////*********Movement Positions on Airports********************///////
 // Country Airfield (small) 4x3
 static const AirportMovingData _airport_moving_data_country[22] = {
-	{   53,    3, AMED_EXACTPOS,                   3 }, // 00 In Hangar
-	{   53,   27, 0,                               0 }, // 01 Taxi to right outside depot
-	{   32,   23, AMED_EXACTPOS,                   7 }, // 02 Terminal 1
-	{   10,   23, AMED_EXACTPOS,                   7 }, // 03 Terminal 2
-	{   43,   37, 0,                               0 }, // 04 Going towards terminal 2
-	{   24,   37, 0,                               0 }, // 05 Going towards terminal 2
-	{   53,   37, 0,                               0 }, // 06 Going for takeoff
-	{   61,   40, AMED_EXACTPOS,                   1 }, // 07 Taxi to start of runway (takeoff)
-	{    3,   40, AMED_NOSPDCLAMP,                 0 }, // 08 Accelerate to end of runway
-	{  -79,   40, AMED_NOSPDCLAMP | AMED_TAKEOFF,  0 }, // 09 Take off
-	{  177,   40, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 10 Fly to landing position in air
-	{   56,   40, AMED_NOSPDCLAMP | AMED_LAND,     0 }, // 11 Going down for land
-	{    3,   40, AMED_NOSPDCLAMP | AMED_BRAKE,    0 }, // 12 Just landed, brake until end of runway
-	{    7,   40, 0,                               0 }, // 13 Just landed, turn around and taxi 1 square
-	{   53,   40, 0,                               0 }, // 14 Taxi from runway to crossing
-	{  -31,  193, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 15 Fly around waiting for a landing spot (north-east)
-	{    1,    1, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 16 Fly around waiting for a landing spot (north-west)
-	{  257,    1, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 17 Fly around waiting for a landing spot (south-west)
-	{  273,   49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 18 Fly around waiting for a landing spot (south)
-	{   44,   37, AMED_HELI_RAISE,                 0 }, // 19 Helicopter takeoff
-	{   44,   40, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 20 In position above landing spot helicopter
-	{   44,   40, AMED_HELI_LOWER,                 0 }, // 21 Helicopter landing
+	{   53,    3, AMED_EXACTPOS,                   {DIR_SE} }, // 00 In Hangar
+	{   53,   27, 0,                               {DIR_N} }, // 01 Taxi to right outside depot
+	{   32,   23, AMED_EXACTPOS,                   {DIR_NW} }, // 02 Terminal 1
+	{   10,   23, AMED_EXACTPOS,                   {DIR_NW} }, // 03 Terminal 2
+	{   43,   37, 0,                               {DIR_N} }, // 04 Going towards terminal 2
+	{   24,   37, 0,                               {DIR_N} }, // 05 Going towards terminal 2
+	{   53,   37, 0,                               {DIR_N} }, // 06 Going for takeoff
+	{   61,   40, AMED_EXACTPOS,                   {DIR_NE} }, // 07 Taxi to start of runway (takeoff)
+	{    3,   40, AMED_NOSPDCLAMP,                 {DIR_N} }, // 08 Accelerate to end of runway
+	{  -79,   40, AMED_NOSPDCLAMP | AMED_TAKEOFF,  {DIR_N} }, // 09 Take off
+	{  177,   40, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 10 Fly to landing position in air
+	{   56,   40, AMED_NOSPDCLAMP | AMED_LAND,     {DIR_N} }, // 11 Going down for land
+	{    3,   40, AMED_NOSPDCLAMP | AMED_BRAKE,    {DIR_N} }, // 12 Just landed, brake until end of runway
+	{    7,   40, 0,                               {DIR_N} }, // 13 Just landed, turn around and taxi 1 square
+	{   53,   40, 0,                               {DIR_N} }, // 14 Taxi from runway to crossing
+	{  -31,  193, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 15 Fly around waiting for a landing spot (north-east)
+	{    1,    1, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 16 Fly around waiting for a landing spot (north-west)
+	{  257,    1, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 17 Fly around waiting for a landing spot (south-west)
+	{  273,   49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 18 Fly around waiting for a landing spot (south)
+	{   44,   37, AMED_HELI_RAISE,                 {DIR_N} }, // 19 Helicopter takeoff
+	{   44,   40, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 20 In position above landing spot helicopter
+	{   44,   40, AMED_HELI_LOWER,                 {DIR_N} }, // 21 Helicopter landing
 };
 
 // Commuter Airfield (small) 5x4
 static const AirportMovingData _airport_moving_data_commuter[37] = {
-	{   69,    3, AMED_EXACTPOS,                   3 }, // 00 In Hangar
-	{   72,   22, 0,                               0 }, // 01 Taxi to right outside depot
-	{    8,   22, AMED_EXACTPOS,                   5 }, // 01 Taxi to right outside depot
-	{   24,   36, AMED_EXACTPOS,                   3 }, // 03 Terminal 1
-	{   40,   36, AMED_EXACTPOS,                   3 }, // 04 Terminal 2
-	{   56,   36, AMED_EXACTPOS,                   3 }, // 05 Terminal 3
-	{   40,    8, AMED_EXACTPOS,                   1 }, // 06 Helipad 1
-	{   56,    8, AMED_EXACTPOS,                   1 }, // 07 Helipad 2
-	{   24,   22, 0,                               5 }, // 08 Taxiing
-	{   40,   22, 0,                               5 }, // 09 Taxiing
-	{   56,   22, 0,                               5 }, // 10 Taxiing
-	{   72,   40, 0,                               3 }, // 11 Airport OUTWAY
-	{   72,   54, AMED_EXACTPOS,                   1 }, // 12 Accelerate to end of runway
-	{    7,   54, AMED_NOSPDCLAMP,                 0 }, // 13 Release control of runway, for smoother movement
-	{    5,   54, AMED_NOSPDCLAMP,                 0 }, // 14 End of runway
-	{  -79,   54, AMED_NOSPDCLAMP | AMED_TAKEOFF,  0 }, // 15 Take off
-	{  145,   54, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 16 Fly to landing position in air
-	{   73,   54, AMED_NOSPDCLAMP | AMED_LAND,     0 }, // 17 Going down for land
-	{    3,   54, AMED_NOSPDCLAMP | AMED_BRAKE,    0 }, // 18 Just landed, brake until end of runway
-	{   12,   54, 0,                               7 }, // 19 Just landed, turn around and taxi
-	{    8,   32, 0,                               7 }, // 20 Taxi from runway to crossing
-	{  -31,  149, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 21 Fly around waiting for a landing spot (north-east)
-	{    1,    6, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 22 Fly around waiting for a landing spot (north-west)
-	{  193,    6, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 23 Fly around waiting for a landing spot (south-west)
-	{  225,   81, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 24 Fly around waiting for a landing spot (south)
+	{   69,    3, AMED_EXACTPOS,                   {DIR_SE} }, // 00 In Hangar
+	{   72,   22, 0,                               {DIR_N} }, // 01 Taxi to right outside depot
+	{    8,   22, AMED_EXACTPOS,                   {DIR_SW} }, // 01 Taxi to right outside depot
+	{   24,   36, AMED_EXACTPOS,                   {DIR_SE} }, // 03 Terminal 1
+	{   40,   36, AMED_EXACTPOS,                   {DIR_SE} }, // 04 Terminal 2
+	{   56,   36, AMED_EXACTPOS,                   {DIR_SE} }, // 05 Terminal 3
+	{   40,    8, AMED_EXACTPOS,                   {DIR_NE} }, // 06 Helipad 1
+	{   56,    8, AMED_EXACTPOS,                   {DIR_NE} }, // 07 Helipad 2
+	{   24,   22, 0,                               {DIR_SW} }, // 08 Taxiing
+	{   40,   22, 0,                               {DIR_SW} }, // 09 Taxiing
+	{   56,   22, 0,                               {DIR_SW} }, // 10 Taxiing
+	{   72,   40, 0,                               {DIR_SE} }, // 11 Airport OUTWAY
+	{   72,   54, AMED_EXACTPOS,                   {DIR_NE} }, // 12 Accelerate to end of runway
+	{    7,   54, AMED_NOSPDCLAMP,                 {DIR_N} }, // 13 Release control of runway, for smoother movement
+	{    5,   54, AMED_NOSPDCLAMP,                 {DIR_N} }, // 14 End of runway
+	{  -79,   54, AMED_NOSPDCLAMP | AMED_TAKEOFF,  {DIR_N} }, // 15 Take off
+	{  145,   54, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 16 Fly to landing position in air
+	{   73,   54, AMED_NOSPDCLAMP | AMED_LAND,     {DIR_N} }, // 17 Going down for land
+	{    3,   54, AMED_NOSPDCLAMP | AMED_BRAKE,    {DIR_N} }, // 18 Just landed, brake until end of runway
+	{   12,   54, 0,                               {DIR_NW} }, // 19 Just landed, turn around and taxi
+	{    8,   32, 0,                               {DIR_NW} }, // 20 Taxi from runway to crossing
+	{  -31,  149, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 21 Fly around waiting for a landing spot (north-east)
+	{    1,    6, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 22 Fly around waiting for a landing spot (north-west)
+	{  193,    6, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 23 Fly around waiting for a landing spot (south-west)
+	{  225,   81, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 24 Fly around waiting for a landing spot (south)
 	// Helicopter
-	{   80,    0, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 25 Bufferspace before helipad
-	{   80,    0, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 26 Bufferspace before helipad
-	{   32,    8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 27 Get in position for Helipad1
-	{   48,    8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 28 Get in position for Helipad2
-	{   32,    8, AMED_HELI_LOWER,                 0 }, // 29 Land at Helipad1
-	{   48,    8, AMED_HELI_LOWER,                 0 }, // 30 Land at Helipad2
-	{   32,    8, AMED_HELI_RAISE,                 0 }, // 31 Takeoff Helipad1
-	{   48,    8, AMED_HELI_RAISE,                 0 }, // 32 Takeoff Helipad2
-	{   64,   22, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 33 Go to position for Hangarentrance in air
-	{   64,   22, AMED_HELI_LOWER,                 0 }, // 34 Land in front of hangar
-	{   40,    8, AMED_EXACTPOS,                   0 }, // pre-helitakeoff helipad 1
-	{   56,    8, AMED_EXACTPOS,                   0 }, // pre-helitakeoff helipad 2
+	{   80,    0, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 25 Bufferspace before helipad
+	{   80,    0, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 26 Bufferspace before helipad
+	{   32,    8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 27 Get in position for Helipad1
+	{   48,    8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 28 Get in position for Helipad2
+	{   32,    8, AMED_HELI_LOWER,                 {DIR_N} }, // 29 Land at Helipad1
+	{   48,    8, AMED_HELI_LOWER,                 {DIR_N} }, // 30 Land at Helipad2
+	{   32,    8, AMED_HELI_RAISE,                 {DIR_N} }, // 31 Takeoff Helipad1
+	{   48,    8, AMED_HELI_RAISE,                 {DIR_N} }, // 32 Takeoff Helipad2
+	{   64,   22, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 33 Go to position for Hangarentrance in air
+	{   64,   22, AMED_HELI_LOWER,                 {DIR_N} }, // 34 Land in front of hangar
+	{   40,    8, AMED_EXACTPOS,                   {DIR_N} }, // pre-helitakeoff helipad 1
+	{   56,    8, AMED_EXACTPOS,                   {DIR_N} }, // pre-helitakeoff helipad 2
 };
 
 // City Airport (large) 6x6
 static const AirportMovingData _airport_moving_data_town[25] = {
-	{   85,    3, AMED_EXACTPOS,                   3 }, // 00 In Hangar
-	{   85,   27, 0,                               0 }, // 01 Taxi to right outside depot
-	{   26,   41, AMED_EXACTPOS,                   5 }, // 02 Terminal 1
-	{   56,   20, AMED_EXACTPOS,                   3 }, // 03 Terminal 2
-	{   38,    8, AMED_EXACTPOS,                   5 }, // 04 Terminal 3
-	{   65,    6, 0,                               0 }, // 05 Taxi to right in infront of terminal 2/3
-	{   80,   27, 0,                               0 }, // 06 Taxiway terminals 2-3
-	{   44,   63, 0,                               0 }, // 07 Taxi to Airport center
-	{   58,   71, 0,                               0 }, // 08 Towards takeoff
-	{   72,   85, 0,                               0 }, // 09 Taxi to runway (takeoff)
-	{   89,   85, AMED_EXACTPOS,                   1 }, // 10 Taxi to start of runway (takeoff)
-	{    3,   85, AMED_NOSPDCLAMP,                 0 }, // 11 Accelerate to end of runway
-	{  -79,   85, AMED_NOSPDCLAMP | AMED_TAKEOFF,  0 }, // 12 Take off
-	{  177,   85, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 13 Fly to landing position in air
-	{   89,   85, AMED_NOSPDCLAMP | AMED_LAND,     0 }, // 14 Going down for land
-	{    3,   85, AMED_NOSPDCLAMP | AMED_BRAKE,    0 }, // 15 Just landed, brake until end of runway
-	{   20,   87, 0,                               0 }, // 16 Just landed, turn around and taxi 1 square
-	{   36,   71, 0,                               0 }, // 17 Taxi from runway to crossing
-	{  -31,  193, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 18 Fly around waiting for a landing spot (north-east)
-	{    1,    1, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 19 Fly around waiting for a landing spot (north-west)
-	{  257,    1, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 20 Fly around waiting for a landing spot (south-west)
-	{  273,   49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 21 Fly around waiting for a landing spot (south)
-	{   44,   63, AMED_HELI_RAISE,                 0 }, // 22 Helicopter takeoff
-	{   28,   74, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 23 In position above landing spot helicopter
-	{   28,   74, AMED_HELI_LOWER,                 0 }, // 24 Helicopter landing
+	{   85,    3, AMED_EXACTPOS,                   {DIR_SE} }, // 00 In Hangar
+	{   85,   27, 0,                               {DIR_N} }, // 01 Taxi to right outside depot
+	{   26,   41, AMED_EXACTPOS,                   {DIR_SW} }, // 02 Terminal 1
+	{   56,   20, AMED_EXACTPOS,                   {DIR_SE} }, // 03 Terminal 2
+	{   38,    8, AMED_EXACTPOS,                   {DIR_SW} }, // 04 Terminal 3
+	{   65,    6, 0,                               {DIR_N} }, // 05 Taxi to right in infront of terminal 2/3
+	{   80,   27, 0,                               {DIR_N} }, // 06 Taxiway terminals 2-3
+	{   44,   63, 0,                               {DIR_N} }, // 07 Taxi to Airport center
+	{   58,   71, 0,                               {DIR_N} }, // 08 Towards takeoff
+	{   72,   85, 0,                               {DIR_N} }, // 09 Taxi to runway (takeoff)
+	{   89,   85, AMED_EXACTPOS,                   {DIR_NE} }, // 10 Taxi to start of runway (takeoff)
+	{    3,   85, AMED_NOSPDCLAMP,                 {DIR_N} }, // 11 Accelerate to end of runway
+	{  -79,   85, AMED_NOSPDCLAMP | AMED_TAKEOFF,  {DIR_N} }, // 12 Take off
+	{  177,   85, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 13 Fly to landing position in air
+	{   89,   85, AMED_NOSPDCLAMP | AMED_LAND,     {DIR_N} }, // 14 Going down for land
+	{    3,   85, AMED_NOSPDCLAMP | AMED_BRAKE,    {DIR_N} }, // 15 Just landed, brake until end of runway
+	{   20,   87, 0,                               {DIR_N} }, // 16 Just landed, turn around and taxi 1 square
+	{   36,   71, 0,                               {DIR_N} }, // 17 Taxi from runway to crossing
+	{  -31,  193, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 18 Fly around waiting for a landing spot (north-east)
+	{    1,    1, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 19 Fly around waiting for a landing spot (north-west)
+	{  257,    1, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 20 Fly around waiting for a landing spot (south-west)
+	{  273,   49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 21 Fly around waiting for a landing spot (south)
+	{   44,   63, AMED_HELI_RAISE,                 {DIR_N} }, // 22 Helicopter takeoff
+	{   28,   74, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 23 In position above landing spot helicopter
+	{   28,   74, AMED_HELI_LOWER,                 {DIR_N} }, // 24 Helicopter landing
 };
 
 // Metropolitan Airport (metropolitan) - 2 runways
 static const AirportMovingData _airport_moving_data_metropolitan[27] = {
-	{   85,    3, AMED_EXACTPOS,                   3 }, // 00 In Hangar
-	{   85,   27, 0,                               0 }, // 01 Taxi to right outside depot
-	{   26,   41, AMED_EXACTPOS,                   5 }, // 02 Terminal 1
-	{   56,   20, AMED_EXACTPOS,                   3 }, // 03 Terminal 2
-	{   38,    8, AMED_EXACTPOS,                   5 }, // 04 Terminal 3
-	{   65,    6, 0,                               0 }, // 05 Taxi to right in infront of terminal 2/3
-	{   70,   33, 0,                               0 }, // 06 Taxiway terminals 2-3
-	{   44,   58, 0,                               0 }, // 07 Taxi to Airport center
-	{   72,   58, 0,                               0 }, // 08 Towards takeoff
-	{   72,   69, 0,                               0 }, // 09 Taxi to runway (takeoff)
-	{   89,   69, AMED_EXACTPOS,                   1 }, // 10 Taxi to start of runway (takeoff)
-	{    3,   69, AMED_NOSPDCLAMP,                 0 }, // 11 Accelerate to end of runway
-	{  -79,   69, AMED_NOSPDCLAMP | AMED_TAKEOFF,  0 }, // 12 Take off
-	{  177,   85, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 13 Fly to landing position in air
-	{   89,   85, AMED_NOSPDCLAMP | AMED_LAND,     0 }, // 14 Going down for land
-	{    3,   85, AMED_NOSPDCLAMP | AMED_BRAKE,    0 }, // 15 Just landed, brake until end of runway
-	{   21,   85, 0,                               0 }, // 16 Just landed, turn around and taxi 1 square
-	{   21,   69, 0,                               0 }, // 17 On Runway-out taxiing to In-Way
-	{   21,   54, AMED_EXACTPOS,                   5 }, // 18 Taxi from runway to crossing
-	{  -31,  193, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 19 Fly around waiting for a landing spot (north-east)
-	{    1,    1, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 20 Fly around waiting for a landing spot (north-west)
-	{  257,    1, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 21 Fly around waiting for a landing spot (south-west)
-	{  273,   49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 22 Fly around waiting for a landing spot (south)
-	{   44,   58, 0,                               0 }, // 23 Helicopter takeoff spot on ground (to clear airport sooner)
-	{   44,   63, AMED_HELI_RAISE,                 0 }, // 24 Helicopter takeoff
-	{   15,   54, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 25 Get in position above landing spot helicopter
-	{   15,   54, AMED_HELI_LOWER,                 0 }, // 26 Helicopter landing
+	{   85,    3, AMED_EXACTPOS,                   {DIR_SE} }, // 00 In Hangar
+	{   85,   27, 0,                               {DIR_N} }, // 01 Taxi to right outside depot
+	{   26,   41, AMED_EXACTPOS,                   {DIR_SW} }, // 02 Terminal 1
+	{   56,   20, AMED_EXACTPOS,                   {DIR_SE} }, // 03 Terminal 2
+	{   38,    8, AMED_EXACTPOS,                   {DIR_SW} }, // 04 Terminal 3
+	{   65,    6, 0,                               {DIR_N} }, // 05 Taxi to right in infront of terminal 2/3
+	{   70,   33, 0,                               {DIR_N} }, // 06 Taxiway terminals 2-3
+	{   44,   58, 0,                               {DIR_N} }, // 07 Taxi to Airport center
+	{   72,   58, 0,                               {DIR_N} }, // 08 Towards takeoff
+	{   72,   69, 0,                               {DIR_N} }, // 09 Taxi to runway (takeoff)
+	{   89,   69, AMED_EXACTPOS,                   {DIR_NE} }, // 10 Taxi to start of runway (takeoff)
+	{    3,   69, AMED_NOSPDCLAMP,                 {DIR_N} }, // 11 Accelerate to end of runway
+	{  -79,   69, AMED_NOSPDCLAMP | AMED_TAKEOFF,  {DIR_N} }, // 12 Take off
+	{  177,   85, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 13 Fly to landing position in air
+	{   89,   85, AMED_NOSPDCLAMP | AMED_LAND,     {DIR_N} }, // 14 Going down for land
+	{    3,   85, AMED_NOSPDCLAMP | AMED_BRAKE,    {DIR_N} }, // 15 Just landed, brake until end of runway
+	{   21,   85, 0,                               {DIR_N} }, // 16 Just landed, turn around and taxi 1 square
+	{   21,   69, 0,                               {DIR_N} }, // 17 On Runway-out taxiing to In-Way
+	{   21,   54, AMED_EXACTPOS,                   {DIR_SW} }, // 18 Taxi from runway to crossing
+	{  -31,  193, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 19 Fly around waiting for a landing spot (north-east)
+	{    1,    1, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 20 Fly around waiting for a landing spot (north-west)
+	{  257,    1, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 21 Fly around waiting for a landing spot (south-west)
+	{  273,   49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 22 Fly around waiting for a landing spot (south)
+	{   44,   58, 0,                               {DIR_N} }, // 23 Helicopter takeoff spot on ground (to clear airport sooner)
+	{   44,   63, AMED_HELI_RAISE,                 {DIR_N} }, // 24 Helicopter takeoff
+	{   15,   54, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 25 Get in position above landing spot helicopter
+	{   15,   54, AMED_HELI_LOWER,                 {DIR_N} }, // 26 Helicopter landing
 };
 
 // International Airport (international) - 2 runways, 6 terminals, dedicated helipod
 static const AirportMovingData _airport_moving_data_international[51] = {
-	{    7,   55, AMED_EXACTPOS,                   3 }, // 00 In Hangar 1
-	{  100,   21, AMED_EXACTPOS,                   3 }, // 01 In Hangar 2
-	{    7,   70, 0,                               0 }, // 02 Taxi to right outside depot
-	{  100,   36, 0,                               0 }, // 03 Taxi to right outside depot
-	{   38,   70, AMED_EXACTPOS,                   5 }, // 04 Terminal 1
-	{   38,   54, AMED_EXACTPOS,                   5 }, // 05 Terminal 2
-	{   38,   38, AMED_EXACTPOS,                   5 }, // 06 Terminal 3
-	{   70,   70, AMED_EXACTPOS,                   1 }, // 07 Terminal 4
-	{   70,   54, AMED_EXACTPOS,                   1 }, // 08 Terminal 5
-	{   70,   38, AMED_EXACTPOS,                   1 }, // 09 Terminal 6
-	{  104,   71, AMED_EXACTPOS,                   1 }, // 10 Helipad 1
-	{  104,   55, AMED_EXACTPOS,                   1 }, // 11 Helipad 2
-	{   22,   87, 0,                               0 }, // 12 Towards Terminals 4/5/6, Helipad 1/2
-	{   60,   87, 0,                               0 }, // 13 Towards Terminals 4/5/6, Helipad 1/2
-	{   66,   87, 0,                               0 }, // 14 Towards Terminals 4/5/6, Helipad 1/2
-	{   86,   87, AMED_EXACTPOS,                   7 }, // 15 Towards Terminals 4/5/6, Helipad 1/2
-	{   86,   70, 0,                               0 }, // 16 In Front of Terminal 4 / Helipad 1
-	{   86,   54, 0,                               0 }, // 17 In Front of Terminal 5 / Helipad 2
-	{   86,   38, 0,                               0 }, // 18 In Front of Terminal 6
-	{   86,   22, 0,                               0 }, // 19 Towards Terminals Takeoff (Taxiway)
-	{   66,   22, 0,                               0 }, // 20 Towards Terminals Takeoff (Taxiway)
-	{   60,   22, 0,                               0 }, // 21 Towards Terminals Takeoff (Taxiway)
-	{   38,   22, 0,                               0 }, // 22 Towards Terminals Takeoff (Taxiway)
-	{   22,   70, 0,                               0 }, // 23 In Front of Terminal 1
-	{   22,   58, 0,                               0 }, // 24 In Front of Terminal 2
-	{   22,   38, 0,                               0 }, // 25 In Front of Terminal 3
-	{   22,   22, AMED_EXACTPOS,                   7 }, // 26 Going for Takeoff
-	{   22,    6, 0,                               0 }, // 27 On Runway-out, prepare for takeoff
-	{    3,    6, AMED_EXACTPOS,                   5 }, // 28 Accelerate to end of runway
-	{   60,    6, AMED_NOSPDCLAMP,                 0 }, // 29 Release control of runway, for smoother movement
-	{  105,    6, AMED_NOSPDCLAMP,                 0 }, // 30 End of runway
-	{  190,    6, AMED_NOSPDCLAMP | AMED_TAKEOFF,  0 }, // 31 Take off
-	{  193,  104, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 32 Fly to landing position in air
-	{  105,  104, AMED_NOSPDCLAMP | AMED_LAND,     0 }, // 33 Going down for land
-	{    3,  104, AMED_NOSPDCLAMP | AMED_BRAKE,    0 }, // 34 Just landed, brake until end of runway
-	{   12,  104, 0,                               0 }, // 35 Just landed, turn around and taxi 1 square
-	{    7,   84, 0,                               0 }, // 36 Taxi from runway to crossing
-	{  -31,  209, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 37 Fly around waiting for a landing spot (north-east)
-	{    1,    6, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 38 Fly around waiting for a landing spot (north-west)
-	{  273,    6, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 39 Fly around waiting for a landing spot (south-west)
-	{  305,   81, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 40 Fly around waiting for a landing spot (south)
+	{    7,   55, AMED_EXACTPOS,                   {DIR_SE} }, // 00 In Hangar 1
+	{  100,   21, AMED_EXACTPOS,                   {DIR_SE} }, // 01 In Hangar 2
+	{    7,   70, 0,                               {DIR_N} }, // 02 Taxi to right outside depot
+	{  100,   36, 0,                               {DIR_N} }, // 03 Taxi to right outside depot
+	{   38,   70, AMED_EXACTPOS,                   {DIR_SW} }, // 04 Terminal 1
+	{   38,   54, AMED_EXACTPOS,                   {DIR_SW} }, // 05 Terminal 2
+	{   38,   38, AMED_EXACTPOS,                   {DIR_SW} }, // 06 Terminal 3
+	{   70,   70, AMED_EXACTPOS,                   {DIR_NE} }, // 07 Terminal 4
+	{   70,   54, AMED_EXACTPOS,                   {DIR_NE} }, // 08 Terminal 5
+	{   70,   38, AMED_EXACTPOS,                   {DIR_NE} }, // 09 Terminal 6
+	{  104,   71, AMED_EXACTPOS,                   {DIR_NE} }, // 10 Helipad 1
+	{  104,   55, AMED_EXACTPOS,                   {DIR_NE} }, // 11 Helipad 2
+	{   22,   87, 0,                               {DIR_N} }, // 12 Towards Terminals 4/5/6, Helipad 1/2
+	{   60,   87, 0,                               {DIR_N} }, // 13 Towards Terminals 4/5/6, Helipad 1/2
+	{   66,   87, 0,                               {DIR_N} }, // 14 Towards Terminals 4/5/6, Helipad 1/2
+	{   86,   87, AMED_EXACTPOS,                   {DIR_NW} }, // 15 Towards Terminals 4/5/6, Helipad 1/2
+	{   86,   70, 0,                               {DIR_N} }, // 16 In Front of Terminal 4 / Helipad 1
+	{   86,   54, 0,                               {DIR_N} }, // 17 In Front of Terminal 5 / Helipad 2
+	{   86,   38, 0,                               {DIR_N} }, // 18 In Front of Terminal 6
+	{   86,   22, 0,                               {DIR_N} }, // 19 Towards Terminals Takeoff (Taxiway)
+	{   66,   22, 0,                               {DIR_N} }, // 20 Towards Terminals Takeoff (Taxiway)
+	{   60,   22, 0,                               {DIR_N} }, // 21 Towards Terminals Takeoff (Taxiway)
+	{   38,   22, 0,                               {DIR_N} }, // 22 Towards Terminals Takeoff (Taxiway)
+	{   22,   70, 0,                               {DIR_N} }, // 23 In Front of Terminal 1
+	{   22,   58, 0,                               {DIR_N} }, // 24 In Front of Terminal 2
+	{   22,   38, 0,                               {DIR_N} }, // 25 In Front of Terminal 3
+	{   22,   22, AMED_EXACTPOS,                   {DIR_NW} }, // 26 Going for Takeoff
+	{   22,    6, 0,                               {DIR_N} }, // 27 On Runway-out, prepare for takeoff
+	{    3,    6, AMED_EXACTPOS,                   {DIR_SW} }, // 28 Accelerate to end of runway
+	{   60,    6, AMED_NOSPDCLAMP,                 {DIR_N} }, // 29 Release control of runway, for smoother movement
+	{  105,    6, AMED_NOSPDCLAMP,                 {DIR_N} }, // 30 End of runway
+	{  190,    6, AMED_NOSPDCLAMP | AMED_TAKEOFF,  {DIR_N} }, // 31 Take off
+	{  193,  104, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 32 Fly to landing position in air
+	{  105,  104, AMED_NOSPDCLAMP | AMED_LAND,     {DIR_N} }, // 33 Going down for land
+	{    3,  104, AMED_NOSPDCLAMP | AMED_BRAKE,    {DIR_N} }, // 34 Just landed, brake until end of runway
+	{   12,  104, 0,                               {DIR_N} }, // 35 Just landed, turn around and taxi 1 square
+	{    7,   84, 0,                               {DIR_N} }, // 36 Taxi from runway to crossing
+	{  -31,  209, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 37 Fly around waiting for a landing spot (north-east)
+	{    1,    6, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 38 Fly around waiting for a landing spot (north-west)
+	{  273,    6, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 39 Fly around waiting for a landing spot (south-west)
+	{  305,   81, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 40 Fly around waiting for a landing spot (south)
 	// Helicopter
-	{  128,   80, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 41 Bufferspace before helipad
-	{  128,   80, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 42 Bufferspace before helipad
-	{   96,   71, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 43 Get in position for Helipad1
-	{   96,   55, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 44 Get in position for Helipad2
-	{   96,   71, AMED_HELI_LOWER,                 0 }, // 45 Land at Helipad1
-	{   96,   55, AMED_HELI_LOWER,                 0 }, // 46 Land at Helipad2
-	{  104,   71, AMED_HELI_RAISE,                 0 }, // 47 Takeoff Helipad1
-	{  104,   55, AMED_HELI_RAISE,                 0 }, // 48 Takeoff Helipad2
-	{  104,   32, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 49 Go to position for Hangarentrance in air
-	{  104,   32, AMED_HELI_LOWER,                 0} // 50 Land in HANGAR2_AREA to go to hangar
+	{  128,   80, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 41 Bufferspace before helipad
+	{  128,   80, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 42 Bufferspace before helipad
+	{   96,   71, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 43 Get in position for Helipad1
+	{   96,   55, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 44 Get in position for Helipad2
+	{   96,   71, AMED_HELI_LOWER,                 {DIR_N} }, // 45 Land at Helipad1
+	{   96,   55, AMED_HELI_LOWER,                 {DIR_N} }, // 46 Land at Helipad2
+	{  104,   71, AMED_HELI_RAISE,                 {DIR_N} }, // 47 Takeoff Helipad1
+	{  104,   55, AMED_HELI_RAISE,                 {DIR_N} }, // 48 Takeoff Helipad2
+	{  104,   32, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 49 Go to position for Hangarentrance in air
+	{  104,   32, AMED_HELI_LOWER,                 {DIR_N} }, // 50 Land in HANGAR2_AREA to go to hangar
 };
 
 // Intercontinental Airport - 4 runways, 8 terminals, 2 dedicated helipads
 static const AirportMovingData _airport_moving_data_intercontinental[77] = {
-	{    7,   87, AMED_EXACTPOS,                   3 }, // 00 In Hangar 1
-	{  135,   72, AMED_EXACTPOS,                   3 }, // 01 In Hangar 2
-	{    7,  104, 0,                               0 }, // 02 Taxi to right outside depot 1
-	{  135,   88, 0, 0 }, // 03 Taxi to right outside depot 2
-	{   56,  120, AMED_EXACTPOS,                   6 }, // 04 Terminal 1
-	{   56,  104, AMED_EXACTPOS,                   5 }, // 05 Terminal 2
-	{   56,   88, AMED_EXACTPOS,                   5 }, // 06 Terminal 3
-	{   56,   72, AMED_EXACTPOS,                   5 }, // 07 Terminal 4
-	{   88,  120, AMED_EXACTPOS,                   0 }, // 08 Terminal 5
-	{   88,  104, AMED_EXACTPOS,                   1 }, // 09 Terminal 6
-	{   88,   88, AMED_EXACTPOS,                   1 }, // 10 Terminal 7
-	{   88,   72, AMED_EXACTPOS,                   1 }, // 11 Terminal 8
-	{   88,   56, AMED_EXACTPOS,                   3 }, // 12 Helipad 1
-	{   72,   56, AMED_EXACTPOS,                   1 }, // 13 Helipad 2
-	{   40,  136, 0,                               0 }, // 14 Term group 2 enter 1 a
-	{   56,  136, 0,                               0 }, // 15 Term group 2 enter 1 b
-	{   88,  136, 0,                               0 }, // 16 Term group 2 enter 2 a
-	{  104,  136, 0,                               0 }, // 17 Term group 2 enter 2 b
-	{  104,  120, 0,                               0 }, // 18 Term group 2 - opp term 5
-	{  104,  104, 0,                               0 }, // 19 Term group 2 - opp term 6 & exit2
-	{  104,   88, 0,                               0 }, // 20 Term group 2 - opp term 7 & hangar area 2
-	{  104,   72, 0,                               0 }, // 21 Term group 2 - opp term 8
-	{  104,   56, 0,                               0 }, // 22 Taxi Term group 2 exit a
-	{  104,   40, 0,                               0 }, // 23 Taxi Term group 2 exit b
-	{   56,   40, 0,                               0 }, // 24 Term group 2 exit 2a
-	{   40,   40, 0,                               0 }, // 25 Term group 2 exit 2b
-	{   40,  120, 0,                               0 }, // 26 Term group 1 - opp term 1
-	{   40,  104, 0,                               0 }, // 27 Term group 1 - opp term 2 & hangar area 1
-	{   40,   88, 0,                               0 }, // 28 Term group 1 - opp term 3
-	{   40,   72, 0,                               0 }, // 29 Term group 1 - opp term 4
-	{   18,   72, 0,                               7 }, // 30 Outway 1
-	{    8,   40, 0,                               7 }, // 31 Airport OUTWAY
-	{    8,   24, AMED_EXACTPOS,                   5 }, // 32 Accelerate to end of runway
-	{  119,   24, AMED_NOSPDCLAMP,                 0 }, // 33 Release control of runway, for smoother movement
-	{  117,   24, AMED_NOSPDCLAMP,                 0 }, // 34 End of runway
-	{  197,   24, AMED_NOSPDCLAMP | AMED_TAKEOFF,  0 }, // 35 Take off
-	{  254,   84, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 36 Flying to landing position in air
-	{  117,  168, AMED_NOSPDCLAMP | AMED_LAND,     0 }, // 37 Going down for land
-	{    3,  168, AMED_NOSPDCLAMP | AMED_BRAKE,    0 }, // 38 Just landed, brake until end of runway
-	{    8,  168, 0,                               0 }, // 39 Just landed, turn around and taxi
-	{    8,  144, 0,                               7 }, // 40 Taxi from runway
-	{    8,  128, 0,                               7 }, // 41 Taxi from runway
-	{    8,  120, AMED_EXACTPOS,                   5 }, // 42 Airport entrance
-	{   56,  344, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 43 Fly around waiting for a landing spot (north-east)
-	{ -200,   88, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 44 Fly around waiting for a landing spot (north-west)
-	{   56, -168, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 45 Fly around waiting for a landing spot (south-west)
-	{  312,   88, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 46 Fly around waiting for a landing spot (south)
+	{    7,   87, AMED_EXACTPOS,                   {DIR_SE} }, // 00 In Hangar 1
+	{  135,   72, AMED_EXACTPOS,                   {DIR_SE} }, // 01 In Hangar 2
+	{    7,  104, 0,                               {DIR_N} }, // 02 Taxi to right outside depot 1
+	{  135,   88, 0,                               {DIR_N} }, // 03 Taxi to right outside depot 2
+	{   56,  120, AMED_EXACTPOS,                   {DIR_W} }, // 04 Terminal 1
+	{   56,  104, AMED_EXACTPOS,                   {DIR_SW} }, // 05 Terminal 2
+	{   56,   88, AMED_EXACTPOS,                   {DIR_SW} }, // 06 Terminal 3
+	{   56,   72, AMED_EXACTPOS,                   {DIR_SW} }, // 07 Terminal 4
+	{   88,  120, AMED_EXACTPOS,                   {DIR_N} }, // 08 Terminal 5
+	{   88,  104, AMED_EXACTPOS,                   {DIR_NE} }, // 09 Terminal 6
+	{   88,   88, AMED_EXACTPOS,                   {DIR_NE} }, // 10 Terminal 7
+	{   88,   72, AMED_EXACTPOS,                   {DIR_NE} }, // 11 Terminal 8
+	{   88,   56, AMED_EXACTPOS,                   {DIR_SE} }, // 12 Helipad 1
+	{   72,   56, AMED_EXACTPOS,                   {DIR_NE} }, // 13 Helipad 2
+	{   40,  136, 0,                               {DIR_N} }, // 14 Term group 2 enter 1 a
+	{   56,  136, 0,                               {DIR_N} }, // 15 Term group 2 enter 1 b
+	{   88,  136, 0,                               {DIR_N} }, // 16 Term group 2 enter 2 a
+	{  104,  136, 0,                               {DIR_N} }, // 17 Term group 2 enter 2 b
+	{  104,  120, 0,                               {DIR_N} }, // 18 Term group 2 - opp term 5
+	{  104,  104, 0,                               {DIR_N} }, // 19 Term group 2 - opp term 6 & exit2
+	{  104,   88, 0,                               {DIR_N} }, // 20 Term group 2 - opp term 7 & hangar area 2
+	{  104,   72, 0,                               {DIR_N} }, // 21 Term group 2 - opp term 8
+	{  104,   56, 0,                               {DIR_N} }, // 22 Taxi Term group 2 exit a
+	{  104,   40, 0,                               {DIR_N} }, // 23 Taxi Term group 2 exit b
+	{   56,   40, 0,                               {DIR_N} }, // 24 Term group 2 exit 2a
+	{   40,   40, 0,                               {DIR_N} }, // 25 Term group 2 exit 2b
+	{   40,  120, 0,                               {DIR_N} }, // 26 Term group 1 - opp term 1
+	{   40,  104, 0,                               {DIR_N} }, // 27 Term group 1 - opp term 2 & hangar area 1
+	{   40,   88, 0,                               {DIR_N} }, // 28 Term group 1 - opp term 3
+	{   40,   72, 0,                               {DIR_N} }, // 29 Term group 1 - opp term 4
+	{   18,   72, 0,                               {DIR_NW} }, // 30 Outway 1
+	{    8,   40, 0,                               {DIR_NW} }, // 31 Airport OUTWAY
+	{    8,   24, AMED_EXACTPOS,                   {DIR_SW} }, // 32 Accelerate to end of runway
+	{  119,   24, AMED_NOSPDCLAMP,                 {DIR_N} }, // 33 Release control of runway, for smoother movement
+	{  117,   24, AMED_NOSPDCLAMP,                 {DIR_N} }, // 34 End of runway
+	{  197,   24, AMED_NOSPDCLAMP | AMED_TAKEOFF,  {DIR_N} }, // 35 Take off
+	{  254,   84, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 36 Flying to landing position in air
+	{  117,  168, AMED_NOSPDCLAMP | AMED_LAND,     {DIR_N} }, // 37 Going down for land
+	{    3,  168, AMED_NOSPDCLAMP | AMED_BRAKE,    {DIR_N} }, // 38 Just landed, brake until end of runway
+	{    8,  168, 0,                               {DIR_N} }, // 39 Just landed, turn around and taxi
+	{    8,  144, 0,                               {DIR_NW} }, // 40 Taxi from runway
+	{    8,  128, 0,                               {DIR_NW} }, // 41 Taxi from runway
+	{    8,  120, AMED_EXACTPOS,                   {DIR_SW} }, // 42 Airport entrance
+	{   56,  344, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 43 Fly around waiting for a landing spot (north-east)
+	{ -200,   88, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 44 Fly around waiting for a landing spot (north-west)
+	{   56, -168, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 45 Fly around waiting for a landing spot (south-west)
+	{  312,   88, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 46 Fly around waiting for a landing spot (south)
 	// Helicopter
-	{   96,   40, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 47 Bufferspace before helipad
-	{   96,   40, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 48 Bufferspace before helipad
-	{   82,   54, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 49 Get in position for Helipad1
-	{   64,   56, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 50 Get in position for Helipad2
-	{   81,   55, AMED_HELI_LOWER,                 0 }, // 51 Land at Helipad1
-	{   64,   56, AMED_HELI_LOWER,                 0 }, // 52 Land at Helipad2
-	{   80,   56, AMED_HELI_RAISE,                 0 }, // 53 Takeoff Helipad1
-	{   64,   56, AMED_HELI_RAISE,                 0 }, // 54 Takeoff Helipad2
-	{  136,   96, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 55 Go to position for Hangarentrance in air
-	{  136,   96, AMED_HELI_LOWER,                 0 }, // 56 Land in front of hangar2
-	{  126,  104, 0,                               3 }, // 57 Outway 2
-	{  136,  136, 0,                               1 }, // 58 Airport OUTWAY 2
-	{  136,  152, AMED_EXACTPOS,                   5 }, // 59 Accelerate to end of runway2
-	{   16,  152, AMED_NOSPDCLAMP,                 0 }, // 60 Release control of runway2, for smoother movement
-	{   20,  152, AMED_NOSPDCLAMP,                 0 }, // 61 End of runway2
-	{  -56,  152, AMED_NOSPDCLAMP | AMED_TAKEOFF,  0 }, // 62 Take off2
-	{   24,    8, AMED_NOSPDCLAMP | AMED_LAND,     0 }, // 63 Going down for land2
-	{  136,    8, AMED_NOSPDCLAMP | AMED_BRAKE,    0 }, // 64 Just landed, brake until end of runway2in
-	{  136,    8, 0,                               0 }, // 65 Just landed, turn around and taxi
-	{  136,   24, 0,                               3 }, // 66 Taxi from runway 2in
-	{  136,   40, 0,                               3 }, // 67 Taxi from runway 2in
-	{  136,   56, AMED_EXACTPOS,                   1 }, // 68 Airport entrance2
-	{  -56,    8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 69 Fly to landing position in air2
-	{   88,   40, 0,                               0 }, // 70 Taxi Term group 2 exit - opp heli1
-	{   72,   40, 0,                               0 }, // 71 Taxi Term group 2 exit - opp heli2
-	{   88,   57, AMED_EXACTPOS,                   3 }, // 72 pre-helitakeoff helipad 1
-	{   71,   56, AMED_EXACTPOS,                   1 }, // 73 pre-helitakeoff helipad 2
-	{    8,  120, AMED_HELI_RAISE,                 0 }, // 74 Helitakeoff outside depot 1
-	{  136,  104, AMED_HELI_RAISE,                 0 }, // 75 Helitakeoff outside depot 2
-	{  197,  168, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0} // 76 Fly to landing position in air1
+	{   96,   40, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 47 Bufferspace before helipad
+	{   96,   40, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 48 Bufferspace before helipad
+	{   82,   54, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 49 Get in position for Helipad1
+	{   64,   56, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 50 Get in position for Helipad2
+	{   81,   55, AMED_HELI_LOWER,                 {DIR_N} }, // 51 Land at Helipad1
+	{   64,   56, AMED_HELI_LOWER,                 {DIR_N} }, // 52 Land at Helipad2
+	{   80,   56, AMED_HELI_RAISE,                 {DIR_N} }, // 53 Takeoff Helipad1
+	{   64,   56, AMED_HELI_RAISE,                 {DIR_N} }, // 54 Takeoff Helipad2
+	{  136,   96, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 55 Go to position for Hangarentrance in air
+	{  136,   96, AMED_HELI_LOWER,                 {DIR_N} }, // 56 Land in front of hangar2
+	{  126,  104, 0,                               {DIR_SE} }, // 57 Outway 2
+	{  136,  136, 0,                               {DIR_NE} }, // 58 Airport OUTWAY 2
+	{  136,  152, AMED_EXACTPOS,                   {DIR_SW} }, // 59 Accelerate to end of runway2
+	{   16,  152, AMED_NOSPDCLAMP,                 {DIR_N} }, // 60 Release control of runway2, for smoother movement
+	{   20,  152, AMED_NOSPDCLAMP,                 {DIR_N} }, // 61 End of runway2
+	{  -56,  152, AMED_NOSPDCLAMP | AMED_TAKEOFF,  {DIR_N} }, // 62 Take off2
+	{   24,    8, AMED_NOSPDCLAMP | AMED_LAND,     {DIR_N} }, // 63 Going down for land2
+	{  136,    8, AMED_NOSPDCLAMP | AMED_BRAKE,    {DIR_N} }, // 64 Just landed, brake until end of runway2in
+	{  136,    8, 0,                               {DIR_N} }, // 65 Just landed, turn around and taxi
+	{  136,   24, 0,                               {DIR_SE} }, // 66 Taxi from runway 2in
+	{  136,   40, 0,                               {DIR_SE} }, // 67 Taxi from runway 2in
+	{  136,   56, AMED_EXACTPOS,                   {DIR_NE} }, // 68 Airport entrance2
+	{  -56,    8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 69 Fly to landing position in air2
+	{   88,   40, 0,                               {DIR_N} }, // 70 Taxi Term group 2 exit - opp heli1
+	{   72,   40, 0,                               {DIR_N} }, // 71 Taxi Term group 2 exit - opp heli2
+	{   88,   57, AMED_EXACTPOS,                   {DIR_SE} }, // 72 pre-helitakeoff helipad 1
+	{   71,   56, AMED_EXACTPOS,                   {DIR_NE} }, // 73 pre-helitakeoff helipad 2
+	{    8,  120, AMED_HELI_RAISE,                 {DIR_N} }, // 74 Helitakeoff outside depot 1
+	{  136,  104, AMED_HELI_RAISE,                 {DIR_N} }, // 75 Helitakeoff outside depot 2
+	{  197,  168, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 76 Fly to landing position in air1
 };
 
 
 // Heliport (heliport)
 static const AirportMovingData _airport_moving_data_heliport[9] = {
-	{    5,    9, AMED_EXACTPOS,                   1 }, // 0 - At heliport terminal
-	{    2,    9, AMED_HELI_RAISE,                 0 }, // 1 - Take off (play sound)
-	{   -3,    9, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 2 - In position above landing spot helicopter
-	{   -3,    9, AMED_HELI_LOWER,                 0 }, // 3 - Land
-	{    2,    9, 0,                               0 }, // 4 - Goto terminal on ground
-	{  -31,   59, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 5 - Circle #1 (north-east)
-	{  -31,  -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 6 - Circle #2 (north-west)
-	{   49,  -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 7 - Circle #3 (south-west)
-	{   70,    9, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 8 - Circle #4 (south)
+	{    5,    9, AMED_EXACTPOS,                   {DIR_NE} }, // 0 - At heliport terminal
+	{    2,    9, AMED_HELI_RAISE,                 {DIR_N} }, // 1 - Take off (play sound)
+	{   -3,    9, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 2 - In position above landing spot helicopter
+	{   -3,    9, AMED_HELI_LOWER,                 {DIR_N} }, // 3 - Land
+	{    2,    9, 0,                               {DIR_N} }, // 4 - Goto terminal on ground
+	{  -31,   59, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 5 - Circle #1 (north-east)
+	{  -31,  -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 6 - Circle #2 (north-west)
+	{   49,  -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 7 - Circle #3 (south-west)
+	{   70,    9, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 8 - Circle #4 (south)
 };
 
 // HeliDepot 2x2 (heliport)
 static const AirportMovingData _airport_moving_data_helidepot[18] = {
-	{   24,    4, AMED_EXACTPOS,                   1 }, // 0 - At depot
-	{   24,   28, 0,                               0 }, // 1 Taxi to right outside depot
-	{    5,   38, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 2 Flying
-	{  -15,  -15, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 3 - Circle #1 (north-east)
-	{  -15,  -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 4 - Circle #2 (north-west)
-	{   49,  -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 5 - Circle #3 (south-west)
-	{   49,  -15, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 6 - Circle #4 (south-east)
-	{    8,   32, AMED_NOSPDCLAMP | AMED_SLOWTURN, 7 }, // 7 - PreHelipad
-	{    8,   32, AMED_NOSPDCLAMP | AMED_SLOWTURN, 7 }, // 8 - Helipad
-	{    8,   16, AMED_NOSPDCLAMP | AMED_SLOWTURN, 7 }, // 9 - Land
-	{    8,   16, AMED_HELI_LOWER,                 7 }, // 10 - Land
-	{    8,   24, AMED_HELI_RAISE,                 0 }, // 11 - Take off (play sound)
-	{   32,   24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 7 }, // 12 Air to above hangar area
-	{   32,   24, AMED_HELI_LOWER,                 7 }, // 13 Taxi to right outside depot
-	{    8,   24, AMED_EXACTPOS,                   7 }, // 14 - on helipad1
-	{   24,   28, AMED_HELI_RAISE,                 0 }, // 15 Takeoff right outside depot
-	{    8,   24, AMED_HELI_RAISE,                 5 }, // 16 - Take off (play sound)
-	{    8,   24, AMED_SLOWTURN | AMED_EXACTPOS,   2 }, // 17 - turn on helipad1 for takeoff
+	{   24,    4, AMED_EXACTPOS,                   {DIR_NE} }, // 0 - At depot
+	{   24,   28, 0,                               {DIR_N} }, // 1 Taxi to right outside depot
+	{    5,   38, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 2 Flying
+	{  -15,  -15, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 3 - Circle #1 (north-east)
+	{  -15,  -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 4 - Circle #2 (north-west)
+	{   49,  -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 5 - Circle #3 (south-west)
+	{   49,  -15, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 6 - Circle #4 (south-east)
+	{    8,   32, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_NW} }, // 7 - PreHelipad
+	{    8,   32, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_NW} }, // 8 - Helipad
+	{    8,   16, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_NW} }, // 9 - Land
+	{    8,   16, AMED_HELI_LOWER,                 {DIR_NW} }, // 10 - Land
+	{    8,   24, AMED_HELI_RAISE,                 {DIR_N} }, // 11 - Take off (play sound)
+	{   32,   24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_NW} }, // 12 Air to above hangar area
+	{   32,   24, AMED_HELI_LOWER,                 {DIR_NW} }, // 13 Taxi to right outside depot
+	{    8,   24, AMED_EXACTPOS,                   {DIR_NW} }, // 14 - on helipad1
+	{   24,   28, AMED_HELI_RAISE,                 {DIR_N} }, // 15 Takeoff right outside depot
+	{    8,   24, AMED_HELI_RAISE,                 {DIR_SW} }, // 16 - Take off (play sound)
+	{    8,   24, AMED_SLOWTURN | AMED_EXACTPOS,   {DIR_E} }, // 17 - turn on helipad1 for takeoff
 };
 
 // HeliDepot 2x2 (heliport)
 static const AirportMovingData _airport_moving_data_helistation[33] = {
-	{    8,    3, AMED_EXACTPOS,                   3 }, // 00 In Hangar2
-	{    8,   22, 0,                               0 }, // 01 outside hangar 2
-	{  116,   24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 02 Fly to landing position in air
-	{   14,   22, AMED_HELI_RAISE,                 0 }, // 03 Helitakeoff outside hangar1(play sound)
-	{   24,   22, 0,                               0 }, // 04 taxiing
-	{   40,   22, 0,                               0 }, // 05 taxiing
-	{   40,    8, AMED_EXACTPOS,                   1 }, // 06 Helipad 1
-	{   56,    8, AMED_EXACTPOS,                   1 }, // 07 Helipad 2
-	{   56,   24, AMED_EXACTPOS,                   1 }, // 08 Helipad 3
-	{   40,    8, AMED_EXACTPOS,                   0 }, // 09 pre-helitakeoff helipad 1
-	{   56,    8, AMED_EXACTPOS,                   0 }, // 10 pre-helitakeoff helipad 2
-	{   56,   24, AMED_EXACTPOS,                   0 }, // 11 pre-helitakeoff helipad 3
-	{   32,    8, AMED_HELI_RAISE,                 0 }, // 12 Takeoff Helipad1
-	{   48,    8, AMED_HELI_RAISE,                 0 }, // 13 Takeoff Helipad2
-	{   48,   24, AMED_HELI_RAISE,                 0 }, // 14 Takeoff Helipad3
-	{   84,   24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 15 Bufferspace before helipad
-	{   68,   24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 16 Bufferspace before helipad
-	{   32,    8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 17 Get in position for Helipad1
-	{   48,    8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 18 Get in position for Helipad2
-	{   48,   24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 1 }, // 19 Get in position for Helipad3
-	{   40,    8, AMED_HELI_LOWER,                 0 }, // 20 Land at Helipad1
-	{   48,    8, AMED_HELI_LOWER,                 0 }, // 21 Land at Helipad2
-	{   48,   24, AMED_HELI_LOWER,                 0 }, // 22 Land at Helipad3
-	{    0,   22, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 23 Go to position for Hangarentrance in air
-	{    0,   22, AMED_HELI_LOWER,                 0 }, // 24 Land in front of hangar
-	{  148,   -8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 25 Fly around waiting for a landing spot (south-east)
-	{  148,    8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 26 Fly around waiting for a landing spot (south-west)
-	{  132,   24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 27 Fly around waiting for a landing spot (south-west)
-	{  100,   24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 28 Fly around waiting for a landing spot (north-east)
-	{   84,    8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 29 Fly around waiting for a landing spot (south-east)
-	{   84,   -8, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 30 Fly around waiting for a landing spot (south-west)
-	{  100,  -24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 31 Fly around waiting for a landing spot (north-west)
-	{  132,  -24, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 32 Fly around waiting for a landing spot (north-east)
+	{    8,    3, AMED_EXACTPOS,                   {DIR_SE} }, // 00 In Hangar2
+	{    8,   22, 0,                               {DIR_N} }, // 01 outside hangar 2
+	{  116,   24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 02 Fly to landing position in air
+	{   14,   22, AMED_HELI_RAISE,                 {DIR_N} }, // 03 Helitakeoff outside hangar1(play sound)
+	{   24,   22, 0,                               {DIR_N} }, // 04 taxiing
+	{   40,   22, 0,                               {DIR_N} }, // 05 taxiing
+	{   40,    8, AMED_EXACTPOS,                   {DIR_NE} }, // 06 Helipad 1
+	{   56,    8, AMED_EXACTPOS,                   {DIR_NE} }, // 07 Helipad 2
+	{   56,   24, AMED_EXACTPOS,                   {DIR_NE} }, // 08 Helipad 3
+	{   40,    8, AMED_EXACTPOS,                   {DIR_N} }, // 09 pre-helitakeoff helipad 1
+	{   56,    8, AMED_EXACTPOS,                   {DIR_N} }, // 10 pre-helitakeoff helipad 2
+	{   56,   24, AMED_EXACTPOS,                   {DIR_N} }, // 11 pre-helitakeoff helipad 3
+	{   32,    8, AMED_HELI_RAISE,                 {DIR_N} }, // 12 Takeoff Helipad1
+	{   48,    8, AMED_HELI_RAISE,                 {DIR_N} }, // 13 Takeoff Helipad2
+	{   48,   24, AMED_HELI_RAISE,                 {DIR_N} }, // 14 Takeoff Helipad3
+	{   84,   24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 15 Bufferspace before helipad
+	{   68,   24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 16 Bufferspace before helipad
+	{   32,    8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 17 Get in position for Helipad1
+	{   48,    8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 18 Get in position for Helipad2
+	{   48,   24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_NE} }, // 19 Get in position for Helipad3
+	{   40,    8, AMED_HELI_LOWER,                 {DIR_N} }, // 20 Land at Helipad1
+	{   48,    8, AMED_HELI_LOWER,                 {DIR_N} }, // 21 Land at Helipad2
+	{   48,   24, AMED_HELI_LOWER,                 {DIR_N} }, // 22 Land at Helipad3
+	{    0,   22, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 23 Go to position for Hangarentrance in air
+	{    0,   22, AMED_HELI_LOWER,                 {DIR_N} }, // 24 Land in front of hangar
+	{  148,   -8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 25 Fly around waiting for a landing spot (south-east)
+	{  148,    8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 26 Fly around waiting for a landing spot (south-west)
+	{  132,   24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 27 Fly around waiting for a landing spot (south-west)
+	{  100,   24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 28 Fly around waiting for a landing spot (north-east)
+	{   84,    8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 29 Fly around waiting for a landing spot (south-east)
+	{   84,   -8, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 30 Fly around waiting for a landing spot (south-west)
+	{  100,  -24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 31 Fly around waiting for a landing spot (north-west)
+	{  132,  -24, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 32 Fly around waiting for a landing spot (north-east)
 };
 
 // Oilrig
 static const AirportMovingData _airport_moving_data_oilrig[9] = {
-	{   31,    9, AMED_EXACTPOS,                   1 }, // 0 - At oilrig terminal
-	{   28,    9, AMED_HELI_RAISE,                 0 }, // 1 - Take off (play sound)
-	{   23,    9, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 2 - In position above landing spot helicopter
-	{   23,    9, AMED_HELI_LOWER,                 0 }, // 3 - Land
-	{   28,    9, 0,                               0 }, // 4 - Goto terminal on ground
-	{  -31,   69, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 5 - circle #1 (north-east)
-	{  -31,  -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 6 - circle #2 (north-west)
-	{   69,  -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 7 - circle #3 (south-west)
-	{   70,    9, AMED_NOSPDCLAMP | AMED_SLOWTURN, 0 }, // 8 - circle #4 (south)
+	{   31,    9, AMED_EXACTPOS,                   {DIR_NE} }, // 0 - At oilrig terminal
+	{   28,    9, AMED_HELI_RAISE,                 {DIR_N} }, // 1 - Take off (play sound)
+	{   23,    9, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 2 - In position above landing spot helicopter
+	{   23,    9, AMED_HELI_LOWER,                 {DIR_N} }, // 3 - Land
+	{   28,    9, 0,                               {DIR_N} }, // 4 - Goto terminal on ground
+	{  -31,   69, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 5 - circle #1 (north-east)
+	{  -31,  -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 6 - circle #2 (north-west)
+	{   69,  -49, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 7 - circle #3 (south-west)
+	{   70,    9, AMED_NOSPDCLAMP | AMED_SLOWTURN, {DIR_N} }, // 8 - circle #4 (south)
 };
 
 ///////////////////////////////////////////////////////////////////////
--- a/src/aystar.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/aystar.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -19,6 +19,7 @@
 #include "stdafx.h"
 #include "openttd.h"
 #include "aystar.h"
+#include "helpers.hpp"
 
 int _aystar_stats_open_size;
 int _aystar_stats_closed_size;
@@ -35,7 +36,8 @@
 static void AyStarMain_ClosedList_Add(AyStar *aystar, const PathNode *node)
 {
 	// Add a node to the ClosedList
-	PathNode *new_node = malloc(sizeof(*new_node));
+	PathNode *new_node;
+	MallocT(&new_node, 1);
 	*new_node = *node;
 	Hash_Set(&aystar->ClosedListHash, node->node.tile, node->node.direction, new_node);
 }
@@ -66,7 +68,8 @@
 static void AyStarMain_OpenList_Add(AyStar *aystar, PathNode *parent, const AyStarNode *node, int f, int g)
 {
 	// Add a new Node to the OpenList
-	OpenListNode *new_node = malloc(sizeof(*new_node));
+	OpenListNode *new_node;
+	MallocT(&new_node, 1);
 	new_node->g = g;
 	new_node->path.parent = parent;
 	new_node->path.node = *node;
--- a/src/aystar.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/aystar.h	Mon Jan 15 20:14:06 2007 +0000
@@ -30,7 +30,7 @@
 typedef struct AyStarNode AyStarNode;
 struct AyStarNode {
 	TileIndex tile;
-	uint direction;
+	int direction;
 	uint user_data[2];
 };
 
--- a/src/bmp.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/bmp.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -5,6 +5,7 @@
 #include "gfx.h"
 #include "bmp.h"
 #include "macros.h"
+#include "helpers.hpp"
 
 void BmpInitializeBuffer(BmpBuffer *buffer, FILE *file) {
 	buffer->pos      = -1;
@@ -328,7 +329,7 @@
 		}
 		if (info->palette_size == 0) info->palette_size = 1 << info->bpp;
 
-		data->palette = calloc(info->palette_size, sizeof(*(data->palette)));
+		CallocT(&data->palette, info->palette_size);
 		if (data->palette == NULL) return false;
 
 		for (i = 0; i < info->palette_size; i++) {
@@ -350,7 +351,7 @@
 {
 	assert(info != NULL && data != NULL);
 
-	data->bitmap = calloc(info->width * info->height, ((info->bpp == 24) ? 3 : 1) * sizeof(byte));
+	data->bitmap = (byte*)calloc(info->width * info->height, ((info->bpp == 24) ? 3 : 1) * sizeof(byte));
 	if (data->bitmap == NULL) return false;
 
 	/* Load image */
--- a/src/bridge_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/bridge_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -190,11 +190,11 @@
 
 	// type of bridge
 	if (HASBIT(p2, 15)) {
-		railtype = 0;
+		railtype = RAILTYPE_BEGIN;
 		transport = TRANSPORT_ROAD;
 	} else {
 		if (!ValParamRailtype(GB(p2, 8, 8))) return CMD_ERROR;
-		railtype = GB(p2, 8, 8);
+		railtype = (RailType)GB(p2, 8, 8);
 		transport = TRANSPORT_RAIL;
 	}
 
@@ -833,7 +833,7 @@
 			} else if (f < 15) {
 				return z + TILE_HEIGHT;
 			}
-			tileh = _inclined_tileh[f - 15];
+			tileh = (Slope)_inclined_tileh[f - 15];
 		}
 	}
 	return z + GetPartialZ(x, y, tileh);
@@ -848,7 +848,7 @@
 
 		if (f == 0) return tileh;
 		if (f < 15) return SLOPE_FLAT;
-		return _inclined_tileh[f - 15];
+		return (Slope)_inclined_tileh[f - 15];
 	}
 }
 
@@ -1018,7 +1018,7 @@
 
 	if (v->direction == DiagDirToDir(ReverseDiagDir(dir))) {
 		/* We are entering the bridge head from the bridge itself */
-		if (v->u.rail.track == 0x40) {
+		if (v->u.rail.track == TRACK_BIT_WORMHOLE) {
 			/* Get the vehicle out of the wormhole, the track will be chosen later
 			   by the pathfinder */
 			v->tile = tile;
@@ -1046,7 +1046,7 @@
 			if (diff.x != 0) v->y_pos = y; else v->x_pos = x;
 			v->direction = DiagDirToDir(dir);
 			/* We're about to enter the bridge body, clear all up/down flags just in case */
-			v->u.rail.track = 0x40;
+			v->u.rail.track = TRACK_BIT_WORMHOLE;
 			v->direction = DiagDirToDir(dir);
 			CLRBIT(v->u.rail.flags, VRF_GOINGUP);
 			CLRBIT(v->u.rail.flags, VRF_GOINGDOWN);
@@ -1068,7 +1068,7 @@
 	NOT_REACHED();
 }
 
-const TileTypeProcs _tile_type_bridge_procs = {
+extern const TileTypeProcs _tile_type_bridge_procs = {
 	DrawTile_Bridge,           /* draw_tile_proc */
 	GetSlopeZ_Bridge,          /* get_slope_z_proc */
 	ClearTile_Bridge,          /* clear_tile_proc */
--- a/src/bridge_map.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/bridge_map.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -40,7 +40,7 @@
 uint GetBridgeHeight(TileIndex t)
 {
 	uint h;
-	uint tileh = GetTileSlope(t, &h);
+	Slope tileh = GetTileSlope(t, &h);
 	uint f = GetBridgeFoundation(tileh, DiagDirToAxis(GetBridgeRampDirection(t)));
 
 	// one height level extra if the ramp is on a flat foundation
--- a/src/build_vehicle_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/build_vehicle_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -302,6 +302,8 @@
 					break;
 
 				case ALL: break;
+				default:
+					NOT_REACHED();
 			}
 			EngList_Add(&bv->eng_list, eid);
 
@@ -479,7 +481,7 @@
 
 	switch (type) {
 		case VEH_Aircraft: {
-			byte acc_planes = (tile == 0) ? ALL : GetAirport(GetStationByTile(tile)->airport_type)->acc_planes;
+			AcceptPlanes acc_planes = (tile == 0) ? ALL : GetAirport(GetStationByTile(tile)->airport_type)->acc_planes;
 			bv->filter.acc_planes = acc_planes;
 			break;
 		}
--- a/src/clear_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/clear_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -548,7 +548,7 @@
 static uint GetSlopeZ_Clear(TileIndex tile, uint x, uint y)
 {
 	uint z;
-	uint tileh = GetTileSlope(tile, &z);
+	Slope tileh = GetTileSlope(tile, &z);
 
 	return z + GetPartialZ(x & 0xF, y & 0xF, tileh);
 }
@@ -786,7 +786,7 @@
 	_opt.snow_line = _patches.snow_line_height * TILE_HEIGHT;
 }
 
-const TileTypeProcs _tile_type_clear_procs = {
+extern const TileTypeProcs _tile_type_clear_procs = {
 	DrawTile_Clear,           /* draw_tile_proc */
 	GetSlopeZ_Clear,          /* get_slope_z_proc */
 	ClearTile_Clear,          /* clear_tile_proc */
--- a/src/clear_map.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/clear_map.h	Mon Jan 15 20:14:06 2007 +0000
@@ -23,7 +23,7 @@
 static inline ClearGround GetClearGround(TileIndex t)
 {
 	assert(IsTileType(t, MP_CLEAR));
-	return GB(_m[t].m5, 2, 3);
+	return (ClearGround)GB(_m[t].m5, 2, 3);
 }
 
 static inline bool IsClearGround(TileIndex t, ClearGround ct)
--- a/src/command.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/command.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -504,7 +504,7 @@
 	 */
 	if (_networking && !(cmd & CMD_NETWORK_COMMAND)) {
 		PlayerID pbck = _local_player;
-		if (_network_dedicated || (_network_server && pbck == PLAYER_SPECTATOR)) _local_player = 0;
+		if (_network_dedicated || (_network_server && pbck == PLAYER_SPECTATOR)) _local_player = PLAYER_FIRST;
 		NetworkSend_Command(tile, p1, p2, cmd, callback);
 		if (_network_dedicated || (_network_server && pbck == PLAYER_SPECTATOR)) _local_player = pbck;
 		_docommand_recursive = 0;
--- a/src/console.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/console.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -13,6 +13,7 @@
 #include <stdarg.h>
 #include <string.h>
 #include "console.h"
+#include "helpers.hpp"
 #include "network/network.h"
 #include "network/network_data.h"
 #include "network/network_server.h"
@@ -223,7 +224,7 @@
 	memset(_iconsole_history, 0, sizeof(_iconsole_history));
 	memset(_iconsole_buffer, 0, sizeof(_iconsole_buffer));
 	memset(_iconsole_cbuffer, 0, sizeof(_iconsole_cbuffer));
-	_iconsole_cmdline.buf = calloc(ICON_CMDLN_SIZE, sizeof(*_iconsole_cmdline.buf)); // create buffer and zero it
+	CallocT(&_iconsole_cmdline.buf, ICON_CMDLN_SIZE); // create buffer and zero it
 	_iconsole_cmdline.maxlength = ICON_CMDLN_SIZE;
 
 	IConsolePrintF(13, "OpenTTD Game Console Revision 7 - %s", _openttd_revision);
@@ -612,7 +613,8 @@
 void IConsoleCmdRegister(const char *name, IConsoleCmdProc *proc)
 {
 	char *new_cmd = strdup(name);
-	IConsoleCmd *item_new = malloc(sizeof(IConsoleCmd));
+	IConsoleCmd *item_new;
+	MallocT(&item_new, 1);
 
 	item_new->next = NULL;
 	item_new->proc = proc;
@@ -649,7 +651,8 @@
 {
 	char *new_alias = strdup(name);
 	char *cmd_aliased = strdup(cmd);
-	IConsoleAlias *item_new = malloc(sizeof(IConsoleAlias));
+	IConsoleAlias *item_new;
+	MallocT(&item_new, 1);
 
 	item_new->next = NULL;
 	item_new->cmdline = cmd_aliased;
@@ -784,7 +787,8 @@
 void IConsoleVarRegister(const char *name, void *addr, IConsoleVarTypes type, const char *help)
 {
 	char *new_cmd = strdup(name);
-	IConsoleVar *item_new = malloc(sizeof(IConsoleVar));
+	IConsoleVar *item_new;
+	MallocT(&item_new, 1);
 
 	item_new->help = (help != NULL) ? strdup(help) : NULL;
 
@@ -861,7 +865,7 @@
 	if (var->type != ICONSOLE_VAR_STRING || var->addr == NULL) return;
 
 	IConsoleHookHandle(&var->hook, ICONSOLE_HOOK_PRE_ACTION);
-	ttd_strlcpy(var->addr, value, var->size);
+	ttd_strlcpy((char*)var->addr, value, var->size);
 	IConsoleHookHandle(&var->hook, ICONSOLE_HOOK_POST_ACTION);
 	IConsoleVarPrintSetValue(var); // print out the new value, giving feedback
 	return;
--- a/src/console_cmds.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/console_cmds.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -562,7 +562,7 @@
 		const NetworkClientInfo *ci = DEREF_CLIENT_INFO(cs);
 		const char* status;
 
-		status = (cs->status < lengthof(stat_str) ? stat_str[cs->status] : "unknown");
+		status = (cs->status < (ptrdiff_t)lengthof(stat_str) ? stat_str[cs->status] : "unknown");
 		IConsolePrintF(8, "Client #%1d  name: '%s'  status: '%s'  frame-lag: %3d  company: %1d  IP: %s  unique-id: '%s'",
 			cs->index, ci->client_name, status, lag,
 			ci->client_playas + (IsValidPlayer(ci->client_playas) ? 1 : 0),
@@ -684,7 +684,7 @@
 
 	if (argc != 2) return false;
 
-	index = atoi(argv[1]) - 1;
+	index = (PlayerID)(atoi(argv[1]) - 1);
 
 	/* Check valid range */
 	if (!IsValidPlayer(index)) {
@@ -770,7 +770,7 @@
 
 	IConsolePrintF(_icolour_def, "Connecting to %s...", ip);
 	if (player != NULL) {
-		_network_playas = atoi(player);
+		_network_playas = (PlayerID)atoi(player);
 		IConsolePrintF(_icolour_def, "    player-no: %d", _network_playas);
 
 		/* From a user pov 0 is a new player, internally it's different and all
--- a/src/debug.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/debug.h	Mon Jan 15 20:14:06 2007 +0000
@@ -3,6 +3,10 @@
 #ifndef DEBUG_H
 #define DEBUG_H
 
+#ifdef __cplusplus
+extern "C" {
+#endif //__cplusplus
+
 /* Debugging messages policy:
  * These should be the severities used for direct DEBUG() calls
  * maximum debugging level should be 10 if really deep, deep
@@ -105,4 +109,8 @@
 	}\
 }
 
+#ifdef __cplusplus
+}
+#endif //__cplusplus
+
 #endif /* DEBUG_H */
--- a/src/depot.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/depot.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -122,6 +122,6 @@
 	}
 }
 
-const ChunkHandler _depot_chunk_handlers[] = {
+extern const ChunkHandler _depot_chunk_handlers[] = {
 	{ 'DEPT', Save_DEPT, Load_DEPT, CH_ARRAY | CH_LAST},
 };
--- a/src/direction.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/direction.h	Mon Jan 15 20:14:06 2007 +0000
@@ -3,8 +3,11 @@
 #ifndef DIRECTION_H
 #define DIRECTION_H
 
+#include "helpers.hpp"
+
 /* Direction as commonly used in v->direction, 8 way. */
 typedef enum Direction {
+	DIR_BEGIN = 0,
 	DIR_N   = 0,
 	DIR_NE  = 1,      /* Northeast, upper right on your monitor */
 	DIR_E   = 2,
@@ -17,6 +20,10 @@
 	INVALID_DIR = 0xFF,
 } Direction;
 
+/** Define basic enum properties */
+template <> struct EnumPropsT<Direction> : MakeEnumPropsT<Direction, byte, DIR_BEGIN, DIR_END, INVALID_DIR> {};
+typedef TinyEnumT<Direction> DirectionByte;
+
 static inline Direction ReverseDir(Direction d)
 {
 	return (Direction)(4 ^ d);
@@ -51,6 +58,7 @@
 
 /* Direction commonly used as the direction of entering and leaving tiles, 4-way */
 typedef enum DiagDirection {
+	DIAGDIR_BEGIN = 0,
 	DIAGDIR_NE  = 0,      /* Northeast, upper right on your monitor */
 	DIAGDIR_SE  = 1,
 	DIAGDIR_SW  = 2,
@@ -59,6 +67,12 @@
 	INVALID_DIAGDIR = 0xFF,
 } DiagDirection;
 
+DECLARE_POSTFIX_INCREMENT(DiagDirection);
+
+/** Define basic enum properties */
+template <> struct EnumPropsT<DiagDirection> : MakeEnumPropsT<DiagDirection, byte, DIAGDIR_BEGIN, DIAGDIR_END, INVALID_DIAGDIR> {};
+typedef TinyEnumT<DiagDirection> DiagDirectionByte;
+
 static inline DiagDirection ReverseDiagDir(DiagDirection d)
 {
 	return (DiagDirection)(2 ^ d);
--- a/src/disaster_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/disaster_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -276,7 +276,7 @@
 // fly around randomly
 		int x = TileX(v->dest_tile) * TILE_SIZE;
 		int y = TileY(v->dest_tile) * TILE_SIZE;
-		if (abs(x - v->x_pos) + abs(y - v->y_pos) >= TILE_SIZE) {
+		if (delta(x, v->x_pos) + delta(y, v->y_pos) >= TILE_SIZE) {
 			v->direction = GetDirectionTowards(v, x, y);
 			GetNewVehiclePos(v, &gp);
 			SetDisasterVehiclePos(v, gp.x, gp.y, v->z_pos);
@@ -305,7 +305,7 @@
 			return;
 		}
 
-		dist = abs(v->x_pos - u->x_pos) + abs(v->y_pos - u->y_pos);
+		dist = delta(v->x_pos, u->x_pos) + delta(v->y_pos, u->y_pos);
 
 		if (dist < TILE_SIZE && !(u->vehstatus&VS_HIDDEN) && u->breakdown_ctr==0) {
 			u->breakdown_ctr = 3;
@@ -526,7 +526,7 @@
 	if (v->current_order.dest == 1) {
 		int x = TileX(v->dest_tile) * TILE_SIZE + TILE_SIZE / 2;
 		int y = TileY(v->dest_tile) * TILE_SIZE + TILE_SIZE / 2;
-		if (abs(v->x_pos - x) + abs(v->y_pos - y) >= 8) {
+		if (delta(v->x_pos, x) + delta(v->y_pos, y) >= 8) {
 			v->direction = GetDirectionTowards(v, x, y);
 
 			GetNewVehiclePos(v, &gp);
@@ -544,7 +544,7 @@
 
 		FOR_ALL_VEHICLES(u) {
 			if (u->type == VEH_Train || u->type == VEH_Road) {
-				if (abs(u->x_pos - v->x_pos) + abs(u->y_pos - v->y_pos) <= 12 * TILE_SIZE) {
+				if (delta(u->x_pos, v->x_pos) + delta(u->y_pos, v->y_pos) <= 12 * TILE_SIZE) {
 					u->breakdown_ctr = 5;
 					u->breakdown_delay = 0xF0;
 				}
@@ -578,7 +578,7 @@
 
 		int x = TileX(v->dest_tile) * TILE_SIZE;
 		int y = TileY(v->dest_tile) * TILE_SIZE;
-		if (abs(x - v->x_pos) + abs(y - v->y_pos) >= TILE_SIZE) {
+		if (delta(x, v->x_pos) + delta(y, v->y_pos) >= TILE_SIZE) {
 			v->direction = GetDirectionTowards(v, x, y);
 			GetNewVehiclePos(v, &gp);
 			SetDisasterVehiclePos(v, gp.x, gp.y, v->z_pos);
@@ -626,7 +626,7 @@
 
 	if (v->current_order.dest == 0) {
 		u = GetVehicle(v->u.disaster.unk2);
-		if (abs(v->x_pos - u->x_pos) > TILE_SIZE)
+		if (delta(v->x_pos, u->x_pos) > TILE_SIZE)
 			return;
 		v->current_order.dest = 1;
 
--- a/src/dock_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/dock_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -254,7 +254,7 @@
 			case 3:
 			case 4:
 				RaiseWindowWidget(w, _station_show_coverage + 3);
-				_station_show_coverage = e->we.click.widget - 3;
+				_station_show_coverage = (e->we.click.widget != 3);
 				LowerWindowWidget(w, _station_show_coverage + 3);
 				SndPlayFx(SND_15_BEEP);
 				SetWindowDirty(w);
@@ -328,7 +328,7 @@
 		case 3:
 		case 4:
 			RaiseWindowWidget(w, _ship_depot_direction + 3);
-			_ship_depot_direction = e->we.click.widget - 3;
+			_ship_depot_direction = (e->we.click.widget == 3 ? AXIS_X : AXIS_Y);
 			LowerWindowWidget(w, _ship_depot_direction + 3);
 			SndPlayFx(SND_15_BEEP);
 			UpdateDocksDirection();
--- a/src/dummy_land.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/dummy_land.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -66,7 +66,7 @@
 	return 0;
 }
 
-const TileTypeProcs _tile_type_dummy_procs = {
+extern const TileTypeProcs _tile_type_dummy_procs = {
 	DrawTile_Dummy,           /* draw_tile_proc */
 	GetSlopeZ_Dummy,          /* get_slope_z_proc */
 	ClearTile_Dummy,          /* clear_tile_proc */
--- a/src/economy.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/economy.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -47,7 +47,7 @@
 	{ SCORE_TOTAL,             0,   0 }
 };
 
-int _score_part[MAX_PLAYERS][NUM_SCORE];
+int _score_part[MAX_PLAYERS][SCORE_END];
 
 int64 CalculateCompanyValue(const Player* p)
 {
@@ -209,11 +209,10 @@
 
 	// Now we calculate the score for each item..
 	{
-		int i;
 		int total_score = 0;
 		int s;
 		score = 0;
-		for (i = 0; i < NUM_SCORE; i++) {
+		for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) {
 			// Skip the total
 			if (i == SCORE_TOTAL) continue;
 			// Check the score
@@ -467,7 +466,7 @@
 
 	DrawNewsBorder(w);
 
-	p = GetPlayer(GB(WP(w,news_d).ni->string_id, 0, 4));
+	p = GetPlayer((PlayerID)GB(WP(w,news_d).ni->string_id, 0, 4));
 	DrawPlayerFace(p->face, p->player_color, 2, 23);
 	GfxFillRect(3, 23, 3+91, 23+118, 0x323 | USE_COLORTABLE);
 
@@ -536,7 +535,7 @@
 
 StringID GetNewsStringBankrupcy(const NewsItem *ni)
 {
-	const Player *p = GetPlayer(GB(ni->string_id, 0, 4));
+	const Player *p = GetPlayer((PlayerID)GB(ni->string_id, 0, 4));
 
 	switch (ni->string_id & 0xF0) {
 	case NB_BTROUBLE:
@@ -1562,7 +1561,7 @@
 static void DoAcquireCompany(Player *p)
 {
 	Player *owner;
-	int i,pi;
+	int i;
 	int64 value;
 
 	SetDParam(0, p->name_1);
@@ -1571,7 +1570,7 @@
 	AddNewsItem( (StringID)(_current_player | NB_BMERGER), NEWS_FLAGS(NM_CALLBACK, 0, NT_COMPANY_INFO, DNC_BANKRUPCY),0,0);
 
 	// original code does this a little bit differently
-	pi = p->index;
+	PlayerID pi = p->index;
 	ChangeOwnershipOfPlayerItems(pi, _current_player);
 
 	if (p->bankrupt_value == 0) {
@@ -1595,7 +1594,7 @@
 	RebuildVehicleLists(); //Updates the open windows to add the newly acquired vehicles to the lists
 }
 
-extern int GetAmountOwnedBy(Player *p, byte owner);
+extern int GetAmountOwnedBy(const Player *p, PlayerID owner);
 
 /** Acquire shares in an opposing company.
  * @param tile unused
@@ -1611,7 +1610,7 @@
 	if (!IsValidPlayer((PlayerID)p1) || !_patches.allow_shares) return CMD_ERROR;
 
 	SET_EXPENSES_TYPE(EXPENSES_OTHER);
-	p = GetPlayer(p1);
+	p = GetPlayer((PlayerID)p1);
 
 	/* Protect new companies from hostile takeovers */
 	if (_cur_year - p->inaugurated_year < 6) return_cmd_error(STR_7080_PROTECTED);
@@ -1624,7 +1623,7 @@
 
 	cost = CalculateCompanyValue(p) >> 2;
 	if (flags & DC_EXEC) {
-		PlayerID* b = p->share_owners;
+		PlayerByte* b = p->share_owners;
 		int i;
 
 		while (*b != PLAYER_SPECTATOR) b++; /* share owners is guaranteed to contain at least one PLAYER_SPECTATOR */
@@ -1656,7 +1655,7 @@
 	if (!IsValidPlayer((PlayerID)p1) || !_patches.allow_shares) return CMD_ERROR;
 
 	SET_EXPENSES_TYPE(EXPENSES_OTHER);
-	p = GetPlayer(p1);
+	p = GetPlayer((PlayerID)p1);
 
 	/* Those lines are here for network-protection (clients can be slow) */
 	if (GetAmountOwnedBy(p, _current_player) == 0) return 0;
@@ -1666,7 +1665,7 @@
 	cost = -(cost - (cost >> 7));
 
 	if (flags & DC_EXEC) {
-		PlayerID* b = p->share_owners;
+		PlayerByte* b = p->share_owners;
 		while (*b != _current_player) b++; /* share owners is guaranteed to contain player */
 		*b = PLAYER_SPECTATOR;
 		InvalidateWindow(WC_COMPANY, p1);
@@ -1690,7 +1689,7 @@
 	if (!IsValidPlayer((PlayerID)p1) || _networking) return CMD_ERROR;
 
 	SET_EXPENSES_TYPE(EXPENSES_OTHER);
-	p = GetPlayer(p1);
+	p = GetPlayer((PlayerID)p1);
 
 	if (!p->is_ai) return CMD_ERROR;
 
@@ -1730,7 +1729,7 @@
 	SlObject(&_economy, _economy_desc);
 }
 
-const ChunkHandler _economy_chunk_handlers[] = {
+extern const ChunkHandler _economy_chunk_handlers[] = {
 	{ 'PRIC', SaveLoad_PRIC, SaveLoad_PRIC, CH_RIFF | CH_AUTO_LENGTH},
 	{ 'CAPR', SaveLoad_CAPR, SaveLoad_CAPR, CH_RIFF | CH_AUTO_LENGTH},
 	{ 'SUBS', Save_SUBS,     Load_SUBS,     CH_ARRAY},
--- a/src/economy.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/economy.h	Mon Jan 15 20:14:06 2007 +0000
@@ -29,7 +29,8 @@
 } Subsidy;
 
 
-enum {
+enum ScoreID {
+	SCORE_BEGIN      = 0,
 	SCORE_VEHICLES   = 0,
 	SCORE_STATIONS   = 1,
 	SCORE_MIN_PROFIT = 2,
@@ -40,13 +41,14 @@
 	SCORE_MONEY      = 7,
 	SCORE_LOAN       = 8,
 	SCORE_TOTAL      = 9, // This must always be the last entry
-
-	NUM_SCORE = 10, // How many scores are there..
+	SCORE_END        = 10, // How many scores are there..
 
 	SCORE_MAX = 1000 // The max score that can be in the performance history
 	//  the scores together of score_info is allowed to be more!
 };
 
+DECLARE_POSTFIX_INCREMENT(ScoreID);
+
 typedef struct ScoreInfo {
 	byte id;    // Unique ID of the score
 	int needed; // How much you need to get the perfect score
@@ -54,7 +56,7 @@
 } ScoreInfo;
 
 extern const ScoreInfo _score_info[];
-extern int _score_part[MAX_PLAYERS][NUM_SCORE];
+extern int _score_part[MAX_PLAYERS][SCORE_END];
 
 int UpdateCompanyRatingAndValue(Player *p, bool update);
 
--- a/src/elrail.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/elrail.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -67,7 +67,7 @@
 
 static inline TLG GetTLG(TileIndex t)
 {
-	return (HASBIT(TileX(t), 0) << 1) + HASBIT(TileY(t), 0);
+	return (TLG)((HASBIT(TileX(t), 0) << 1) + HASBIT(TileY(t), 0));
 }
 
 /** Finds which Rail Bits are present on a given tile. For bridge tiles,
@@ -77,42 +77,42 @@
 {
 	switch (GetTileType(t)) {
 		case MP_RAILWAY:
-			if (GetRailType(t) != RAILTYPE_ELECTRIC) return 0;
+			if (GetRailType(t) != RAILTYPE_ELECTRIC) return TRACK_BIT_NONE;
 			switch (GetRailTileType(t)) {
 				case RAIL_TILE_NORMAL: case RAIL_TILE_SIGNALS:
 					return GetTrackBits(t);
 				case RAIL_TILE_DEPOT_WAYPOINT:
 					if (GetRailTileSubtype(t) == RAIL_SUBTYPE_WAYPOINT) return GetRailWaypointBits(t);
 				default:
-					return 0;
+					return TRACK_BIT_NONE;
 			}
 			break;
 
 		case MP_TUNNEL:
-			if (GetRailType(t) != RAILTYPE_ELECTRIC) return 0;
+			if (GetRailType(t) != RAILTYPE_ELECTRIC) return TRACK_BIT_NONE;
 			if (override != NULL) *override = 1 << GetTunnelDirection(t);
 			return AxisToTrackBits(DiagDirToAxis(GetTunnelDirection(t)));
 
 		case MP_RAILWAY_BRIDGE:
-			if (GetRailType(t) != RAILTYPE_ELECTRIC) return 0;
+			if (GetRailType(t) != RAILTYPE_ELECTRIC) return TRACK_BIT_NONE;
 			if (override != NULL && DistanceMax(t, GetOtherBridgeEnd(t)) > 1) {
 				*override = 1 << GetBridgeRampDirection(t);
 			}
 			return GetTrackBits(t);
 
 		case MP_STREET:
-			if (GetRoadTileType(t) != ROAD_TILE_CROSSING) return 0;
-			if (GetRailTypeCrossing(t) != RAILTYPE_ELECTRIC) return 0;
+			if (GetRoadTileType(t) != ROAD_TILE_CROSSING) return TRACK_BIT_NONE;
+			if (GetRailTypeCrossing(t) != RAILTYPE_ELECTRIC) return TRACK_BIT_NONE;
 			return GetCrossingRailBits(t);
 
 		case MP_STATION:
-			if (!IsRailwayStation(t)) return 0;
-			if (GetRailType(t) != RAILTYPE_ELECTRIC) return 0;
-			if (!IsStationTileElectrifiable(t)) return 0;
+			if (!IsRailwayStation(t)) return TRACK_BIT_NONE;
+			if (GetRailType(t) != RAILTYPE_ELECTRIC) return TRACK_BIT_NONE;
+			if (!IsStationTileElectrifiable(t)) return TRACK_BIT_NONE;
 			return TrackToTrackBits(GetRailStationTrack(t));
 
 		default:
-			return 0;
+			return TRACK_BIT_NONE;
 	}
 }
 
@@ -172,7 +172,7 @@
 	 *    which have no middle tiles */
 	trackconfig[TS_HOME] = GetRailTrackBitsUniversal(ti->tile, &OverridePCP);
 	/* If a track bit is present that is not in the main direction, the track is level */
-	isflat[TS_HOME] = trackconfig[TS_HOME] & (TRACK_BIT_HORZ | TRACK_BIT_VERT);
+	isflat[TS_HOME] = ((trackconfig[TS_HOME] & (TRACK_BIT_HORZ | TRACK_BIT_VERT)) != 0);
 
 	AdjustTileh(ti->tile, &tileh[TS_HOME]);
 
@@ -185,8 +185,8 @@
 		 * existing foundataions, so we do have to do that manually later on.*/
 		tileh[TS_NEIGHBOUR] = GetTileSlope(neighbour, NULL);
 		trackconfig[TS_NEIGHBOUR] = GetRailTrackBitsUniversal(neighbour, NULL);
-		if (IsTunnelTile(neighbour) && i != GetTunnelDirection(neighbour)) trackconfig[TS_NEIGHBOUR] = 0;
-		isflat[TS_NEIGHBOUR] = trackconfig[TS_NEIGHBOUR] & (TRACK_BIT_HORZ | TRACK_BIT_VERT);
+		if (IsTunnelTile(neighbour) && i != GetTunnelDirection(neighbour)) trackconfig[TS_NEIGHBOUR] = TRACK_BIT_NONE;
+		isflat[TS_NEIGHBOUR] = ((trackconfig[TS_NEIGHBOUR] & (TRACK_BIT_HORZ | TRACK_BIT_VERT)) != 0);
 
 		PPPpreferred[i] = 0xFF; /* We start with preferring everything (end-of-line in any direction) */
 		PPPallowed[i] = AllowedPPPonPCP[i];
@@ -290,7 +290,7 @@
 	}
 
 	/* Drawing of pylons is finished, now draw the wires */
-	for (t = 0; t < TRACK_END; t++) {
+	for (t = TRACK_BEGIN; t < TRACK_END; t++) {
 		if (HASBIT(trackconfig[TS_HOME], t)) {
 
 			byte PCPconfig = HASBIT(PCPstatus, PCPpositions[t][0]) +
@@ -322,7 +322,7 @@
 	Axis axis = GetBridgeAxis(ti->tile);
 	TLG tlg = GetTLG(ti->tile);
 
-	CatenarySprite offset = axis == AXIS_X ? 0 : WIRE_Y_FLAT_BOTH - WIRE_X_FLAT_BOTH;
+	CatenarySprite offset = (CatenarySprite)(axis == AXIS_X ? 0 : WIRE_Y_FLAT_BOTH - WIRE_X_FLAT_BOTH);
 
 	if ((length % 2) && num == length) {
 		/* Draw the "short" wire on the southern end of the bridge
--- a/src/endian_check.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/endian_check.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -1,6 +1,7 @@
 /* $Id$ */
 
 #include <stdio.h>
+#include <string.h>
 
 // This pretty simple file checks if the system is LITTLE_ENDIAN or BIG_ENDIAN
 //  it does that by putting a 1 and a 0 in an array, and read it out as one
--- a/src/engine.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/engine.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -129,7 +129,7 @@
 		uint32 r;
 
 		e->age = 0;
-		e->railtype = ei->railtype;
+		e->railtype = (RailType)ei->railtype;
 		e->flags = 0;
 		e->player_avail = 0;
 
@@ -189,7 +189,7 @@
 	SETBIT(e->player_avail, player);
 	SETBIT(p->avail_railtypes, e->railtype);
 
-	e->preview_player = 0xFF;
+	e->preview_player = INVALID_PLAYER;
 	if (player == _local_player) {
 		InvalidateWindowClassesData(WC_BUILD_VEHICLE);
 		InvalidateWindowClasses(WC_REPLACE_VEHICLE);
@@ -217,7 +217,7 @@
 		if (best_player == PLAYER_SPECTATOR) return PLAYER_SPECTATOR;
 
 		SETBIT(mask, best_player);
-	} while (--pp != 0);
+	} while (pp--, pp != 0);
 
 	return best_player;
 }
@@ -242,7 +242,7 @@
 				PlayerID best_player = GetBestPlayer(e->preview_player);
 
 				if (best_player == PLAYER_SPECTATOR) {
-					e->preview_player = 0xFF;
+					e->preview_player = INVALID_PLAYER;
 					continue;
 				}
 
@@ -364,7 +364,7 @@
 
 				// Do not introduce new rail wagons
 				if (!IsWagon(e - _engines))
-					e->preview_player = 1; // Give to the player with the highest rating.
+					e->preview_player = (PlayerID)1; // Give to the player with the highest rating.
 			}
 		}
 	}
@@ -636,7 +636,7 @@
 	SlArray(_engine_name_strings, lengthof(_engine_name_strings), SLE_STRINGID);
 }
 
-const ChunkHandler _engine_chunk_handlers[] = {
+extern const ChunkHandler _engine_chunk_handlers[] = {
 	{ 'ENGN', Save_ENGN,     Load_ENGN,     CH_ARRAY          },
 	{ 'ENGS', LoadSave_ENGS, LoadSave_ENGS, CH_RIFF           },
 	{ 'ERNW', Save_ERNW,     Load_ERNW,     CH_ARRAY | CH_LAST},
--- a/src/engine.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/engine.h	Mon Jan 15 20:14:06 2007 +0000
@@ -6,6 +6,8 @@
 /** @file engine.h */
 
 #include "oldpool.h"
+#include "rail.h"
+#include "sound.h"
 
 typedef struct RailVehicleInfo {
 	byte image_index;
@@ -38,8 +40,8 @@
 	CargoID cargo_type;
 	uint16 capacity;
 	byte running_cost;
-	byte sfx;
-	byte refittable;
+	SoundFxByte sfx;
+	bool refittable;
 } ShipVehicleInfo;
 
 // Aircraft subtypes
@@ -53,7 +55,7 @@
 	byte base_cost;
 	byte running_cost;
 	byte subtype;
-	byte sfx;
+	SoundFxByte sfx;
 	byte acceleration;
 	byte max_speed;
 	byte mail_capacity;
@@ -64,7 +66,7 @@
 	byte image_index;
 	byte base_cost;
 	byte running_cost;
-	byte sfx;
+	SoundFxByte sfx;
 	byte max_speed;
 	byte capacity;
 	CargoID cargo_type;
@@ -96,9 +98,9 @@
 	uint16 duration_phase_1, duration_phase_2, duration_phase_3;
 	byte lifelength;
 	byte flags;
-	byte preview_player;
+	PlayerByte preview_player;
 	byte preview_wait;
-	byte railtype;
+	RailTypeByte railtype;
 	byte player_avail;
 	byte type; // type, ie VEH_Road, VEH_Train, etc. Same as in vehicle.h
 } Engine;
@@ -122,9 +124,8 @@
 	NUM_VEHICLE_TYPES = 6
 };
 
-enum {
-	INVALID_ENGINE = 0xFFFF,
-};
+static const EngineID INVALID_ENGINE = 0xFFFF;
+
 
 void AddTypeToEngines(void);
 void StartupEngines(void);
--- a/src/engine_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/engine_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -24,6 +24,7 @@
 			case RAILTYPE_ELECTRIC: return STR_8102_RAILROAD_LOCOMOTIVE;
 			case RAILTYPE_MONO:     return STR_8106_MONORAIL_LOCOMOTIVE;
 			case RAILTYPE_MAGLEV:   return STR_8107_MAGLEV_LOCOMOTIVE;
+			default: NOT_REACHED();
 		}
 	}
 
--- a/src/fios.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/fios.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -11,6 +11,7 @@
 #include "variables.h"
 #include "functions.h"
 #include "heightmap.h"
+#include "helpers.hpp"
 #include "table/strings.h"
 #include "fios.h"
 #include <sys/types.h>
@@ -47,7 +48,7 @@
 {
 	if (_fios_count == _fios_alloc) {
 		_fios_alloc += 256;
-		_fios_items = realloc(_fios_items, _fios_alloc * sizeof(FiosItem));
+		ReallocT(&_fios_items, _fios_alloc);
 	}
 	return &_fios_items[_fios_count++];
 }
@@ -323,7 +324,7 @@
 	static char *_fios_save_path = NULL;
 
 	if (_fios_save_path == NULL) {
-		_fios_save_path = malloc(MAX_PATH);
+		MallocT(&_fios_save_path, MAX_PATH);
 		ttd_strlcpy(_fios_save_path, _paths.save_dir, MAX_PATH);
 	}
 
@@ -371,7 +372,7 @@
 	static char *_fios_scn_path = NULL;
 
 	if (_fios_scn_path == NULL) {
-		_fios_scn_path = malloc(MAX_PATH);
+		MallocT(&_fios_scn_path, MAX_PATH);
 		ttd_strlcpy(_fios_scn_path, _paths.scenario_dir, MAX_PATH);
 	}
 
@@ -402,7 +403,7 @@
 	static char *_fios_hmap_path = NULL;
 
 	if (_fios_hmap_path == NULL) {
-		_fios_hmap_path = malloc(MAX_PATH);
+		MallocT(&_fios_hmap_path, MAX_PATH);
 		strcpy(_fios_hmap_path, _paths.heightmap_dir);
 	}
 
--- a/src/fontcache.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/fontcache.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -11,6 +11,7 @@
 #include "gfx.h"
 #include "string.h"
 #include "fontcache.h"
+#include "helpers.hpp"
 
 #ifdef WITH_FREETYPE
 
@@ -77,7 +78,7 @@
 	 * normal char to match the data returned by RegEnumValue,
 	 * otherwise just use parameter */
 #if defined(UNICODE)
-	font_namep = malloc(MAX_PATH * sizeof(TCHAR));
+	MallocT(&font_namep, MAX_PATH);
 	MB_TO_WIDE_BUFFER(font_name, font_namep, MAX_PATH * sizeof(TCHAR));
 #else
 	font_namep = (char*)font_name; // only cast because in unicode pointer is not const
@@ -345,12 +346,12 @@
 {
 	if (_glyph_ptr[size] == NULL) {
 		DEBUG(freetype, 3, "Allocating root glyph cache for size %u", size);
-		_glyph_ptr[size] = calloc(256, sizeof(**_glyph_ptr));
+		CallocT(&_glyph_ptr[size], 256);
 	}
 
 	if (_glyph_ptr[size][GB(key, 8, 8)] == NULL) {
 		DEBUG(freetype, 3, "Allocating glyph cache for range 0x%02X00, size %u", GB(key, 8, 8), size);
-		_glyph_ptr[size][GB(key, 8, 8)] = calloc(256, sizeof(***_glyph_ptr));
+		CallocT(&_glyph_ptr[size][GB(key, 8, 8)], 256);
 	}
 
 	DEBUG(freetype, 4, "Set glyph for unicode character 0x%04X, size %u", key, size);
@@ -395,7 +396,7 @@
 	height = max(1, slot->bitmap.rows  + (size == FS_NORMAL));
 
 	/* FreeType has rendered the glyph, now we allocate a sprite and copy the image into it */
-	sprite = calloc(width * height + 8, 1);
+	sprite = (Sprite*)calloc(width * height + 8, 1);
 	sprite->info   = 1;
 	sprite->width  = width;
 	sprite->height = height;
@@ -483,8 +484,8 @@
 
 void SetUnicodeGlyph(FontSize size, uint32 key, SpriteID sprite)
 {
-	if (_unicode_glyph_map[size] == NULL) _unicode_glyph_map[size] = calloc(256, sizeof(*_unicode_glyph_map[size]));
-	if (_unicode_glyph_map[size][GB(key, 8, 8)] == NULL) _unicode_glyph_map[size][GB(key, 8, 8)] = calloc(256, sizeof(**_unicode_glyph_map[size]));
+	if (_unicode_glyph_map[size] == NULL) CallocT(&_unicode_glyph_map[size], 256);
+	if (_unicode_glyph_map[size][GB(key, 8, 8)] == NULL) CallocT(&_unicode_glyph_map[size][GB(key, 8, 8)], 256);
 	_unicode_glyph_map[size][GB(key, 8, 8)][GB(key, 0, 8)] = sprite;
 }
 
--- a/src/functions.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/functions.h	Mon Jan 15 20:14:06 2007 +0000
@@ -10,7 +10,7 @@
 uint GetSlopeZ(int x, int y);
 uint32 GetTileTrackStatus(TileIndex tile, TransportType mode);
 void GetAcceptedCargo(TileIndex tile, AcceptedCargo ac);
-void ChangeTileOwner(TileIndex tile, byte old_player, byte new_player);
+void ChangeTileOwner(TileIndex tile, PlayerID old_player, PlayerID new_player);
 void AnimateTile(TileIndex tile);
 void ClickTile(TileIndex tile);
 void GetTileDesc(TileIndex tile, TileDesc *td);
@@ -217,5 +217,4 @@
 
 void DeterminePaths(void);
 
-void CSleep(int milliseconds);
 #endif /* FUNCTIONS_H */
--- a/src/genworld.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/genworld.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -182,7 +182,7 @@
 {
 	if (_gw.thread == NULL) return;
 	_gw.quit_thread = true;
-	OTTDJoinThread(_gw.thread);
+	OTTDJoinThread((OTTDThread*)_gw.thread);
 	_gw.thread   = NULL;
 	_gw.threaded = false;
 }
--- a/src/genworld.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/genworld.h	Mon Jan 15 20:14:06 2007 +0000
@@ -34,7 +34,7 @@
 	bool quit_thread;      //! Do we want to quit the active thread
 	bool threaded;         //! Whether we run _GenerateWorld threaded
 	int mode;              //! What mode are we making a world in
-	byte lp;               //! The local_player before generating
+	PlayerID lp;               //! The local_player before generating
 	uint size_x;           //! X-size of the map
 	uint size_y;           //! Y-size of the map
 	gw_done_proc *proc;    //! Proc that is called when done (can be NULL)
@@ -84,8 +84,8 @@
 void HandleGeneratingWorldAbortion(void);
 
 /* genworld_gui.c */
-void SetGeneratingWorldProgress(gwp_class class, uint total);
-void IncreaseGeneratingWorldProgress(gwp_class class);
+void SetGeneratingWorldProgress(gwp_class cls, uint total);
+void IncreaseGeneratingWorldProgress(gwp_class cls);
 void PrepareGenerateWorldProgress(void);
 void ShowGenerateWorldProgress(void);
 void StartNewGameWithoutGUI(uint seed);
--- a/src/genworld_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/genworld_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -196,7 +196,7 @@
 	static querystr_d _genseed_query;
 	static char _genseed_buffer[LEN_RND_SEED];
 
-	uint mode = w->window_number;
+	glwp_modes mode = (glwp_modes)w->window_number;
 	uint y;
 
 	switch (e->event) {
@@ -714,7 +714,7 @@
 
 typedef struct tp_info {
 	uint percent;
-	StringID class;
+	StringID cls;
 	uint current;
 	uint total;
 	int timer;
@@ -753,12 +753,12 @@
 
 		/* Draw the % complete with a bar and a text */
 		DrawFrameRect(19, 20, (w->width - 18), 37, 14, FR_BORDERONLY);
-		DrawFrameRect(20, 21, (int)((w->width - 40) * _tp.percent / 100) + 20, 36, 10, 0);
+		DrawFrameRect(20, 21, (int)((w->width - 40) * _tp.percent / 100) + 20, 36, 10, FR_NONE);
 		SetDParam(0, _tp.percent);
 		DrawStringCentered(90, 25, STR_PROGRESS, 0);
 
 		/* Tell which class we are generating */
-		DrawStringCentered(90, 46, _tp.class, 0);
+		DrawStringCentered(90, 46, _tp.cls, 0);
 
 		/* And say where we are in that class */
 		SetDParam(0, _tp.current);
@@ -783,7 +783,7 @@
  */
 void PrepareGenerateWorldProgress(void)
 {
-	_tp.class   = STR_WORLD_GENERATION;
+	_tp.cls   = STR_WORLD_GENERATION;
 	_tp.current = 0;
 	_tp.total   = 0;
 	_tp.percent = 0;
@@ -798,7 +798,7 @@
 	AllocateWindowDescFront(&_show_terrain_progress_desc, 0);
 }
 
-static void _SetGeneratingWorldProgress(gwp_class class, uint progress, uint total)
+static void _SetGeneratingWorldProgress(gwp_class cls, uint progress, uint total)
 {
 	static const int percent_table[GWP_CLASS_COUNT + 1] = {0, 5, 15, 20, 40, 60, 65, 80, 85, 99, 100 };
 	static const StringID class_table[GWP_CLASS_COUNT]  = {
@@ -814,7 +814,7 @@
 		STR_PREPARING_GAME
 	};
 
-	assert(class < GWP_CLASS_COUNT);
+	assert(cls < GWP_CLASS_COUNT);
 
 	/* Do not run this function if we aren't in a thread */
 	if (!IsGenerateWorldThreaded() && !_network_dedicated) return;
@@ -822,13 +822,13 @@
 	if (IsGeneratingWorldAborted()) HandleGeneratingWorldAbortion();
 
 	if (total == 0) {
-		assert(_tp.class == class_table[class]);
+		assert(_tp.cls == class_table[cls]);
 		_tp.current += progress;
 	} else {
-		_tp.class   = class_table[class];
+		_tp.cls   = class_table[cls];
 		_tp.current = progress;
 		_tp.total   = total;
-		_tp.percent = percent_table[class];
+		_tp.percent = percent_table[cls];
 	}
 
 	/* Don't update the screen too often. So update it once in every 200ms.
@@ -837,7 +837,7 @@
 	if (!_network_dedicated && _tp.timer != 0 && _timer_counter - _tp.timer < (200 * 8 / 30)) return;
 
 	/* Percentage is about the number of completed tasks, so 'current - 1' */
-	_tp.percent = percent_table[class] + (percent_table[class + 1] - percent_table[class]) * (_tp.current == 0 ? 0 : _tp.current - 1) / _tp.total;
+	_tp.percent = percent_table[cls] + (percent_table[cls + 1] - percent_table[cls]) * (_tp.current == 0 ? 0 : _tp.current - 1) / _tp.total;
 	_tp.timer = _timer_counter;
 
 	if (_network_dedicated) {
@@ -877,11 +877,11 @@
  * Warning: this function isn't clever. Don't go from class 4 to 3. Go upwards, always.
  *  Also, progress works if total is zero, total works if progress is zero.
  */
-void SetGeneratingWorldProgress(gwp_class class, uint total)
+void SetGeneratingWorldProgress(gwp_class cls, uint total)
 {
 	if (total == 0) return;
 
-	_SetGeneratingWorldProgress(class, 0, total);
+	_SetGeneratingWorldProgress(cls, 0, total);
 }
 
 /**
@@ -891,8 +891,8 @@
  * Warning: this function isn't clever. Don't go from class 4 to 3. Go upwards, always.
  *  Also, progress works if total is zero, total works if progress is zero.
  */
-void IncreaseGeneratingWorldProgress(gwp_class class)
+void IncreaseGeneratingWorldProgress(gwp_class cls)
 {
 	/* In fact the param 'class' isn't needed.. but for some security reasons, we want it around */
-	_SetGeneratingWorldProgress(class, 1, 0);
+	_SetGeneratingWorldProgress(cls, 1, 0);
 }
--- a/src/gfx.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/gfx.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -473,7 +473,7 @@
 	tmp = FormatStringLinebreaks(buffer, maxw);
 	num = GB(tmp, 0, 16);
 
-	mt = GetCharacterHeight(GB(tmp, 16, 16));
+	mt = GetCharacterHeight((FontSize)GB(tmp, 16, 16));
 
 	y -= (mt >> 1) * num;
 
@@ -517,7 +517,7 @@
 	tmp = FormatStringLinebreaks(buffer, maxw);
 	num = GB(tmp, 0, 16);
 
-	mt = GetCharacterHeight(GB(tmp, 16, 16));
+	mt = GetCharacterHeight((FontSize)GB(tmp, 16, 16));
 	total_height = (num + 1) * mt;
 
 	src = buffer;
--- a/src/gfx.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/gfx.h	Mon Jan 15 20:14:06 2007 +0000
@@ -3,31 +3,7 @@
 #ifndef GFX_H
 #define GFX_H
 
-typedef byte Pixel;
-
-struct DrawPixelInfo {
-	Pixel *dst_ptr;
-	int left, top, width, height;
-	int pitch;
-	uint16 zoom;
-};
-
-
-typedef struct CursorVars {
-	Point pos, size, offs, delta; ///< position, size, offset from top-left, and movement
-	Point draw_pos, draw_size;    ///< position and size bounding-box for drawing
-	CursorID sprite; ///< current image of cursor
-
-	int wheel;       ///< mouse wheel movement
-	const CursorID *animate_list, *animate_cur; ///< in case of animated cursor, list of frames
-	uint animate_timeout;                       ///< current frame in list of animated cursor
-
-	bool visible;    ///< cursor is visible
-	bool dirty;      ///< the rect occupied by the mouse is dirty (redraw)
-	bool fix_at;     ///< mouse is moving, but cursor is not (used for scrolling)
-	bool in_window;  ///< mouse inside this window, determines drawing logic
-} CursorVars;
-
+#include "helpers.hpp"
 
 typedef enum FontSizes {
 	FS_NORMAL,
@@ -36,6 +12,7 @@
 	FS_END,
 } FontSize;
 
+DECLARE_POSTFIX_INCREMENT(FontSize);
 
 void RedrawScreenRect(int left, int top, int right, int bottom);
 void GfxScroll(int left, int top, int width, int height, int xo, int yo);
@@ -83,7 +60,7 @@
 /* window.c */
 void DrawOverlappedWindowForAll(int left, int top, int right, int bottom);
 
-void SetMouseCursor(uint cursor);
+void SetMouseCursor(CursorID cursor);
 void SetAnimatedMouseCursor(const CursorID *table);
 void CursorTick(void);
 void DrawMouseCursor(void);
@@ -91,7 +68,7 @@
 void UndrawMouseCursor(void);
 bool ChangeResInGame(int w, int h);
 void SortResolutions(int count);
-void ToggleFullScreen(bool fs);
+extern "C" void ToggleFullScreen(bool fs);
 
 /* gfx.c */
 #define ASCII_LETTERSTART 32
@@ -109,9 +86,7 @@
 	}
 }
 
-VARDEF DrawPixelInfo _screen;
 VARDEF DrawPixelInfo *_cur_dpi;
-VARDEF CursorVars _cursor;
 
 enum {
 	COLOUR_DARK_BLUE,
@@ -138,20 +113,8 @@
  */
 VARDEF byte _colour_gradient[16][8];
 
-VARDEF int _pal_first_dirty;
-VARDEF int _pal_last_dirty;
-
 VARDEF bool _use_dos_palette;
 
-typedef struct Colour {
-	byte r;
-	byte g;
-	byte b;
-} Colour;
-
-extern Colour _cur_palette[256];
-
-
 typedef enum StringColorFlags {
 	IS_PALETTE_COLOR = 0x100, // color value is already a real palette color index, not an index of a StringColor
 } StringColorFlags;
--- a/src/gfxinit.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/gfxinit.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -17,13 +17,13 @@
 #include <string.h>
 
 typedef struct MD5File {
-	const char * const filename;     // filename
-	const md5_byte_t hash[16]; // md5 sum of the file
+	const char * filename;     // filename
+	md5_byte_t hash[16]; // md5 sum of the file
 } MD5File;
 
 typedef struct FileList {
-	const MD5File basic[4];     // grf files that always have to be loaded
-	const MD5File landscape[3]; // landscape specific grf files
+	MD5File basic[4];     // grf files that always have to be loaded
+	MD5File landscape[3]; // landscape specific grf files
 } FileList;
 
 enum {
--- a/src/graph_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/graph_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -15,6 +15,7 @@
 #include "debug.h"
 #include "variables.h"
 #include "date.h"
+#include "helpers.hpp"
 
 const byte _cargo_colours[NUM_CARGO] = {152, 32, 15, 174, 208, 194, 191, 84, 184, 10, 202, 48};
 
@@ -65,7 +66,7 @@
 
 	/* the colors and cost array of GraphDrawer must accomodate
 	 * both values for cargo and players. So if any are higher, quit */
-	assert(GRAPH_NUM >= NUM_CARGO && GRAPH_NUM >= MAX_PLAYERS);
+	assert(GRAPH_NUM >= (int)NUM_CARGO && GRAPH_NUM >= (int)MAX_PLAYERS);
 
 	color = _colour_gradient[gw->bg_line_color][4];
 
@@ -118,7 +119,7 @@
 			col_ptr = row_ptr;
 			do {
 				if (*col_ptr != INVALID_VALUE) {
-					mx = max64(mx, myabs64(*col_ptr));
+					mx = max64(mx, *col_ptr);
 				}
 			} while (col_ptr++, --num_x);
 		}
@@ -906,11 +907,10 @@
 
 static void PerformanceRatingDetailWndProc(Window *w, WindowEvent *e)
 {
-	static PlayerID _performance_rating_detail_player = 0;
+	static PlayerID _performance_rating_detail_player = PLAYER_FIRST;
 
 	switch (e->event) {
 		case WE_PAINT: {
-			int i;
 			byte x;
 			uint16 y = 14;
 			int total_score = 0;
@@ -920,7 +920,7 @@
 			DrawWindowWidgets(w);
 
 			// Paint the player icons
-			for (i = 0; i < MAX_PLAYERS; i++) {
+			for (PlayerID i = PLAYER_FIRST; i < MAX_PLAYERS; i++) {
 				if (!GetPlayer(i)->is_active) {
 					// Check if we have the player as an active player
 					if (!IsWindowWidgetDisabled(w, i + 13)) {
@@ -930,7 +930,7 @@
 						if (IsWindowWidgetLowered(w, i + 13)) {
 							RaiseWindowWidget(w, i + 13);
 							LowerWindowWidget(w, 13);
-							_performance_rating_detail_player = 0;
+							_performance_rating_detail_player = PLAYER_FIRST;
 						}
 						// We need a repaint
 						SetWindowDirty(w);
@@ -955,7 +955,7 @@
 			color_notdone = _colour_gradient[COLOUR_RED][4];
 
 			// Draw all the score parts
-			for (i = 0; i < NUM_SCORE; i++) {
+			for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) {
 				int val    = _score_part[_performance_rating_detail_player][i];
 				int needed = _score_info[i].needed;
 				int score  = _score_info[i].score;
@@ -1030,7 +1030,7 @@
 				// Is it no on disable?
 				if (!IsWindowWidgetDisabled(w, e->we.click.widget)) {
 					RaiseWindowWidget(w, _performance_rating_detail_player + 13);
-					_performance_rating_detail_player = e->we.click.widget - 13;
+					_performance_rating_detail_player = (PlayerID)(e->we.click.widget - 13);
 					LowerWindowWidget(w, _performance_rating_detail_player + 13);
 					SetWindowDirty(w);
 				}
@@ -1038,11 +1038,11 @@
 			break;
 
 		case WE_CREATE: {
-			int i;
+			PlayerID i;
 			Player *p2;
 
 			/* Disable the players who are not active */
-			for (i = 0; i < MAX_PLAYERS; i++) {
+			for (i = PLAYER_FIRST; i < MAX_PLAYERS; i++) {
 				SetWindowWidgetDisabledState(w, i + 13, !GetPlayer(i)->is_active);
 			}
 			/* Update all player stats with the current data
@@ -1054,7 +1054,7 @@
 			w->custom[0] = DAY_TICKS;
 			w->custom[1] = 5;
 
-			_performance_rating_detail_player = 0;
+			_performance_rating_detail_player = PLAYER_FIRST;
 			LowerWindowWidget(w, _performance_rating_detail_player + 13);
 			SetWindowDirty(w);
 
@@ -1151,7 +1151,7 @@
 	uint n = 0;
 
 	/* Create array for sorting */
-	_sign_sort = realloc((void *)_sign_sort, (GetMaxSignIndex() + 1)* sizeof(_sign_sort[0]));
+	ReallocT(&_sign_sort, GetMaxSignIndex() + 1);
 	if (_sign_sort == NULL) error("Could not allocate memory for the sign-sorting-list");
 
 	FOR_ALL_SIGNS(si) _sign_sort[n++] = si;
--- a/src/gui.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/gui.h	Mon Jan 15 20:14:06 2007 +0000
@@ -132,7 +132,7 @@
 
 /* main_gui.c */
 void HandleOnEditText(const char *str);
-VARDEF byte _station_show_coverage;
+VARDEF bool _station_show_coverage;
 VARDEF PlaceProc *_place_proc;
 
 /* vehicle_gui.c */
--- a/src/hal.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/hal.h	Mon Jan 15 20:14:06 2007 +0000
@@ -3,6 +3,85 @@
 #ifndef HAL_H
 #define HAL_H
 
+#ifdef __cplusplus
+extern "C" {
+#endif //__cplusplus
+
+enum WindowKeyCodes {
+	WKC_SHIFT = 0x8000,
+	WKC_CTRL  = 0x4000,
+	WKC_ALT   = 0x2000,
+	WKC_META  = 0x1000,
+
+	// Special ones
+	WKC_NONE        =  0,
+	WKC_ESC         =  1,
+	WKC_BACKSPACE   =  2,
+	WKC_INSERT      =  3,
+	WKC_DELETE      =  4,
+
+	WKC_PAGEUP      =  5,
+	WKC_PAGEDOWN    =  6,
+	WKC_END         =  7,
+	WKC_HOME        =  8,
+
+	// Arrow keys
+	WKC_LEFT        =  9,
+	WKC_UP          = 10,
+	WKC_RIGHT       = 11,
+	WKC_DOWN        = 12,
+
+	// Return & tab
+	WKC_RETURN      = 13,
+	WKC_TAB         = 14,
+
+	// Numerical keyboard
+	WKC_NUM_0       = 16,
+	WKC_NUM_1       = 17,
+	WKC_NUM_2       = 18,
+	WKC_NUM_3       = 19,
+	WKC_NUM_4       = 20,
+	WKC_NUM_5       = 21,
+	WKC_NUM_6       = 22,
+	WKC_NUM_7       = 23,
+	WKC_NUM_8       = 24,
+	WKC_NUM_9       = 25,
+	WKC_NUM_DIV     = 26,
+	WKC_NUM_MUL     = 27,
+	WKC_NUM_MINUS   = 28,
+	WKC_NUM_PLUS    = 29,
+	WKC_NUM_ENTER   = 30,
+	WKC_NUM_DECIMAL = 31,
+
+	// Space
+	WKC_SPACE       = 32,
+
+	// Function keys
+	WKC_F1          = 33,
+	WKC_F2          = 34,
+	WKC_F3          = 35,
+	WKC_F4          = 36,
+	WKC_F5          = 37,
+	WKC_F6          = 38,
+	WKC_F7          = 39,
+	WKC_F8          = 40,
+	WKC_F9          = 41,
+	WKC_F10         = 42,
+	WKC_F11         = 43,
+	WKC_F12         = 44,
+
+	// 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,
+	WKC_PAUSE       = 46,
+
+	// 0-9 are mapped to 48-57
+	// A-Z are mapped to 65-90
+	// a-z are mapped to 97-122
+};
+
+
 typedef struct {
 	const char *(*start)(const char * const *parm);
 	void (*stop)(void);
@@ -32,9 +111,9 @@
 	void (*set_volume)(byte vol);
 } HalMusicDriver;
 
-VARDEF HalMusicDriver *_music_driver;
-VARDEF HalSoundDriver *_sound_driver;
-VARDEF HalVideoDriver *_video_driver;
+extern HalMusicDriver *_music_driver;
+extern HalSoundDriver *_sound_driver;
+extern HalVideoDriver *_video_driver;
 
 enum DriverType {
 	VIDEO_DRIVER = 0,
@@ -42,8 +121,99 @@
 	MUSIC_DRIVER = 2,
 };
 
+enum GameModes {
+	GM_MENU,
+	GM_NORMAL,
+	GM_EDITOR
+};
+
 void GameLoop(void);
 
 void CreateConsole(void);
 
+typedef int32 CursorID;
+typedef byte Pixel;
+
+typedef struct Point {
+	int x,y;
+} Point;
+
+typedef struct Rect {
+	int left,top,right,bottom;
+} Rect;
+
+
+typedef struct CursorVars {
+	Point pos, size, offs, delta; ///< position, size, offset from top-left, and movement
+	Point draw_pos, draw_size;    ///< position and size bounding-box for drawing
+	CursorID sprite; ///< current image of cursor
+
+	int wheel;       ///< mouse wheel movement
+	const CursorID *animate_list, *animate_cur; ///< in case of animated cursor, list of frames
+	uint animate_timeout;                       ///< current frame in list of animated cursor
+
+	bool visible;    ///< cursor is visible
+	bool dirty;      ///< the rect occupied by the mouse is dirty (redraw)
+	bool fix_at;     ///< mouse is moving, but cursor is not (used for scrolling)
+	bool in_window;  ///< mouse inside this window, determines drawing logic
+} CursorVars;
+
+typedef struct DrawPixelInfo {
+	Pixel *dst_ptr;
+	int left, top, width, height;
+	int pitch;
+	uint16 zoom;
+} DrawPixelInfo;
+
+
+extern byte _dirkeys;        // 1 = left, 2 = up, 4 = right, 8 = down
+extern bool _fullscreen;
+extern CursorVars _cursor;
+extern bool _ctrl_pressed;   // Is Ctrl pressed?
+extern bool _shift_pressed;  // Is Shift pressed?
+extern byte _fast_forward;
+
+extern bool _left_button_down;
+extern bool _left_button_clicked;
+extern bool _right_button_down;
+extern bool _right_button_clicked;
+
+extern DrawPixelInfo _screen;
+extern bool _exit_game;
+extern bool _networking;         ///< are we in networking mode?
+extern byte _game_mode;
+extern byte _pause;
+
+
+void HandleKeypress(uint32 key);
+void HandleMouseEvents(void);
+void CSleep(int milliseconds);
+void UpdateWindows(void);
+
+uint32 InteractiveRandom(void); /* Used for random sequences that are not the same on the other end of the multiplayer link */
+uint InteractiveRandomRange(uint max);
+void DrawTextMessage(void);
+void DrawMouseCursor(void);
+void ScreenSizeChanged(void);
+void HandleExitGameRequest(void);
+void GameSizeChanged(void);
+void UndrawMouseCursor(void);
+
+extern int _pal_first_dirty;
+extern int _pal_last_dirty;
+extern int _num_resolutions;
+extern uint16 _resolutions[32][2];
+extern uint16 _cur_resolution[2];
+
+typedef struct Colour {
+	byte r;
+	byte g;
+	byte b;
+} Colour;
+extern Colour _cur_palette[256];
+
+#ifdef __cplusplus
+} // extern "C"
+#endif //__cplusplus
+
 #endif /* HAL_H */
--- a/src/heightmap.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/heightmap.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -13,6 +13,7 @@
 #include "gui.h"
 #include "saveload.h"
 #include "bmp.h"
+#include "helpers.hpp"
 
 /**
  * Convert RGB colors to Grayscale using 29.9% Red, 58.7% Green, 11.4% Blue
@@ -135,7 +136,7 @@
 	}
 
 	if (map != NULL) {
-		*map = malloc(info_ptr->width * info_ptr->height * sizeof(byte));
+		MallocT(/* NO & */map, info_ptr->width * info_ptr->height);
 
 		if (*map == NULL) {
 			ShowErrorMessage(STR_PNGMAP_ERR_MISC, STR_PNGMAP_ERROR, 0, 0);
@@ -248,7 +249,7 @@
 			return false;
 		}
 
-		*map = malloc(info.width * info.height * sizeof(byte));
+		MallocT(map, info.width * info.height);
 		if (*map == NULL) {
 			ShowErrorMessage(STR_PNGMAP_ERR_MISC, STR_BMPMAP_ERROR, 0, 0);
 			fclose(f);
--- a/src/helpers.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/helpers.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -1,10 +1,8 @@
 /* $Id$ */
 #include "stdafx.h"
 
-EXTERN_C_BEGIN
 #include "openttd.h"
 #include "engine.h"
-EXTERN_C_END
 
 #include <new>
 #include "yapf/blob.hpp"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/helpers.hpp	Mon Jan 15 20:14:06 2007 +0000
@@ -0,0 +1,178 @@
+/* $Id$ */
+
+#ifndef HELPERS_HPP
+#define HELPERS_HPP
+
+/** @file helpers.hpp */
+#include "macros.h"
+
+#ifdef __cplusplus
+
+/** When allocating using malloc/calloc in C++ it is usually needed to cast the return value
+*  from void* to the proper pointer type. Another alternative would be MallocT<> as follows */
+template <typename T> FORCEINLINE bool MallocT(T** t_ptr, size_t num_elements)
+{
+	*t_ptr = (T*)malloc(num_elements * sizeof(T));
+	return (*t_ptr != NULL);
+}
+/** When allocating using malloc/calloc in C++ it is usually needed to cast the return value
+*  from void* to the proper pointer type. Another alternative would be MallocT<> as follows */
+template <typename T> FORCEINLINE bool CallocT(T** t_ptr, size_t num_elements)
+{
+	*t_ptr = (T*)calloc(num_elements, sizeof(T));
+	return (*t_ptr != NULL);
+}
+/** When allocating using malloc/calloc in C++ it is usually needed to cast the return value
+*  from void* to the proper pointer type. Another alternative would be MallocT<> as follows */
+template <typename T> FORCEINLINE bool ReallocT(T** t_ptr, size_t num_elements)
+{
+	*t_ptr = (T*)realloc(*t_ptr, num_elements * sizeof(T));
+	return (*t_ptr != NULL);
+}
+
+/** type safe swap operation */
+template <typename T> void SwapT(T *a, T *b);
+
+template <typename T> FORCEINLINE void SwapT(T *a, T *b)
+{
+	T t = *a;
+	*a = *b;
+	*b = t;
+}
+
+
+/** returns the absolute value of (scalar) variable. @note assumes variable to be signed */
+template <typename T> static inline T myabs(T a) { return a < (T)0 ? -a : a; }
+/** returns the (absolute) difference between two (scalar) variables */
+template <typename T> static inline T delta(T a, T b) { return a < b ? b - a : a - b; }
+
+/** Some enums need to have allowed incrementing (i.e. StationClassID) */
+#define DECLARE_POSTFIX_INCREMENT(type) \
+	FORCEINLINE type operator ++(type& e, int) \
+	{ \
+		type e_org = e; \
+		e = (type)((int)e + 1); \
+		return e_org; \
+	} \
+	FORCEINLINE type operator --(type& e, int) \
+	{ \
+		type e_org = e; \
+		e = (type)((int)e - 1); \
+		return e_org; \
+	}
+
+
+
+/** Operators to allow to work with enum as with type safe bit set in C++ */
+# define DECLARE_ENUM_AS_BIT_SET(mask_t) \
+	FORCEINLINE mask_t operator | (mask_t m1, mask_t m2) {return (mask_t)((int)m1 | m2);} \
+	FORCEINLINE mask_t operator & (mask_t m1, mask_t m2) {return (mask_t)((int)m1 & m2);} \
+	FORCEINLINE mask_t operator ^ (mask_t m1, mask_t m2) {return (mask_t)((int)m1 ^ m2);} \
+	FORCEINLINE mask_t& operator |= (mask_t& m1, mask_t m2) {m1 = m1 | m2; return m1;} \
+	FORCEINLINE mask_t& operator &= (mask_t& m1, mask_t m2) {m1 = m1 & m2; return m1;} \
+	FORCEINLINE mask_t& operator ^= (mask_t& m1, mask_t m2) {m1 = m1 ^ m2; return m1;} \
+	FORCEINLINE mask_t operator ~(mask_t m) {return (mask_t)(~(int)m);}
+
+/** probably redundant enum combining operators (as we have conversion functions)
+ *  but the old code is full of such arithmetics */
+# define DECLARE_ENUM_AS_BIT_INDEX(idx_t, mask_t) \
+	FORCEINLINE mask_t operator << (int m, idx_t i) {return (mask_t)(m << (int)i);} \
+	FORCEINLINE mask_t operator << (mask_t m, int i) {return (mask_t)(((int)m) << i);} \
+	FORCEINLINE mask_t operator >> (mask_t m, int i) {return (mask_t)(((int)m) >> i);}
+
+
+/** Informative template class exposing basic enumeration properties used by several
+ *  other templates below. Here we have only forward declaration. For each enum type
+ *  we will create specialization derived from MakeEnumPropsT<>. */
+template <typename Tenum_t> struct EnumPropsT;
+
+/** Helper template class that makes basic properties of given enumeration type visible
+ *  from outsize. It is used as base class of several EnumPropsT specializations each
+ *  dedicated to one of commonly used enumeration types. */
+template <typename Tenum_t, typename Tstorage_t, Tenum_t Tbegin, Tenum_t Tend, Tenum_t Tinvalid>
+struct MakeEnumPropsT {
+	typedef Tenum_t type;                     ///< enum type (i.e. Trackdir)
+	typedef Tstorage_t storage;               ///< storage type (i.e. byte)
+	static const Tenum_t begin = Tbegin;      ///< lowest valid value (i.e. TRACKDIR_BEGIN)
+	static const Tenum_t end = Tend;          ///< one after the last valid value (i.e. TRACKDIR_END)
+	static const Tenum_t invalid = Tinvalid;  ///< what value is used as invalid value (i.e. INVALID_TRACKDIR)
+};
+
+
+
+/** In some cases we use byte or uint16 to store values that are defined as enum. It is
+	*  necessary in order to control the sizeof() such values. Some compilers make enum
+	*  the same size as int (4 or 8 bytes instead of 1 or 2). As a consequence the strict
+	*  compiler type-checking causes errors like:
+	*     'HasPowerOnRail' : cannot convert parameter 1 from 'byte' to 'RailType' when
+	*  u->u.rail.railtype is passed as argument or type RailType. In such cases it is better
+	*  to teach the compiler that u->u.rail.railtype is to be treated as RailType. */
+template <typename Tenum_t> struct TinyEnumT;
+
+/** The general declaration of TinyEnumT<> (above) */
+template <typename Tenum_t> struct TinyEnumT
+{
+	typedef Tenum_t enum_type;                      ///< expose our enumeration type (i.e. Trackdir) to outside
+	typedef EnumPropsT<Tenum_t> Props;              ///< make easier access to our enumeration propeties
+	typedef typename Props::storage storage_type;   ///< small storage type
+	static const enum_type begin = Props::begin;    ///< enum beginning (i.e. TRACKDIR_BEGIN)
+	static const enum_type end = Props::end;        ///< enum end (i.e. TRACKDIR_END)
+	static const enum_type invalid = Props::invalid;///< invalid value (i.e. INVALID_TRACKDIR)
+
+	storage_type m_val;  ///< here we hold the actual value in small (i.e. byte) form
+
+	/** Cast operator - invoked then the value is assigned to the Tenum_t type */
+	FORCEINLINE operator enum_type () const
+	{
+		return (enum_type)m_val;
+	}
+
+	/** Assignment operator (from Tenum_t type) */
+	FORCEINLINE TinyEnumT& operator = (enum_type e)
+	{
+		m_val = (storage_type)e; return *this;
+	}
+
+	/** postfix ++ operator on tiny type */
+	FORCEINLINE TinyEnumT& operator ++ (int)
+	{
+		if (++m_val >= end) m_val -= (storage_type)(end - begin);
+		return *this;
+	}
+};
+
+template <typename Tenum_t> FORCEINLINE void SwapT(TinyEnumT<Tenum_t> *a, TinyEnumT<Tenum_t> *b)
+{
+	SwapT(&a->m_val, &b->m_val);
+}
+
+template <typename T> FORCEINLINE T ClrBitT(T t, int bit_index)
+{
+	int val = t;
+	CLRBIT(val, bit_index);
+	return (T)val;
+}
+
+template <typename T> FORCEINLINE T SetBitT(T t, int bit_index)
+{
+	int val = t;
+	SETBIT(val, bit_index);
+	return (T)val;
+}
+
+template <typename T> FORCEINLINE T ToggleBitT(T t, int bit_index)
+{
+	int val = t;
+	TOGGLEBIT(val, bit_index);
+	return (T)val;
+}
+
+#else // __cplusplus
+
+#define DECLARE_POSTFIX_INCREMENT(E)
+#define DECLARE_ENUM_AS_BIT_SET(E)
+#define DECLARE_ENUM_AS_BIT_INDEX(E1,E2)
+
+#endif  // __cplusplus
+
+#endif /* HELPERS_HPP */
--- a/src/industry.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/industry.h	Mon Jan 15 20:14:06 2007 +0000
@@ -36,7 +36,7 @@
 	uint16 counter;
 
 	byte type;
-	byte owner;
+	OwnerByte owner;
 	byte random_color;
 	Year last_prod_year;
 	byte was_cargo_delivered;
--- a/src/industry_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/industry_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -765,14 +765,14 @@
 		tile = TILE_MASK(tile);
 
 		if (IsTileType(tile, MP_CLEAR) || IsTileType(tile, MP_TREES)) {
-			byte or = type;
+			byte or_ = type;
 
-			if (or == 1 && CHANCE16(1, 7)) or = 2;
+			if (or_ == 1 && CHANCE16(1, 7)) or_ = 2;
 
 			if (direction == AXIS_X) {
-				SetFenceSE(tile, or);
+				SetFenceSE(tile, or_);
 			} else {
-				SetFenceSW(tile, or);
+				SetFenceSW(tile, or_);
 			}
 		}
 
@@ -942,7 +942,7 @@
 	if ((i->counter & 0x3F) == 0) {
 		if (CHANCE16R(1,14,r) && (num=_industry_sounds[i->type][0]) != 0) {
 			SndPlayTileFx(
-				_industry_sounds[i->type][1] + (((r >> 16) * num) >> 16),
+				(SoundFx)(_industry_sounds[i->type][1] + (((r >> 16) * num) >> 16)),
 				i->xy);
 		}
 	}
@@ -1225,7 +1225,7 @@
 			return false;
 
 		/* Don't allow too big of a change if this is the sub-tile check */
-		if (internal != 0 && myabs(curh - height) > 1) return false;
+		if (internal != 0 && delta(curh, height) > 1) return false;
 
 		/* Different height, so the surrounding tiles of this tile
 		 *  has to be correct too (in level, or almost in level)
@@ -1353,7 +1353,7 @@
 	return AddBlockToPool(&_Industry_pool) ? AllocateIndustry() : NULL;
 }
 
-static void DoCreateNewIndustry(Industry *i, TileIndex tile, int type, const IndustryTileTable *it, const Town *t, byte owner)
+static void DoCreateNewIndustry(Industry *i, TileIndex tile, int type, const IndustryTileTable *it, const Town *t, Owner owner)
 {
 	const IndustrySpec *indspec = GetIndustrySpec(type);
 	uint32 r;
@@ -1595,25 +1595,25 @@
 		default: /* INDUSTRY_PRODUCTION */
 			for (j = 0; j < 2 && i->produced_cargo[j] != CT_INVALID; j++){
 				uint32 r = Random();
-				int old, new, percent;
+				int old_prod, new_prod, percent;
 				int mag;
 
-				new = old = i->production_rate[j];
+				new_prod = old_prod = i->production_rate[j];
 				if (CHANCE16I(20, 1024, r))
-					new -= ((RandomRange(50) + 10) * old) >> 8;
+					new_prod -= ((RandomRange(50) + 10) * old_prod) >> 8;
 				if (CHANCE16I(20 + (i->pct_transported[j] * 20 >> 8), 1024, r >> 16))
-					new += ((RandomRange(50) + 10) * old) >> 8;
+					new_prod += ((RandomRange(50) + 10) * old_prod) >> 8;
 
-				new = clamp(new, 0, 255);
-				if (new == old) {
+				new_prod = clamp(new_prod, 0, 255);
+				if (new_prod == old_prod) {
 					closeit = false;
 					continue;
 				}
 
-				percent = new * 100 / old - 100;
-				i->production_rate[j] = new;
+				percent = new_prod * 100 / old_prod - 100;
+				i->production_rate[j] = new_prod;
 
-				if (new >= indspec->production_rate[j] / 4)
+				if (new_prod >= indspec->production_rate[j] / 4)
 					closeit = false;
 
 				mag = abs(percent);
@@ -1827,7 +1827,7 @@
 	_industry_sound_tile = 0;
 }
 
-const TileTypeProcs _tile_type_industry_procs = {
+extern const TileTypeProcs _tile_type_industry_procs = {
 	DrawTile_Industry,           /* draw_tile_proc */
 	GetSlopeZ_Industry,          /* get_slope_z_proc */
 	ClearTile_Industry,          /* clear_tile_proc */
@@ -1905,6 +1905,6 @@
 	}
 }
 
-const ChunkHandler _industry_chunk_handlers[] = {
+extern const ChunkHandler _industry_chunk_handlers[] = {
 	{ 'INDY', Save_INDY, Load_INDY, CH_ARRAY | CH_LAST},
 };
--- a/src/industry_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/industry_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -16,6 +16,7 @@
 #include "industry.h"
 #include "town.h"
 #include "variables.h"
+#include "helpers.hpp"
 
 const byte _build_industry_types[4][12] = {
 	{  1,  2,  4,  6,  8,  0,  3,  5,  9, 11, 18 },
@@ -559,7 +560,7 @@
 	if (GetNumIndustries() == 0) return;
 
 	/* Create array for sorting */
-	_industry_sort = realloc((void *)_industry_sort, (GetMaxIndustryIndex() + 1) * sizeof(_industry_sort[0]));
+	ReallocT(&_industry_sort, GetMaxIndustryIndex() + 1);
 	if (_industry_sort == NULL) error("Could not allocate memory for the industry-sorting-list");
 
 	FOR_ALL_INDUSTRIES(i) _industry_sort[n++] = i;
--- a/src/landscape.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/landscape.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -62,7 +62,7 @@
 	0, 0, 0, 0, 0, 0, 0, 16, 0, 0,  0, 17,  0, 15, 18, 0,
 };
 
-const byte _inclined_tileh[] = {
+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
@@ -283,7 +283,7 @@
 	return _tile_type_procs[GetTileType(tile)]->get_tile_track_status_proc(tile, mode);
 }
 
-void ChangeTileOwner(TileIndex tile, byte old_player, byte new_player)
+void ChangeTileOwner(TileIndex tile, PlayerID old_player, PlayerID new_player)
 {
 	_tile_type_procs[GetTileType(tile)]->change_tile_owner_proc(tile, old_player, new_player);
 }
@@ -475,13 +475,13 @@
 	uint y;
 	uint w;
 	uint h;
-	const Sprite* template;
+	const Sprite* templ;
 	const byte *p;
 	Tile* tile;
 	byte direction;
 
 	r = Random();
-	template = GetSprite((((r >> 24) * _genterrain_tbl_1[type]) >> 8) + _genterrain_tbl_2[type] + 4845);
+	templ = GetSprite((((r >> 24) * _genterrain_tbl_1[type]) >> 8) + _genterrain_tbl_2[type] + 4845);
 
 	x = r & MapMaxX();
 	y = (r >> MapLogX()) & MapMaxY();
@@ -491,13 +491,13 @@
 
 	direction = GB(r, 22, 2);
 	if (direction & 1) {
-		w = template->height;
-		h = template->width;
+		w = templ->height;
+		h = templ->width;
 	} else {
-		w = template->width;
-		h = template->height;
+		w = templ->width;
+		h = templ->height;
 	}
-	p = template->data;
+	p = templ->data;
 
 	if (flag & 4) {
 		uint xw = x * MapSizeY();
--- a/src/livery.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/livery.h	Mon Jan 15 20:14:06 2007 +0000
@@ -3,10 +3,12 @@
 #ifndef LIVERY_H
 #define LIVERY_H
 
+#include "helpers.hpp"
 
 /* List of different livery schemes. */
 typedef enum LiverySchemes {
-	LS_DEFAULT,
+	LS_BEGIN = 0,
+	LS_DEFAULT = 0,
 
 	/* Rail vehicles */
 	LS_STEAM,
@@ -37,6 +39,7 @@
 	LS_END
 } LiveryScheme;
 
+DECLARE_POSTFIX_INCREMENT(LiveryScheme);
 
 /* List of different livery classes, used only by the livery GUI. */
 typedef enum LiveryClasses {
--- a/src/macros.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/macros.h	Mon Jan 15 20:14:06 2007 +0000
@@ -20,9 +20,10 @@
 #undef max
 #endif
 
+static inline int max(int a, int b) { if (a >= b) return a; return b; }
+static inline double dmax(double a, double b) { if (a >= b) return a; return b; }
+static inline uint64 max64(uint64 a, uint64 b) { if (a >= b) return a; return b; }
 static inline int min(int a, int b) { if (a <= b) return a; return b; }
-static inline int max(int a, int b) { if (a >= b) return a; return b; }
-static inline int64 max64(int64 a, int64 b) { if (a >= b) return a; return b; }
 
 static inline uint minu(uint a, uint b) { if (a <= b) return a; return b; }
 static inline uint maxu(uint a, uint b) { if (a >= b) return a; return b; }
@@ -136,15 +137,11 @@
 
 #define abs myabs
 
-
 static inline int intxchg_(int *a, int b) { int t = *a; *a = b; return t; }
 #define intswap(a,b) ((b) = intxchg_(&(a), (b)))
 static inline int uintxchg_(uint *a, uint b) { uint t = *a; *a = b; return t; }
 #define uintswap(a,b) ((b) = uintxchg_(&(a), (b)))
 
-static inline int myabs(int a) { if (a<0) a = -a; return a; }
-static inline int64 myabs64(int64 a) { if (a<0) a = -a; return a; }
-
 static inline void swap_byte(byte *a, byte *b) { byte t = *a; *a = *b; *b = t; }
 static inline void swap_uint16(uint16 *a, uint16 *b) { uint16 t = *a; *a = *b; *b = t; }
 static inline void swap_int16(int16 *a, int16 *b) { int16 t = *a; *a = *b; *b = t; }
--- a/src/main_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/main_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -215,12 +215,12 @@
 
 static void MenuClickStations(int index)
 {
-	ShowPlayerStations(index);
+	ShowPlayerStations((PlayerID)index);
 }
 
 static void MenuClickFinances(int index)
 {
-	ShowPlayerFinances(index);
+	ShowPlayerFinances((PlayerID)index);
 }
 
 static void MenuClickCompany(int index)
@@ -229,7 +229,7 @@
 		ShowClientList();
 	} else {
 		if (_networking) index--;
-		ShowPlayerCompany(index);
+		ShowPlayerCompany((PlayerID)index);
 	}
 }
 
@@ -263,27 +263,27 @@
 
 static void MenuClickShowTrains(int index)
 {
-	ShowVehicleListWindow(index, INVALID_STATION, VEH_Train);
+	ShowVehicleListWindow((PlayerID)index, INVALID_STATION, VEH_Train);
 }
 
 static void MenuClickShowRoad(int index)
 {
-	ShowVehicleListWindow(index, INVALID_STATION, VEH_Road);
+	ShowVehicleListWindow((PlayerID)index, INVALID_STATION, VEH_Road);
 }
 
 static void MenuClickShowShips(int index)
 {
-	ShowVehicleListWindow(index, INVALID_STATION, VEH_Ship);
+	ShowVehicleListWindow((PlayerID)index, INVALID_STATION, VEH_Ship);
 }
 
 static void MenuClickShowAir(int index)
 {
-	ShowVehicleListWindow(index, INVALID_STATION, VEH_Aircraft);
+	ShowVehicleListWindow((PlayerID)index, INVALID_STATION, VEH_Aircraft);
 }
 
 static void MenuClickBuildRail(int index)
 {
-	_last_built_railtype = index;
+	_last_built_railtype = (RailType)index;
 	ShowBuildRailToolbar(_last_built_railtype, -1);
 }
 
@@ -1564,7 +1564,7 @@
 	return false;
 }
 
-extern Industry *CreateNewIndustry(TileIndex tile, int type);
+extern Industry *CreateNewIndustry(TileIndex tile, IndustryType type);
 
 /**
  * Search callback function for TryBuildIndustry
@@ -2283,7 +2283,7 @@
 			case '1' | WKC_ALT: /* Gimme money */
 				/* Server can not cheat in advertise mode either! */
 				if (!_networking || !_network_server || !_network_advertise)
-					DoCommandP(0, -10000000, 0, NULL, CMD_MONEY_CHEAT);
+					DoCommandP(0, 10000000, 0, NULL, CMD_MONEY_CHEAT);
 				break;
 
 			case '2' | WKC_ALT: /* Update the coordinates of all station signs */
@@ -2430,7 +2430,7 @@
 void InitializeMainGui(void)
 {
 	/* Clean old GUI values */
-	_last_built_railtype = 0;
+	_last_built_railtype = RAILTYPE_RAIL;
 }
 
 
--- a/src/map.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/map.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -7,10 +7,11 @@
 #include "macros.h"
 #include "map.h"
 #include "direction.h"
+#include "helpers.hpp"
 
 #if defined(_MSC_VER) && _MSC_VER >= 1400 /* VStudio 2005 is stupid! */
 /* Why the hell is that not in all MSVC headers?? */
-_CRTIMP void __cdecl _assert(void *, void *, unsigned);
+extern "C" _CRTIMP void __cdecl _assert(void *, void *, unsigned);
 #endif
 
 uint _map_log_x;
@@ -41,7 +42,7 @@
 	_map_tile_mask = _map_size - 1;
 
 	free(_m);
-	_m = calloc(_map_size, sizeof(*_m));
+	CallocT(&_m, _map_size);
 
 	// XXX TODO handle memory shortage more gracefully
 	if (_m == NULL) error("Failed to allocate memory for the map");
@@ -121,14 +122,14 @@
 	return INVALID_TILE;
 }
 
-const TileIndexDiffC _tileoffs_by_diagdir[] = {
+extern const TileIndexDiffC _tileoffs_by_diagdir[] = {
 	{-1,  0}, // DIAGDIR_NE
 	{ 0,  1}, // DIAGDIR_SE
 	{ 1,  0}, // DIAGDIR_SW
 	{ 0, -1}  // DIAGDIR_NW
 };
 
-const TileIndexDiffC _tileoffs_by_dir[] = {
+extern const TileIndexDiffC _tileoffs_by_dir[] = {
 	{-1, -1}, // DIR_N
 	{-1,  0}, // DIR_NE
 	{-1,  1}, // DIR_E
@@ -141,8 +142,8 @@
 
 uint DistanceManhattan(TileIndex t0, TileIndex t1)
 {
-	const uint dx = abs(TileX(t0) - TileX(t1));
-	const uint dy = abs(TileY(t0) - TileY(t1));
+	const uint dx = delta(TileX(t0), TileX(t1));
+	const uint dy = delta(TileY(t0), TileY(t1));
 	return dx + dy;
 }
 
@@ -157,16 +158,16 @@
 
 uint DistanceMax(TileIndex t0, TileIndex t1)
 {
-	const uint dx = abs(TileX(t0) - TileX(t1));
-	const uint dy = abs(TileY(t0) - TileY(t1));
+	const uint dx = delta(TileX(t0), TileX(t1));
+	const uint dy = delta(TileY(t0), TileY(t1));
 	return dx > dy ? dx : dy;
 }
 
 
 uint DistanceMaxPlusManhattan(TileIndex t0, TileIndex t1)
 {
-	const uint dx = abs(TileX(t0) - TileX(t1));
-	const uint dy = abs(TileY(t0) - TileY(t1));
+	const uint dx = delta(TileX(t0), TileX(t1));
+	const uint dy = delta(TileY(t0), TileY(t1));
 	return dx > dy ? 2 * dx + dy : 2 * dy + dx;
 }
 
--- a/src/map.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/map.h	Mon Jan 15 20:14:06 2007 +0000
@@ -67,13 +67,6 @@
 	return (y >> 4 << MapLogX()) + (x >> 4);
 }
 
-typedef byte Owner;
-enum Owners {
-	OWNER_TOWN      = 0x0F, // a town owns the tile
-	OWNER_NONE      = 0x10, // nobody owns the tile
-	OWNER_WATER     = 0x11, // "water" owns the tile
-	OWNER_END       = 0x12,
-};
 
 enum {
 	INVALID_TILE = (TileIndex)-1
--- a/src/misc.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/misc.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -611,13 +611,13 @@
 	uint i;
 
 	for (i = 0; i < count; i++) {
-		cht[i].been_used = SlReadByte();
-		cht[i].value     = SlReadByte();
+		cht[i].been_used = (SlReadByte() != 0);
+		cht[i].value     = (SlReadByte() != 0);
 	}
 }
 
 
-const ChunkHandler _misc_chunk_handlers[] = {
+extern const ChunkHandler _misc_chunk_handlers[] = {
 	{ 'MAPS', Save_MAPS,     Load_MAPS,     CH_RIFF },
 	{ 'MAPT', Save_MAPT,     Load_MAPT,     CH_RIFF },
 	{ 'MAPO', Save_MAP1,     Load_MAP1,     CH_RIFF },
--- a/src/misc_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/misc_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -40,7 +40,7 @@
 {
 	Player *p, *pp;
 	byte colour;
-	LiveryScheme scheme = GB(p1, 0, 8);
+	LiveryScheme scheme = (LiveryScheme)GB(p1, 0, 8);
 	byte state = GB(p1, 8, 2);
 
 	if (p2 >= 16) return CMD_ERROR; // max 16 colours
@@ -271,7 +271,7 @@
 	if (_networking) return CMD_ERROR;
 #endif
 	SET_EXPENSES_TYPE(EXPENSES_OTHER);
-	return (int32)p1;
+	return -(int32)p1;
 }
 
 /** Transfer funds (money) from one player to another.
@@ -296,7 +296,7 @@
 	if (flags & DC_EXEC) {
 		/* Add money to player */
 		PlayerID old_cp = _current_player;
-		_current_player = p2;
+		_current_player = (PlayerID)p2;
 		SubtractMoneyFromPlayer(-amount);
 		_current_player = old_cp;
 	}
--- a/src/misc_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/misc_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -95,7 +95,7 @@
 	w = AllocateWindowDesc(&_land_info_desc);
 	WP(w, void_d).data = &_landinfo_data;
 
-	p = GetPlayer(IsValidPlayer(_local_player) ? _local_player : 0);
+	p = GetPlayer(IsValidPlayer(_local_player) ? _local_player : PLAYER_FIRST);
 	t = ClosestTownFromTile(tile, _patches.dist_local_authority);
 
 	old_money = p->money64;
@@ -166,7 +166,7 @@
 
 	if (td.build_date != 0) {
 		SetDParam(0, td.build_date);
-		GetString(_landinfo_data[6], STR_BUILD_DATE, lastof(_landinfo_data[6]));
+	GetString(_landinfo_data[6], STR_BUILD_DATE, lastof(_landinfo_data[6]));
 	} else {
 		_landinfo_data[6][0] = '\0';
 	}
@@ -505,7 +505,7 @@
 					_errmsg_message_1,
 					238);
 		} else {
-			const Player *p = GetPlayer(GetDParamX(_errmsg_decode_params,2));
+			const Player *p = GetPlayer((PlayerID)GetDParamX(_errmsg_decode_params,2));
 			DrawPlayerFace(p->face, p->player_color, 2, 16);
 
 			DrawStringMultiCenter(
@@ -1383,7 +1383,7 @@
 {
 	/* Check if we are not a specatator who wants to generate a name..
 	    Let's use the name of player #0 for now. */
-	const Player *p = GetPlayer(IsValidPlayer(_local_player) ? _local_player : 0);
+	const Player *p = GetPlayer(IsValidPlayer(_local_player) ? _local_player : PLAYER_FIRST);
 
 	SetDParam(0, p->name_1);
 	SetDParam(1, p->name_2);
@@ -1691,7 +1691,7 @@
 
 static int32 ClickMoneyCheat(int32 p1, int32 p2)
 {
-		DoCommandP(0, -10000000, 0, NULL, CMD_MONEY_CHEAT);
+		DoCommandP(0, 10000000, 0, NULL, CMD_MONEY_CHEAT);
 		return true;
 }
 
@@ -1739,9 +1739,17 @@
 
 typedef int32 CheckButtonClick(int32, int32);
 
-enum ce_flags {CE_CLICK = 1 << 0};
+enum ce_flags_long
+{
+	CE_NONE = 0,
+	CE_CLICK = 1 << 0,
+	CE_END = 1 << 1,
+};
 
-typedef byte ce_flags;
+/** Define basic enum properties */
+template <> struct EnumPropsT<ce_flags_long> : MakeEnumPropsT<ce_flags_long, byte, CE_NONE, CE_END, CE_END> {};
+typedef TinyEnumT<ce_flags_long> ce_flags;
+
 
 typedef struct CheatEntry {
 	VarType type;          // type of selector
@@ -1754,15 +1762,15 @@
 } CheatEntry;
 
 static const CheatEntry _cheats_ui[] = {
-	{SLE_BOOL,CE_CLICK, STR_CHEAT_MONEY,          &_cheats.money.value,           &_cheats.money.been_used,           &ClickMoneyCheat,         0,  0},
-	{SLE_UINT8,      0, STR_CHEAT_CHANGE_PLAYER,  &_local_player,                 &_cheats.switch_player.been_used,   &ClickChangePlayerCheat,  0, 11},
-	{SLE_BOOL,       0, STR_CHEAT_EXTRA_DYNAMITE, &_cheats.magic_bulldozer.value, &_cheats.magic_bulldozer.been_used, NULL,                     0,  0},
-	{SLE_BOOL,       0, STR_CHEAT_CROSSINGTUNNELS,&_cheats.crossing_tunnels.value,&_cheats.crossing_tunnels.been_used,NULL,                     0,  0},
-	{SLE_BOOL,       0, STR_CHEAT_BUILD_IN_PAUSE, &_cheats.build_in_pause.value,  &_cheats.build_in_pause.been_used,  NULL,                     0,  0},
-	{SLE_BOOL,       0, STR_CHEAT_NO_JETCRASH,    &_cheats.no_jetcrash.value,     &_cheats.no_jetcrash.been_used,     NULL,                     0,  0},
-	{SLE_BOOL,       0, STR_CHEAT_SETUP_PROD,     &_cheats.setup_prod.value,      &_cheats.setup_prod.been_used,      NULL,                     0,  0},
-	{SLE_UINT8,      0, STR_CHEAT_SWITCH_CLIMATE, &_opt.landscape,                &_cheats.switch_climate.been_used,  &ClickChangeClimateCheat,-1,  4},
-	{SLE_INT32,      0, STR_CHEAT_CHANGE_DATE,    &_cur_year,                     &_cheats.change_date.been_used,     &ClickChangeDateCheat,   -1,  1},
+	{SLE_BOOL, {CE_CLICK}, STR_CHEAT_MONEY,          &_cheats.money.value,           &_cheats.money.been_used,           &ClickMoneyCheat,         0,  0},
+	{SLE_UINT8, {CE_NONE}, STR_CHEAT_CHANGE_PLAYER,  &_local_player,                 &_cheats.switch_player.been_used,   &ClickChangePlayerCheat,  0, 11},
+	{SLE_BOOL,  {CE_NONE}, STR_CHEAT_EXTRA_DYNAMITE, &_cheats.magic_bulldozer.value, &_cheats.magic_bulldozer.been_used, NULL,                     0,  0},
+	{SLE_BOOL,  {CE_NONE}, STR_CHEAT_CROSSINGTUNNELS,&_cheats.crossing_tunnels.value,&_cheats.crossing_tunnels.been_used,NULL,                     0,  0},
+	{SLE_BOOL,  {CE_NONE}, STR_CHEAT_BUILD_IN_PAUSE, &_cheats.build_in_pause.value,  &_cheats.build_in_pause.been_used,  NULL,                     0,  0},
+	{SLE_BOOL,  {CE_NONE}, STR_CHEAT_NO_JETCRASH,    &_cheats.no_jetcrash.value,     &_cheats.no_jetcrash.been_used,     NULL,                     0,  0},
+	{SLE_BOOL,  {CE_NONE}, STR_CHEAT_SETUP_PROD,     &_cheats.setup_prod.value,      &_cheats.setup_prod.been_used,      NULL,                     0,  0},
+	{SLE_UINT8, {CE_NONE}, STR_CHEAT_SWITCH_CLIMATE, &_opt.landscape,                &_cheats.switch_climate.been_used,  &ClickChangeClimateCheat,-1,  4},
+	{SLE_INT32, {CE_NONE}, STR_CHEAT_CHANGE_DATE,    &_cur_year,                     &_cheats.change_date.been_used,     &ClickChangeDateCheat,   -1,  1},
 };
 
 
@@ -1801,14 +1809,14 @@
 				bool on = (*(bool*)ce->variable);
 
 				if (ce->flags & CE_CLICK) {
-					DrawFrameRect(x + 20, y + 1, x + 30 + 9, y + 9, 0, (clk - (i * 2) == 1) ? FR_LOWERED : 0);
+					DrawFrameRect(x + 20, y + 1, x + 30 + 9, y + 9, 0, (clk - (i * 2) == 1) ? FR_LOWERED : FR_NONE);
 					if (i == 0) { // XXX - hack/hack for first element which is increase money. Told ya it's a mess
 						SetDParam64(0, 10000000);
 					} else {
 						SetDParam(0, false);
 					}
 				} else {
-					DrawFrameRect(x + 20, y + 1, x + 30 + 9, y + 9, on ? 6 : 4, on ? FR_LOWERED : 0);
+					DrawFrameRect(x + 20, y + 1, x + 30 + 9, y + 9, on ? 6 : 4, on ? FR_LOWERED : FR_NONE);
 					SetDParam(0, on ? STR_CONFIG_PATCHES_ON : STR_CONFIG_PATCHES_OFF);
 				}
 			} break;
--- a/src/mixer.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/mixer.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -85,7 +85,7 @@
 	// Mix each channel
 	for (mc = _channels; mc != endof(_channels); mc++) {
 		if (mc->active) {
-			mix_int8_to_int16(mc, buffer, samples);
+			mix_int8_to_int16(mc, (int16*)buffer, samples);
 			if (mc->samples_left == 0) MxCloseChannel(mc);
 		}
 	}
--- a/src/music/dmusic.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/music/dmusic.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -4,12 +4,10 @@
 
 #ifdef WIN32_ENABLE_DIRECTMUSIC_SUPPORT
 
-extern "C" {
-	#include "../openttd.h"
-	#include "../debug.h"
-	#include "../win32.h"
-	#include "dmusic.h"
-}
+#include "../openttd.h"
+#include "../debug.h"
+#include "../win32.h"
+#include "dmusic.h"
 
 #include <windows.h>
 #include <dmksctrl.h>
--- a/src/music_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/music_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -396,11 +396,11 @@
 		DrawFrameRect(214, 23, 280, 26, 14, FR_LOWERED);
 
 		DrawFrameRect(
-			108 + msf.music_vol / 2, 22, 111 + msf.music_vol / 2, 28, 14, 0
+			108 + msf.music_vol / 2, 22, 111 + msf.music_vol / 2, 28, 14, FR_NONE
 		);
 
 		DrawFrameRect(
-			214 + msf.effect_vol / 2, 22, 217 + msf.effect_vol / 2, 28, 14, 0
+			214 + msf.effect_vol / 2, 22, 217 + msf.effect_vol / 2, 28, 14, FR_NONE
 		);
 	} break;
 
--- a/src/network/core/packet.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/network/core/packet.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -5,6 +5,8 @@
 #include "../../stdafx.h"
 #include "../../macros.h"
 #include "../../string.h"
+#include "../../helpers.hpp"
+#include "../network_data.h"
 
 #include "packet.h"
 
@@ -24,7 +26,8 @@
  */
 Packet *NetworkSend_Init(const PacketType type)
 {
-	Packet *packet = malloc(sizeof(Packet));
+	Packet *packet;
+	MallocT(&packet, 1);
 	/* An error is inplace here, because it simply means we ran out of memory. */
 	if (packet == NULL) error("Failed to allocate Packet");
 
@@ -109,7 +112,7 @@
  */
 
 
-extern uint CloseConnection(NetworkClientState *cs);
+extern NetworkRecvStatus CloseConnection(NetworkClientState *cs);
 
 /** Is it safe to read from the packet, i.e. didn't we run over the buffer ? */
 static inline bool CanReadFromPacket(NetworkClientState *cs, const Packet *packet, const uint bytes_to_read)
--- a/src/network/core/tcp.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/network/core/tcp.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -12,6 +12,7 @@
 #include "../network_data.h"
 #include "packet.h"
 #include "tcp.h"
+#include "../../helpers.hpp"
 
 /**
  * @file tcp.c Basic functions to receive and send TCP packets.
@@ -99,7 +100,7 @@
 
 	p = cs->packet_queue;
 	while (p != NULL) {
-		res = send(cs->socket, p->buffer + p->pos, p->size - p->pos, 0);
+		res = send(cs->socket, (const char*)p->buffer + p->pos, p->size - p->pos, 0);
 		if (res == -1) {
 			int err = GET_LAST_ERROR();
 			if (err != EWOULDBLOCK) {
@@ -148,7 +149,7 @@
 	if (cs->socket == INVALID_SOCKET) return NULL;
 
 	if (cs->packet_recv == NULL) {
-		cs->packet_recv = malloc(sizeof(Packet));
+		MallocT(&cs->packet_recv, 1);
 		if (cs->packet_recv == NULL) error("Failed to allocate packet");
 		/* Set pos to zero! */
 		cs->packet_recv->pos = 0;
@@ -161,7 +162,7 @@
 	if (p->pos < sizeof(PacketSize)) {
 		while (p->pos < sizeof(PacketSize)) {
 			/* Read the size of the packet */
-			res = recv(cs->socket, p->buffer + p->pos, sizeof(PacketSize) - p->pos, 0);
+			res = recv(cs->socket, (char*)p->buffer + p->pos, sizeof(PacketSize) - p->pos, 0);
 			if (res == -1) {
 				int err = GET_LAST_ERROR();
 				if (err != EWOULDBLOCK) {
@@ -191,7 +192,7 @@
 
 	/* Read rest of packet */
 	while (p->pos < p->size) {
-		res = recv(cs->socket, p->buffer + p->pos, p->size - p->pos, 0);
+		res = recv(cs->socket, (char*)p->buffer + p->pos, p->size - p->pos, 0);
 		if (res == -1) {
 			int err = GET_LAST_ERROR();
 			if (err != EWOULDBLOCK) {
--- a/src/network/core/udp.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/network/core/udp.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -5,6 +5,7 @@
 #include "../../stdafx.h"
 #include "../../debug.h"
 #include "../../macros.h"
+#include "../../helpers.hpp"
 #include "packet.h"
 #include "udp.h"
 
@@ -92,7 +93,7 @@
 	NetworkSend_FillPacketSize(p);
 
 	/* Send the buffer */
-	res = sendto(udp, p->buffer, p->size, 0, (struct sockaddr *)recv, sizeof(*recv));
+	res = sendto(udp, (const char*)p->buffer, p->size, 0, (struct sockaddr *)recv, sizeof(*recv));
 
 	/* Check for any errors, but ignore it otherwise */
 	if (res == -1) DEBUG(net, 1, "[udp] sendto failed with: %i", GET_LAST_ERROR());
@@ -114,7 +115,7 @@
 	client_len = sizeof(client_addr);
 
 	/* Try to receive anything */
-	nbytes = recvfrom(udp, p.buffer, packet_len, 0, (struct sockaddr *)&client_addr, &client_len);
+	nbytes = recvfrom(udp, (char*)p.buffer, packet_len, 0, (struct sockaddr *)&client_addr, &client_len);
 
 	/* We got some bytes for the base header of the packet. */
 	if (nbytes > 2) {
@@ -256,7 +257,7 @@
 			uint num_grfs = NetworkRecv_uint8(cs, p);
 
 			for (i = 0; i < num_grfs; i++) {
-				c = calloc(1, sizeof(*c));
+				CallocT(&c, 1);
 				NetworkRecv_GRFIdentifier(cs, p, c);
 				HandleIncomingNetworkGameInfoGRFConfig(c);
 
@@ -290,7 +291,7 @@
 			info->map_width      = NetworkRecv_uint16(cs, p);
 			info->map_height     = NetworkRecv_uint16(cs, p);
 			info->map_set        = NetworkRecv_uint8 (cs, p);
-			info->dedicated      = NetworkRecv_uint8 (cs, p);
+			info->dedicated      = (NetworkRecv_uint8 (cs, p) != 0);
 	}
 }
 
--- a/src/network/network.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/network/network.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -7,9 +7,9 @@
 	extern const char _openttd_revision[];
 #elif defined(WITH_REV_HACK)
 	#define WITH_REV
-	const char _openttd_revision[] = WITH_REV_HACK;
+	extern const char _openttd_revision[] = WITH_REV_HACK;
 #else
-	const char _openttd_revision[] = NOREV_STRING;
+	extern const char _openttd_revision[] = NOREV_STRING;
 #endif
 
 
@@ -38,6 +38,19 @@
 #include <stdarg.h> /* va_list */
 #include "../md5.h"
 
+// global variables (declared in network_data.h)
+CommandPacket *_local_command_queue;
+
+SOCKET _udp_client_socket; // udp client socket
+SOCKET _udp_server_socket; // udp server socket
+SOCKET _udp_master_socket; // udp master socket
+
+// Here we keep track of the clients
+//  (and the client uses [0] for his own communication)
+NetworkClientState _clients[MAX_CLIENTS];
+
+
+
 // The listen socket for the server
 static SOCKET _listensocket;
 
@@ -277,7 +290,7 @@
 		STR_NETWORK_ERR_CLIENT_SERVER_FULL
 	};
 
-	if (err >= lengthof(network_error_strings)) err = 0;
+	if (err >= (ptrdiff_t)lengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL;
 
 	return GetString(buf, network_error_strings[err], last);
 }
@@ -729,7 +742,7 @@
 				p->buffer[0] = p->size & 0xFF;
 				p->buffer[1] = p->size >> 8;
 
-				send(s, p->buffer, p->size, 0);
+				send(s, (const char*)p->buffer, p->size, 0);
 				closesocket(s);
 
 				free(p);
@@ -750,7 +763,7 @@
 			p->buffer[0] = p->size & 0xFF;
 			p->buffer[1] = p->size >> 8;
 
-			send(s, p->buffer, p->size, 0);
+			send(s, (const char*)p->buffer, p->size, 0);
 			closesocket(s);
 
 			free(p);
@@ -1032,7 +1045,7 @@
 	_network_own_client_index = NETWORK_SERVER_INDEX;
 
 	/* Non-dedicated server will always be player #1 */
-	if (!_network_dedicated) _network_playas = 0;
+	if (!_network_dedicated) _network_playas = PLAYER_FIRST;
 
 	_network_clients_connected = 0;
 
--- a/src/network/network.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/network/network.h	Mon Jan 15 20:14:06 2007 +0000
@@ -59,7 +59,7 @@
 	uint16 client_index;                            // Index of the client (same as ClientState->index)
 	char client_name[NETWORK_CLIENT_NAME_LENGTH];   // Name of the client
 	byte client_lang;                               // The language of the client
-	byte client_playas;                             // As which player is this client playing (PlayerID)
+	PlayerID client_playas;                         // As which player is this client playing (PlayerID)
 	uint32 client_ip;                               // IP-address of the client (so he can be banned)
 	Date join_date;                                 // Gamedate the player has joined
 	char unique_id[NETWORK_NAME_LENGTH];            // Every play sends an unique id so we can indentify him
@@ -188,7 +188,6 @@
 void NetworkReboot(void);
 void NetworkDisconnect(void);
 
-VARDEF bool _networking;         ///< are we in networking mode?
 VARDEF bool _network_server;     ///< network-server is active
 VARDEF bool _network_available;  ///< is network mode available?
 
--- a/src/network/network_client.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/network/network_client.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -20,7 +20,7 @@
 #include "../console.h"
 #include "../variables.h"
 #include "../ai/ai.h"
-
+#include "../helpers.hpp"
 
 // This file handles all the client-commands
 
@@ -286,14 +286,14 @@
 
 	if (!MY_CLIENT->has_quit && company_info_version == NETWORK_COMPANY_INFO_VERSION) {
 		byte total;
-		byte current;
+		PlayerID current;
 
 		total = NetworkRecv_uint8(MY_CLIENT, p);
 
 		// There is no data at all..
 		if (total == 0) return NETWORK_RECV_STATUS_CLOSE_QUERY;
 
-		current = NetworkRecv_uint8(MY_CLIENT, p);
+		current = (Owner)NetworkRecv_uint8(MY_CLIENT, p);
 		if (!IsValidPlayer(current)) return NETWORK_RECV_STATUS_CLOSE_QUERY;
 
 		NetworkRecv_string(MY_CLIENT, p, _network_player_info[current].company_name, sizeof(_network_player_info[current].company_name));
@@ -325,7 +325,7 @@
 {
 	NetworkClientInfo *ci;
 	uint16 index = NetworkRecv_uint16(MY_CLIENT, p);
-	PlayerID playas = NetworkRecv_uint8(MY_CLIENT, p);
+	PlayerID playas = (Owner)NetworkRecv_uint8(MY_CLIENT, p);
 	char name[NETWORK_NAME_LENGTH];
 	char unique_id[NETWORK_NAME_LENGTH];
 
@@ -375,7 +375,7 @@
 
 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_ERROR)
 {
-	NetworkErrorCode error = NetworkRecv_uint8(MY_CLIENT, p);
+	NetworkErrorCode error = (NetworkErrorCode)NetworkRecv_uint8(MY_CLIENT, p);
 
 	switch (error) {
 		/* We made an error in the protocol, and our connection is closed.... */
@@ -410,7 +410,7 @@
 
 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_NEED_PASSWORD)
 {
-	NetworkPasswordType type = NetworkRecv_uint8(MY_CLIENT, p);
+	NetworkPasswordType type = (NetworkPasswordType)NetworkRecv_uint8(MY_CLIENT, p);
 
 	switch (type) {
 		case NETWORK_GAME_PASSWORD:
@@ -570,8 +570,9 @@
 
 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_COMMAND)
 {
-	CommandPacket *cp = malloc(sizeof(CommandPacket));
-	cp->player = NetworkRecv_uint8(MY_CLIENT, p);
+	CommandPacket *cp;
+	MallocT(&cp, 1);
+	cp->player = (PlayerID)NetworkRecv_uint8(MY_CLIENT, p);
 	cp->cmd = NetworkRecv_uint32(MY_CLIENT, p);
 	cp->p1 = NetworkRecv_uint32(MY_CLIENT, p);
 	cp->p2 = NetworkRecv_uint32(MY_CLIENT, p);
@@ -601,9 +602,9 @@
 	char name[NETWORK_NAME_LENGTH], msg[MAX_TEXT_MSG_LEN];
 	const NetworkClientInfo *ci = NULL, *ci_to;
 
-	NetworkAction action = NetworkRecv_uint8(MY_CLIENT, p);
+	NetworkAction action = (NetworkAction)NetworkRecv_uint8(MY_CLIENT, p);
 	uint16 index = NetworkRecv_uint16(MY_CLIENT, p);
-	bool self_send = NetworkRecv_uint8(MY_CLIENT, p);
+	bool self_send = (NetworkRecv_uint8(MY_CLIENT, p) != 0);
 	NetworkRecv_string(MY_CLIENT, p, msg, MAX_TEXT_MSG_LEN);
 
 	ci_to = NetworkFindClientInfoFromIndex(index);
@@ -623,7 +624,7 @@
 				if (!IsValidPlayer(ci_to->client_playas)) return NETWORK_RECV_STATUS_OKAY;
 				/* fallthrough */
 			case NETWORK_ACTION_CHAT_COMPANY: {
-				StringID str = IsValidPlayer(ci_to->client_playas) ? GetPlayer(ci_to->client_playas)->name_1 : STR_NETWORK_SPECTATORS;
+				StringID str = IsValidPlayer(ci_to->client_playas) ? GetPlayer(ci_to->client_playas)->name_1 : (uint16)STR_NETWORK_SPECTATORS;
 
 				GetString(name, str, lastof(name));
 				ci = NetworkFindClientInfoFromIndex(_network_own_client_index);
@@ -649,7 +650,7 @@
 	NetworkClientInfo *ci;
 
 	index = NetworkRecv_uint16(MY_CLIENT, p);
-	GetNetworkErrorMsg(str, NetworkRecv_uint8(MY_CLIENT, p), lastof(str));
+	GetNetworkErrorMsg(str, (NetworkErrorCode)NetworkRecv_uint8(MY_CLIENT, p), lastof(str));
 
 	ci = NetworkFindClientInfoFromIndex(index);
 	if (ci != NULL) {
--- a/src/network/network_data.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/network/network_data.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -9,11 +9,13 @@
 #include "network_client.h"
 #include "../command.h"
 #include "../callback_table.h"
+#include "../helpers.hpp"
 
 // Add a command to the local command queue
 void NetworkAddCommandQueue(NetworkClientState *cs, CommandPacket *cp)
 {
-	CommandPacket* new_cp = malloc(sizeof(*new_cp));
+	CommandPacket* new_cp;
+	MallocT(&new_cp, 1);
 
 	*new_cp = *cp;
 
@@ -29,7 +31,8 @@
 // Prepare a DoCommand to be send over the network
 void NetworkSend_Command(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback)
 {
-	CommandPacket *c = malloc(sizeof(CommandPacket));
+	CommandPacket *c;
+	MallocT(&c, 1);
 	byte temp_callback;
 
 	c->player = _local_player;
--- a/src/network/network_data.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/network/network_data.h	Mon Jan 15 20:14:06 2007 +0000
@@ -20,7 +20,7 @@
 
 typedef struct CommandPacket {
 	struct CommandPacket *next;
-	PlayerID player; /// player that is executing the command
+	PlayerByte player; /// player that is executing the command
 	uint32 cmd;    /// command being executed
 	uint32 p1;     /// parameter p1
 	uint32 p2;     /// parameter p2
@@ -120,15 +120,17 @@
 	DESTTYPE_CLIENT,    ///< Send message/notice to only a certain player (Private)
 } DestType;
 
-CommandPacket *_local_command_queue;
+// following externs are instantiated at network.cpp
+extern CommandPacket *_local_command_queue;
 
-SOCKET _udp_client_socket; // udp client socket
-SOCKET _udp_server_socket; // udp server socket
-SOCKET _udp_master_socket; // udp master socket
+extern SOCKET _udp_client_socket; // udp client socket
+extern SOCKET _udp_server_socket; // udp server socket
+extern SOCKET _udp_master_socket; // udp master socket
 
 // Here we keep track of the clients
 //  (and the client uses [0] for his own communication)
-NetworkClientState _clients[MAX_CLIENTS];
+extern NetworkClientState _clients[MAX_CLIENTS];
+
 #define DEREF_CLIENT(i) (&_clients[i])
 // This returns the NetworkClientInfo from a NetworkClientState
 #define DEREF_CLIENT_INFO(cs) (&_network_client_info[cs - _clients])
--- a/src/network/network_gamelist.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/network/network_gamelist.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -6,6 +6,7 @@
 #include "../debug.h"
 #include "network_data.h"
 #include "../newgrf_config.h"
+#include "../helpers.hpp"
 
 // This file handles the GameList
 // Also, it handles the request to a server for data about the server
@@ -25,7 +26,7 @@
 		prev_item = item;
 	}
 
-	item = malloc(sizeof(*item));
+	MallocT(&item, 1);
 	memset(item, 0, sizeof(*item));
 	item->next = NULL;
 	item->ip = ip;
--- a/src/network/network_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/network/network_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -27,6 +27,7 @@
 #include "../string.h"
 #include "../town.h"
 #include "../newgrf.h"
+#include "../helpers.hpp"
 
 #define BGC 5
 #define BTC 15
@@ -166,7 +167,7 @@
 
 	/* Create temporary array of games to use for listing */
 	free(nqld->sort_list);
-	nqld->sort_list = malloc(n * sizeof(nqld->sort_list[0]));
+	MallocT(&nqld->sort_list, n);
 	if (nqld->sort_list == NULL) error("Could not allocate memory for the network-game-sorting-list");
 	nqld->l.list_length = n;
 
@@ -221,7 +222,7 @@
 		nd->server = NULL;
 
 		WP(w, network_ql_d).sort_list = NULL;
-		ld->flags = VL_REBUILD | (_ng_sorting.order << (VL_DESC - 1));
+		ld->flags = VL_REBUILD | (_ng_sorting.order ? VL_DESC : VL_NONE);
 		ld->sort_type = _ng_sorting.criteria;
 		break;
 
@@ -787,19 +788,19 @@
 	InitializeTextBuffer(&WP(w, network_ql_d).q.text, _edit_str_buf, lengthof(_edit_str_buf), 160);
 }
 
-static byte NetworkLobbyFindCompanyIndex(byte pos)
+static PlayerID NetworkLobbyFindCompanyIndex(byte pos)
 {
-	byte i;
+	PlayerID i;
 
 	/* Scroll through all _network_player_info and get the 'pos' item
 	    that is not empty */
-	for (i = 0; i < MAX_PLAYERS; i++) {
+	for (i = PLAYER_FIRST; i < MAX_PLAYERS; i++) {
 		if (_network_player_info[i].company_name[0] != '\0') {
 			if (pos-- == 0) return i;
 		}
 	}
 
-	return 0;
+	return PLAYER_FIRST;
 }
 
 /* uses network_d WP macro */
@@ -809,7 +810,7 @@
 
 	switch (e->event) {
 	case WE_CREATE:
-		nd->company = (byte)-1;
+		nd->company = INVALID_PLAYER;
 		break;
 
 	case WE_PAINT: {
@@ -919,7 +920,7 @@
 			if (id_v >= w->vscroll.cap) return;
 
 			id_v += w->vscroll.pos;
-			nd->company = (id_v >= nd->server->info.companies_on) ? (byte)-1 : NetworkLobbyFindCompanyIndex(id_v);
+			nd->company = (id_v >= nd->server->info.companies_on) ? INVALID_PLAYER : NetworkLobbyFindCompanyIndex(id_v);
 			SetWindowDirty(w);
 		}	break;
 		case 7: /* Join company */
@@ -1411,7 +1412,7 @@
 		}
 
 		/* Draw nice progress bar :) */
-		DrawFrameRect(20, 18, (int)((w->width - 20) * progress / 100), 28, 10, 0);
+		DrawFrameRect(20, 18, (int)((w->width - 20) * progress / 100), 28, 10, FR_NONE);
 	}	break;
 
 	case WE_CLICK:
@@ -1465,9 +1466,9 @@
 {
 	if (buf[0] == '\0') return;
 	if (!_network_server) {
-		SEND_COMMAND(PACKET_CLIENT_CHAT)(NETWORK_ACTION_CHAT + type, type, dest, buf);
+		SEND_COMMAND(PACKET_CLIENT_CHAT)((NetworkAction)(NETWORK_ACTION_CHAT + type), type, dest, buf);
 	} else {
-		NetworkServer_HandleChat(NETWORK_ACTION_CHAT + type, type, dest, buf, NETWORK_SERVER_INDEX);
+		NetworkServer_HandleChat((NetworkAction)(NETWORK_ACTION_CHAT + type), type, dest, buf, NETWORK_SERVER_INDEX);
 	}
 }
 
@@ -1635,7 +1636,7 @@
 	case WE_CLICK:
 		switch (e->we.click.widget) {
 			case 3: { /* Send */
-				DestType type = GB(WP(w, querystr_d).caption, 0, 8);
+				DestType type = (DestType)GB(WP(w, querystr_d).caption, 0, 8);
 				byte dest = GB(WP(w, querystr_d).caption, 8, 8);
 				SendChat(WP(w, querystr_d).text.buf, type, dest);
 			} /* FALLTHROUGH */
@@ -1654,7 +1655,7 @@
 			_chat_tab_completion_active = false;
 			switch (HandleEditBoxKey(w, &WP(w, querystr_d), 2, e)) {
 				case 1: { /* Return */
-				DestType type = GB(WP(w, querystr_d).caption, 0, 8);
+				DestType type = (DestType)GB(WP(w, querystr_d).caption, 0, 8);
 				byte dest = GB(WP(w, querystr_d).caption, 8, 8);
 				SendChat(WP(w, querystr_d).text.buf, type, dest);
 			} /* FALLTHROUGH */
--- a/src/network/network_gui.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/network/network_gui.h	Mon Jan 15 20:14:06 2007 +0000
@@ -8,7 +8,7 @@
 #include "network_data.h"
 
 void ShowNetworkNeedPassword(NetworkPasswordType npt);
-void ShowNetworkGiveMoneyWindow(byte player); // PlayerID
+void ShowNetworkGiveMoneyWindow(PlayerID player); // PlayerID
 void ShowNetworkChatQueryWindow(DestType type, byte dest);
 void ShowJoinStatusWindow(void);
 void ShowNetworkGameWindow(void);
--- a/src/network/network_server.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/network/network_server.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -22,6 +22,7 @@
 #include "../station.h"
 #include "../variables.h"
 #include "../genworld.h"
+#include "../helpers.hpp"
 
 // This file handles all the server-commands
 
@@ -571,7 +572,7 @@
 	char name[NETWORK_CLIENT_NAME_LENGTH];
 	char unique_id[NETWORK_NAME_LENGTH];
 	NetworkClientInfo *ci;
-	byte playas;
+	PlayerID playas;
 	NetworkLanguage client_lang;
 	char client_revision[NETWORK_REVISION_LENGTH];
 
@@ -588,8 +589,8 @@
 #endif
 
 	NetworkRecv_string(cs, p, name, sizeof(name));
-	playas = NetworkRecv_uint8(cs, p);
-	client_lang = NetworkRecv_uint8(cs, p);
+	playas = (Owner)NetworkRecv_uint8(cs, p);
+	client_lang = (NetworkLanguage)NetworkRecv_uint8(cs, p);
 	NetworkRecv_string(cs, p, unique_id, sizeof(unique_id));
 
 	if (cs->has_quit) return;
@@ -654,7 +655,7 @@
 	char password[NETWORK_PASSWORD_LENGTH];
 	const NetworkClientInfo *ci;
 
-	type = NetworkRecv_uint8(cs, p);
+	type = (NetworkPasswordType)NetworkRecv_uint8(cs, p);
 	NetworkRecv_string(cs, p, password, sizeof(password));
 
 	if (cs->status == STATUS_INACTIVE && type == NETWORK_GAME_PASSWORD) {
@@ -792,7 +793,8 @@
 	const NetworkClientInfo *ci;
 	byte callback;
 
-	CommandPacket *cp = malloc(sizeof(CommandPacket));
+	CommandPacket *cp;
+	MallocT(&cp, 1);
 
 	// The client was never joined.. so this is impossible, right?
 	//  Ignore the packet, give the client a warning, and close his connection
@@ -801,7 +803,7 @@
 		return;
 	}
 
-	cp->player = NetworkRecv_uint8(cs, p);
+	cp->player = (Owner)NetworkRecv_uint8(cs, p);
 	cp->cmd    = NetworkRecv_uint32(cs, p);
 	cp->p1     = NetworkRecv_uint32(cs, p);
 	cp->p2     = NetworkRecv_uint32(cs, p);
@@ -851,7 +853,7 @@
 		/* XXX - Execute the command as a valid player. Normally this would be done by a
 		 * spectator, but that is not allowed any commands. So do an impersonation. The drawback
 		 * of this is that the first company's last_built_tile is also updated... */
-		cp->player = 0;
+		cp->player = OWNER_BEGIN;
 		cp->p2 = cs - _clients; // XXX - UGLY! p2 is mis-used to get the client-id in CmdPlayerCtrl
 	}
 
@@ -890,7 +892,7 @@
 	NetworkClientState *new_cs;
 	char str[100];
 	char client_name[NETWORK_CLIENT_NAME_LENGTH];
-	NetworkErrorCode errorno = NetworkRecv_uint8(cs, p);
+	NetworkErrorCode errorno = (NetworkErrorCode)NetworkRecv_uint8(cs, p);
 
 	// The client was never joined.. thank the client for the packet, but ignore it
 	if (cs->status < STATUS_DONE_MAP || cs->has_quit) {
@@ -1044,7 +1046,7 @@
 		if (ci != NULL && show_local) {
 			if (from_index == NETWORK_SERVER_INDEX) {
 				char name[NETWORK_NAME_LENGTH];
-				StringID str = IsValidPlayer(ci_to->client_playas) ? GetPlayer(ci_to->client_playas)->name_1 : STR_NETWORK_SPECTATORS;
+				StringID str = IsValidPlayer(ci_to->client_playas) ? GetPlayer(ci_to->client_playas)->name_1 : (uint16)STR_NETWORK_SPECTATORS;
 				GetString(name, str, lastof(name));
 				NetworkTextMessage(action, GetDrawStringPlayerColor(ci_own->client_playas), true, name, "%s", msg);
 			} else {
@@ -1073,8 +1075,8 @@
 
 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_CHAT)
 {
-	NetworkAction action = NetworkRecv_uint8(cs, p);
-	DestType desttype = NetworkRecv_uint8(cs, p);
+	NetworkAction action = (NetworkAction)NetworkRecv_uint8(cs, p);
+	DestType desttype = (DestType)NetworkRecv_uint8(cs, p);
 	int dest = NetworkRecv_uint8(cs, p);
 	char msg[MAX_TEXT_MSG_LEN];
 
--- a/src/network/network_udp.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/network/network_udp.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -335,7 +335,7 @@
 		 * the current list and do not send the other data.
 		 * The name could be an empty string, if so take the filename. */
 		packet_len += sizeof(c.grfid) + sizeof(c.md5sum) +
-				min(strlen((f->name != NULL && strlen(f->name) > 0) ? f->name : f->filename) + 1, NETWORK_GRF_NAME_LENGTH);
+				min(strlen((f->name != NULL && strlen(f->name) > 0) ? f->name : f->filename) + 1, (size_t)NETWORK_GRF_NAME_LENGTH);
 		if (packet_len > SEND_MTU - 4) { // 4 is 3 byte header + grf count in reply
 			break;
 		}
--- a/src/newgrf.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/newgrf.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -30,6 +30,7 @@
 #include "newgrf_config.h"
 #include "newgrf_sound.h"
 #include "newgrf_spritegroup.h"
+#include "helpers.hpp"
 
 /* TTDPatch extended GRF format codec
  * (c) Petr Baudis 2004 (GPL'd)
@@ -542,7 +543,7 @@
 			break;
 
 		case 0x12: /* SFX */
-			FOR_EACH_OBJECT rvi[i].sfx = grf_load_byte(&buf);
+			FOR_EACH_OBJECT rvi[i].sfx = (SoundFx)grf_load_byte(&buf);
 			break;
 
 		case 0x13: /* Power in 10hp */
@@ -627,7 +628,7 @@
 			break;
 
 		case 0x09: /* Refittable */
-			FOR_EACH_OBJECT svi[i].refittable = grf_load_byte(&buf);
+			FOR_EACH_OBJECT svi[i].refittable = (grf_load_byte(&buf) != 0);
 			break;
 
 		case 0x0A: /* Cost factor */
@@ -666,7 +667,7 @@
 			break;
 
 		case 0x10: /* SFX */
-			FOR_EACH_OBJECT svi[i].sfx = grf_load_byte(&buf);
+			FOR_EACH_OBJECT svi[i].sfx = (SoundFx)grf_load_byte(&buf);
 			break;
 
 		case 0x11: /* Cargos available for refitting */
@@ -779,7 +780,7 @@
 			break;
 
 		case 0x12: /* SFX */
-			FOR_EACH_OBJECT avi[i].sfx = grf_load_byte(&buf);
+			FOR_EACH_OBJECT avi[i].sfx = (SoundFx)grf_load_byte(&buf);
 			break;
 
 		case 0x13: /* Cargos available for refitting */
@@ -841,7 +842,7 @@
 	}
 
 	/* Allocate station specs if necessary */
-	if (_cur_grffile->stations == NULL) _cur_grffile->stations = calloc(MAX_STATIONS, sizeof(*_cur_grffile->stations));
+	if (_cur_grffile->stations == NULL) CallocT(&_cur_grffile->stations, MAX_STATIONS);
 
 	statspec = &_cur_grffile->stations[stid];
 
@@ -861,7 +862,7 @@
 				uint32 classid;
 
 				/* Property 0x08 is special; it is where the station is allocated */
-				if (statspec[i] == NULL) statspec[i] = calloc(1, sizeof(*statspec[i]));
+				if (statspec[i] == NULL) CallocT(&statspec[i], 1);
 
 				/* Swap classid because we read it in BE meaning WAYP or DFLT */
 				classid = grf_load_dword(&buf);
@@ -875,7 +876,7 @@
 				uint t;
 
 				statspec->tiles = grf_load_extended(&buf);
-				statspec->renderdata = calloc(statspec->tiles, sizeof(*statspec->renderdata));
+				CallocT(&statspec->renderdata, statspec->tiles);
 				statspec->copied_renderdata = false;
 
 				for (t = 0; t < statspec->tiles; t++) {
@@ -890,7 +891,7 @@
 						DrawTileSeqStruct *dtss;
 
 						// no relative bounding box support
-						dts->seq = realloc((void*)dts->seq, ++seq_count * sizeof(DrawTileSeqStruct));
+						ReallocT((DrawTileSeqStruct**)&dts->seq, ++seq_count);
 						dtss = (DrawTileSeqStruct*) &dts->seq[seq_count - 1];
 
 						dtss->delta_x = grf_load_byte(&buf);
@@ -956,10 +957,10 @@
 
 					//debug("l %d > %d ?", length, stat->lengths);
 					if (length > statspec->lengths) {
-						statspec->platforms = realloc(statspec->platforms, length);
+						ReallocT(&statspec->platforms, length);
 						memset(statspec->platforms + statspec->lengths, 0, length - statspec->lengths);
 
-						statspec->layouts = realloc(statspec->layouts, length * sizeof(*statspec->layouts));
+						ReallocT(&statspec->layouts, length);
 						memset(statspec->layouts + statspec->lengths, 0,
 						       (length - statspec->lengths) * sizeof(*statspec->layouts));
 
@@ -969,8 +970,7 @@
 
 					//debug("p %d > %d ?", number, stat->platforms[l]);
 					if (number > statspec->platforms[l]) {
-						statspec->layouts[l] = realloc(statspec->layouts[l],
-						                               number * sizeof(**statspec->layouts));
+						ReallocT(&statspec->layouts[l], number);
 						// We expect NULL being 0 here, but C99 guarantees that.
 						memset(statspec->layouts[l] + statspec->platforms[l], 0,
 						       (number - statspec->platforms[l]) * sizeof(**statspec->layouts));
@@ -979,7 +979,7 @@
 					}
 
 					p = 0;
-					layout = malloc(length * number);
+					MallocT(&layout, length * number);
 					for (l = 0; l < length; l++) {
 						for (p = 0; p < number; p++) {
 							layout[l * number + p] = grf_load_byte(&buf);
@@ -1075,7 +1075,7 @@
 
 				if (bridge->sprite_table == NULL) {
 					/* Allocate memory for sprite table pointers and zero out */
-					bridge->sprite_table = calloc(7, sizeof(*bridge->sprite_table));
+					CallocT(bridge->sprite_table, 7);
 				}
 
 				for (; numtables-- != 0; tableid++) {
@@ -1088,7 +1088,7 @@
 					}
 
 					if (bridge->sprite_table[tableid] == NULL) {
-						bridge->sprite_table[tableid] = malloc(32 * sizeof(**bridge->sprite_table));
+						MallocT(&bridge->sprite_table[tableid], 32);
 					}
 
 					for (sprite = 0; sprite < 32; sprite++)
@@ -1595,7 +1595,7 @@
 
 	if (setid >= _cur_grffile->spritegroups_count) {
 		// Allocate memory for new sprite group references.
-		_cur_grffile->spritegroups = realloc(_cur_grffile->spritegroups, (setid + 1) * sizeof(*_cur_grffile->spritegroups));
+		ReallocT(&_cur_grffile->spritegroups, setid + 1);
 		// Initialise new space to NULL
 		for (; _cur_grffile->spritegroups_count < (setid + 1); _cur_grffile->spritegroups_count++)
 			_cur_grffile->spritegroups[_cur_grffile->spritegroups_count] = NULL;
@@ -1640,18 +1640,18 @@
 				}
 
 				group->g.determ.num_adjusts++;
-				group->g.determ.adjusts = realloc(group->g.determ.adjusts, group->g.determ.num_adjusts * sizeof(*group->g.determ.adjusts));
+				ReallocT(&group->g.determ.adjusts, group->g.determ.num_adjusts);
 
 				adjust = &group->g.determ.adjusts[group->g.determ.num_adjusts - 1];
 
 				/* The first var adjust doesn't have an operation specified, so we set it to add. */
-				adjust->operation = group->g.determ.num_adjusts == 1 ? DSGA_OP_ADD : grf_load_byte(&buf);
+				adjust->operation = group->g.determ.num_adjusts == 1 ? DSGA_OP_ADD : (DeterministicSpriteGroupAdjustOperation)grf_load_byte(&buf);
 				adjust->variable  = grf_load_byte(&buf);
 				adjust->parameter = IS_BYTE_INSIDE(adjust->variable, 0x60, 0x80) ? grf_load_byte(&buf) : 0;
 
 				varadjust = grf_load_byte(&buf);
 				adjust->shift_num = GB(varadjust, 0, 5);
-				adjust->type      = GB(varadjust, 6, 2);
+				adjust->type      = (DeterministicSpriteGroupAdjustType)GB(varadjust, 6, 2);
 				adjust->and_mask  = grf_load_var(varsize, &buf);
 
 				if (adjust->type != DSGA_TYPE_NONE) {
@@ -1666,7 +1666,7 @@
 			} while (HASBIT(varadjust, 5));
 
 			group->g.determ.num_ranges = grf_load_byte(&buf);
-			group->g.determ.ranges = calloc(group->g.determ.num_ranges, sizeof(*group->g.determ.ranges));
+			CallocT(&group->g.determ.ranges, group->g.determ.num_ranges);
 
 			check_length(bufend - buf, 2 + (2 + 2 * varsize) * group->g.determ.num_ranges, "NewSpriteGroup (Deterministic)");
 
@@ -1698,7 +1698,7 @@
 			group->g.random.cmp_mode       = HASBIT(triggers, 7) ? RSG_CMP_ALL : RSG_CMP_ANY;
 			group->g.random.lowest_randbit = grf_load_byte(&buf);
 			group->g.random.num_groups     = grf_load_byte(&buf);
-			group->g.random.groups = calloc(group->g.random.num_groups, sizeof(*group->g.random.groups));
+			CallocT(&group->g.random.groups, group->g.random.num_groups);
 
 			check_length(bufend - buf, 2 * group->g.random.num_groups, "NewSpriteGroup (Randomized) (2)");
 
@@ -1738,8 +1738,8 @@
 
 					group->g.real.num_loaded  = num_loaded;
 					group->g.real.num_loading = num_loading;
-					if (num_loaded  > 0) group->g.real.loaded  = calloc(num_loaded,  sizeof(*group->g.real.loaded));
-					if (num_loading > 0) group->g.real.loading = calloc(num_loading, sizeof(*group->g.real.loading));
+					if (num_loaded  > 0) CallocT(&group->g.real.loaded, num_loaded);
+					if (num_loading > 0) CallocT(&group->g.real.loading, num_loading);
 
 					grfmsg(6, "NewSpriteGroup: New SpriteGroup 0x%02X, %u views, %u loaded, %u loading",
 							setid, sprites, num_loaded, num_loading);
@@ -1884,7 +1884,7 @@
 	}
 
 	if (!wagover && last_engines_count != idcount) {
-		last_engines = realloc(last_engines, idcount);
+		ReallocT(&last_engines, idcount);
 		last_engines_count = idcount;
 	}
 
@@ -2235,7 +2235,7 @@
 			return _game_mode;
 
 		case 0x9A: /* Always -1 */
-			return -1;
+			return UINT_MAX;
 
 		case 0x9D: /* TTD Platform, 00=TTDPatch, 01=OpenTTD */
 			return 1;
@@ -2249,7 +2249,7 @@
 
 			/* In-game variable. */
 			grfmsg(1, "Unsupported in-game variable 0x%02X", param);
-			return -1;
+			return UINT_MAX;
 	}
 }
 
@@ -2274,7 +2274,7 @@
 
 	/* Check if the sprite is a pseudo sprite. We can't operate on real sprites. */
 	if (type == 0xFF) {
-		_preload_sprite = malloc(num);
+		MallocT(&_preload_sprite, num);
 		FioReadBlock(_preload_sprite, num);
 	}
 
@@ -2788,7 +2788,7 @@
 								}
 
 								grfmsg(1, "GRM: Unable to allocate %d vehicles", count);
-								src1 = -1;
+								src1 = UINT_MAX;
 							}
 							break;
 						}
@@ -3026,7 +3026,7 @@
 	check_length(len, 1, "DefineGotoLabel");
 	buf++; len--;
 
-	label = malloc(sizeof(*label));
+	MallocT(&label, 1);
 	label->label    = grf_load_byte(&buf);
 	label->nfo_line = _nfo_line;
 	label->pos      = FioGetPos();
@@ -3198,7 +3198,7 @@
 	check_length(len, 1 + num_def * 4, "LoadFontGlyph");
 
 	for (i = 0; i < num_def; i++) {
-		FontSize size    = grf_load_byte(&buf);
+		FontSize size    = (FontSize)grf_load_byte(&buf);
 		uint8  num_char  = grf_load_byte(&buf);
 		uint16 base_char = grf_load_word(&buf);
 		uint c;
@@ -3489,7 +3489,7 @@
 		return;
 	}
 
-	newfile = calloc(1, sizeof(*newfile));
+	CallocT(&newfile, 1);
 
 	if (newfile == NULL) error ("Out of memory");
 
@@ -3617,7 +3617,7 @@
 	if (_preload_sprite == NULL) {
 		/* No preloaded sprite to work with; allocate and read the
 		 * pseudo sprite content. */
-		buf = malloc(num);
+		MallocT(&buf, num);
 		if (buf == NULL) error("DecodeSpecialSprite: Could not allocate memory");
 		FioReadBlock(buf, num);
 	} else {
@@ -3770,3 +3770,4 @@
 }
 
 
+
--- a/src/newgrf.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/newgrf.h	Mon Jan 15 20:14:06 2007 +0000
@@ -5,6 +5,7 @@
 
 #include "station.h"
 #include "newgrf_config.h"
+#include "helpers.hpp"
 
 typedef enum GrfLoadingStage {
 	GLS_FILESCAN,
@@ -15,6 +16,9 @@
 	GLS_END,
 } GrfLoadingStage;
 
+DECLARE_POSTFIX_INCREMENT(GrfLoadingStage);
+
+
 typedef struct GRFLabel {
 	byte label;
 	uint32 nfo_line;
--- a/src/newgrf_config.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/newgrf_config.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -12,6 +12,7 @@
 #include "network/network_data.h"
 #include "newgrf.h"
 #include "newgrf_config.h"
+#include "helpers.hpp"
 
 #include "fileio.h"
 #include "fios.h"
@@ -123,7 +124,7 @@
 	/* Clear destination as it will be overwritten */
 	ClearGRFConfigList(dst);
 	for (; src != NULL; src = src->next) {
-		c = calloc(1, sizeof(*c));
+		CallocT(&c, 1);
 		*c = *src;
 		if (src->filename != NULL) c->filename = strdup(src->filename);
 		if (src->name     != NULL) c->name     = strdup(src->name);
@@ -269,7 +270,7 @@
 			if (ext == NULL) continue;
 			if (strcasecmp(ext, ".grf") != 0) continue;
 
-			c = calloc(1, sizeof(*c));
+			CallocT(&c, 1);
 			c->filename = strdup(file);
 
 			if (FillGRFDetails(c, false)) {
@@ -374,7 +375,7 @@
 
 	if (!create) return NULL;
 
-	grf = calloc(1, sizeof(*grf));
+	CallocT(&grf, 1);
 	grf->grfid = grfid;
 	grf->next  = unknown_grfs;
 	ttd_strlcpy(grf->name, UNKNOWN_GRF_NAME_PLACEHOLDER, sizeof(grf->name));
@@ -445,7 +446,8 @@
 	GRFConfig **last = &first;
 
 	while (SlIterateArray() != -1) {
-		GRFConfig *c = calloc(1, sizeof(*c));
+		GRFConfig *c;
+		CallocT(&c, 1);
 		SlObject(c, _grfconfig_desc);
 
 		/* Append our configuration to the list */
@@ -461,7 +463,7 @@
 	AppendStaticGRFConfigs(&_grfconfig);
 }
 
-const ChunkHandler _newgrf_chunk_handlers[] = {
+extern const ChunkHandler _newgrf_chunk_handlers[] = {
 	{ 'NGRF', Save_NGRF, Load_NGRF, CH_ARRAY | CH_LAST }
 };
 
--- a/src/newgrf_engine.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/newgrf_engine.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -17,6 +17,7 @@
 #include "newgrf_spritegroup.h"
 #include "newgrf_cargo.h"
 #include "date.h"
+#include "helpers.hpp"
 
 
 
@@ -82,8 +83,7 @@
 
 	wos = &_engine_wagon_overrides[engine];
 	wos->overrides_count++;
-	wos->overrides = realloc(wos->overrides,
-		wos->overrides_count * sizeof(*wos->overrides));
+	ReallocT(&wos->overrides, wos->overrides_count);
 
 	wo = &wos->overrides[wos->overrides_count - 1];
 	/* FIXME: If we are replacing an override, release original SpriteGroup
@@ -92,7 +92,7 @@
 	wo->group = group;
 	wo->cargo = cargo;
 	wo->trains = trains;
-	wo->train_id = malloc(trains);
+	MallocT(&wo->train_id, trains);
 	memcpy(wo->train_id, train_id, trains);
 }
 
@@ -563,7 +563,7 @@
 		}
 
 		*available = false;
-		return -1;
+		return UINT_MAX;
 	}
 
 	/* Calculated vehicle parameters */
@@ -628,7 +628,7 @@
 			return v->owner;
 
 		case 0x44: /* Aircraft information */
-			if (v->type != VEH_Aircraft) return -1;
+			if (v->type != VEH_Aircraft) return UINT_MAX;
 
 			{
 				const Vehicle *w = v->next;
@@ -806,7 +806,7 @@
 	DEBUG(grf, 1, "Unhandled vehicle property 0x%X, type 0x%X", variable, v->type);
 
 	*available = false;
-	return -1;
+	return UINT_MAX;
 }
 
 
--- a/src/newgrf_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/newgrf_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -11,6 +11,7 @@
 #include "table/sprites.h"
 #include "newgrf.h"
 #include "newgrf_config.h"
+#include "helpers.hpp"
 
 
 /** Parse an integerlist string and set each found value
@@ -164,7 +165,7 @@
 						}
 
 						/* Copy GRF details from scanned list */
-						c = calloc(1, sizeof(*c));
+						CallocT(&c, 1);
 						*c = *src;
 						c->filename = strdup(src->filename);
 						if (src->name != NULL) c->name = strdup(src->name);
--- a/src/newgrf_sound.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/newgrf_sound.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -63,6 +63,6 @@
 	if (callback == CALLBACK_FAILED) return false;
 	if (callback >= GetNumOriginalSounds()) callback += file->sound_offset - GetNumOriginalSounds();
 
-	if (callback < GetNumSounds()) SndPlayVehicleFx(callback, v);
+	if (callback < GetNumSounds()) SndPlayVehicleFx((SoundFx)callback, v);
 	return true;
 }
--- a/src/newgrf_spritegroup.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/newgrf_spritegroup.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -81,7 +81,7 @@
 		case 0x10: return object->callback_param1;
 		case 0x11: return 0;
 		case 0x18: return object->callback_param2;
-		case 0x1A: return -1;
+		case 0x1A: return (uint32)-1;
 		case 0x1B: return GB(_display_opt, 0, 6);
 		case 0x1C: return object->last_value;
 		case 0x20: return _opt.landscape == LT_HILLY ? _opt.snow_line : 0xFF;
--- a/src/newgrf_station.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/newgrf_station.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -17,6 +17,7 @@
 #include "newgrf_station.h"
 #include "newgrf_spritegroup.h"
 #include "date.h"
+#include "helpers.hpp"
 
 static StationClass station_classes[STAT_CLASS_MAX];
 
@@ -31,8 +32,7 @@
  */
 void ResetStationClasses(void)
 {
-	StationClassID i;
-	for (i = 0; i < STAT_CLASS_MAX; i++) {
+	for (StationClassID i = STAT_CLASS_BEGIN; i < STAT_CLASS_MAX; i++) {
 		station_classes[i].id = 0;
 		station_classes[i].name = STR_EMPTY;
 		station_classes[i].stations = 0;
@@ -45,13 +45,13 @@
 	station_classes[0].id = 'DFLT';
 	station_classes[0].name = STR_STAT_CLASS_DFLT;
 	station_classes[0].stations = 1;
-	station_classes[0].spec = malloc(sizeof(*station_classes[0].spec));
+	MallocT(&station_classes[0].spec, 1);
 	station_classes[0].spec[0] = NULL;
 
 	station_classes[1].id = 'WAYP';
 	station_classes[1].name = STR_STAT_CLASS_WAYP;
 	station_classes[1].stations = 1;
-	station_classes[1].spec = malloc(sizeof(*station_classes[1].spec));
+	MallocT(&station_classes[1].spec, 1);
 	station_classes[1].spec[0] = NULL;
 }
 
@@ -60,17 +60,15 @@
  * @param classid A 32 bit value identifying the class.
  * @return Index into station_classes of allocated class.
  */
-StationClassID AllocateStationClass(uint32 class)
+StationClassID AllocateStationClass(uint32 cls)
 {
-	StationClassID i;
-
-	for (i = 0; i < STAT_CLASS_MAX; i++) {
-		if (station_classes[i].id == class) {
+	for (StationClassID i = STAT_CLASS_BEGIN; i < STAT_CLASS_MAX; i++) {
+		if (station_classes[i].id == cls) {
 			// ClassID is already allocated, so reuse it.
 			return i;
 		} else if (station_classes[i].id == 0) {
 			// This class is empty, so allocate it to the ClassID.
-			station_classes[i].id = class;
+			station_classes[i].id = cls;
 			return i;
 		}
 	}
@@ -150,7 +148,7 @@
 	station_class = &station_classes[statspec->sclass];
 
 	i = station_class->stations++;
-	station_class->spec = realloc(station_class->spec, station_class->stations * sizeof(*station_class->spec));
+	ReallocT(&station_class->spec, station_class->stations);
 
 	station_class->spec[i] = statspec;
 	statspec->allocated = true;
@@ -176,10 +174,9 @@
 
 const StationSpec *GetCustomStationSpecByGrf(uint32 grfid, byte localidx)
 {
-	StationClassID i;
 	uint j;
 
-	for (i = STAT_CLASS_DFLT; i < STAT_CLASS_MAX; i++) {
+	for (StationClassID i = STAT_CLASS_BEGIN; i < STAT_CLASS_MAX; i++) {
 		for (j = 0; j < station_classes[i].stations; j++) {
 			const StationSpec *statspec = station_classes[i].spec[j];
 			if (statspec == NULL) continue;
@@ -364,7 +361,7 @@
 		}
 
 		*available = false;
-		return -1;
+		return UINT_MAX;
 	}
 
 	switch (variable) {
@@ -430,7 +427,7 @@
 	DEBUG(grf, 1, "Unhandled station property 0x%X", variable);
 
 	*available = false;
-	return -1;
+	return UINT_MAX;
 }
 
 
@@ -610,7 +607,7 @@
 	if (exec) {
 		if (i >= st->num_specs) {
 			st->num_specs = i + 1;
-			st->speclist = realloc(st->speclist, st->num_specs * sizeof(*st->speclist));
+			ReallocT(&st->speclist, st->num_specs);
 
 			if (st->num_specs == 2) {
 				/* Initial allocation */
@@ -656,7 +653,7 @@
 		for (; st->speclist[st->num_specs - 1].grfid == 0 && st->num_specs > 1; st->num_specs--);
 
 		if (st->num_specs > 1) {
-			st->speclist = realloc(st->speclist, st->num_specs * sizeof(*st->speclist));
+			ReallocT(&st->speclist, st->num_specs);
 		} else {
 			free(st->speclist);
 			st->num_specs = 0;
@@ -696,7 +693,7 @@
 	if (statspec->renderdata == NULL) {
 		sprites = GetStationTileLayout(tile + axis);
 	} else {
-		sprites = &statspec->renderdata[(tile < statspec->tiles) ? tile + axis : axis];
+		sprites = &statspec->renderdata[(tile < statspec->tiles) ? tile + axis : (uint)axis];
 	}
 
 	image = sprites->ground_sprite;
--- a/src/newgrf_station.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/newgrf_station.h	Mon Jan 15 20:14:06 2007 +0000
@@ -7,13 +7,22 @@
 
 #include "engine.h"
 #include "newgrf_cargo.h"
+#include "helpers.hpp"
 
 typedef enum {
-	STAT_CLASS_DFLT,     ///< Default station class.
-	STAT_CLASS_WAYP,     ///< Waypoint class.
-	STAT_CLASS_MAX = 32, ///< Maximum number of classes.
+	STAT_CLASS_BEGIN = 0,    ///< the lowest valid value
+	STAT_CLASS_DFLT = 0,     ///< Default station class.
+	STAT_CLASS_WAYP,         ///< Waypoint class.
+	STAT_CLASS_MAX = 32,     ///< Maximum number of classes.
 } StationClassID;
 
+/** Define basic enum properties */
+template <> struct EnumPropsT<StationClassID> : MakeEnumPropsT<StationClassID, byte, STAT_CLASS_BEGIN, STAT_CLASS_MAX, STAT_CLASS_MAX> {};
+typedef TinyEnumT<StationClassID> StationClassIDByte;
+
+/** Allow incrementing of StationClassID variables */
+DECLARE_POSTFIX_INCREMENT(StationClassID);
+
 /* Station layout for given dimensions - it is a two-dimensional array
  * where index is computed as (x * platforms) + platform. */
 typedef byte *StationLayout;
--- a/src/newgrf_text.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/newgrf_text.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -20,6 +20,7 @@
 #include "newgrf.h"
 #include "newgrf_text.h"
 #include "table/control_codes.h"
+#include "helpers.hpp"
 
 #define GRFTAB  28
 #define TABSIZE 11
@@ -157,7 +158,8 @@
 
 char *TranslateTTDPatchCodes(const char *str)
 {
-	char *tmp = malloc(strlen(str) * 10 + 1); /* Allocate space to allow for expansion */
+	char *tmp;
+	MallocT(&tmp, strlen(str) * 10 + 1); /* Allocate space to allow for expansion */
 	char *d = tmp;
 	bool unicode = false;
 	WChar c;
@@ -253,7 +255,8 @@
 	}
 
 	*d = '\0';
-	return realloc(tmp, strlen(tmp) + 1);
+	ReallocT(&tmp, strlen(tmp) + 1);
+	return tmp;
 }
 
 
@@ -295,7 +298,7 @@
 
 	translatedtext = TranslateTTDPatchCodes(text_to_add);
 
-	newtext = malloc(sizeof(*newtext) + strlen(translatedtext) + 1);
+	newtext = (GRFText*)malloc(sizeof(*newtext) + strlen(translatedtext) + 1);
 	newtext->next   = NULL;
 	newtext->langid = langid_to_add;
 	strcpy(newtext->text, translatedtext);
--- a/src/news_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/news_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -74,6 +74,7 @@
 	DrawNewsBankrupcy,        /* DNC_BANKRUPCY */
 };
 
+extern GetNewsStringCallbackProc * const _get_news_string_callback[];
 GetNewsStringCallbackProc * const _get_news_string_callback[] = {
 	GetNewsStringNewTrainAvail,    /* DNC_TRAINAVAIL */
 	GetNewsStringNewRoadVehAvail,  /* DNC_ROADAVAIL */
@@ -218,7 +219,7 @@
 		if (w->viewport != NULL)
 			w->viewport->top += y - w->top;
 
-		diff = abs(w->top - y);
+		diff = delta(w->top, y);
 		w->top = y;
 
 		SetDirtyBlocks(w->left, w->top - diff, w->left + w->width, w->top + w->height);
@@ -367,14 +368,14 @@
 static const SoundFx _news_sounds[] = {
 	SND_1D_APPLAUSE,
 	SND_1D_APPLAUSE,
-	0,
-	0,
-	0,
-	0,
+	SND_BEGIN,
+	SND_BEGIN,
+	SND_BEGIN,
+	SND_BEGIN,
 	SND_1E_OOOOH,
-	0,
-	0,
-	0
+	SND_BEGIN,
+	SND_BEGIN,
+	SND_BEGIN
 };
 
 /** Get the value of an item of the news-display settings. This is
@@ -752,7 +753,7 @@
 		for (i = 0, y = 26; i != 10; i++, y += 12, click_state >>= 1, val >>= 2) {
 			bool clicked = !!(click_state & 1);
 
-			DrawFrameRect(13, y, 89, 11 + y, 3, (clicked) ? FR_LOWERED : 0);
+			DrawFrameRect(13, y, 89, 11 + y, 3, (clicked) ? FR_LOWERED : FR_NONE);
 			DrawStringCentered(((13 + 89 + 1) >> 1) + clicked, ((y + 11 + y + 1) >> 1) - 5 + clicked, message_opt[val & 0x3], 0x10);
 			DrawString(103, y + 1, i + STR_0206_ARRIVAL_OF_FIRST_VEHICLE, 0);
 		}
--- a/src/npf.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/npf.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -37,8 +37,8 @@
  */
 static uint NPFDistanceTrack(TileIndex t0, TileIndex t1)
 {
-	const uint dx = abs(TileX(t0) - TileX(t1));
-	const uint dy = abs(TileY(t0) - TileY(t1));
+	const uint dx = delta(TileX(t0), TileX(t1));
+	const uint dy = delta(TileY(t0), TileY(t1));
 
 	const uint straightTracks = 2 * min(dx, dy); /* The number of straight (not full length) tracks */
 	/* OPTIMISATION:
@@ -74,7 +74,7 @@
 	uint part1 = TileX(key1) & NPF_HASH_HALFMASK;
 	uint part2 = TileY(key1) & NPF_HASH_HALFMASK;
 
-	assert(IsValidTrackdir(key2));
+	assert(IsValidTrackdir((Trackdir)key2));
 	assert(IsValidTile(key1));
 	return ((part1 << NPF_HASH_HALFBITS | part2) + (NPF_HASH_SIZE * key2 / TRACKDIR_END)) % NPF_HASH_SIZE;
 }
@@ -137,7 +137,7 @@
 
 	if (dist < ftd->best_bird_dist) {
 		ftd->best_bird_dist = dist;
-		ftd->best_trackdir = current->user_data[NPF_TRACKDIR_CHOICE];
+		ftd->best_trackdir = (Trackdir)current->user_data[NPF_TRACKDIR_CHOICE];
 	}
 	return dist;
 }
@@ -188,7 +188,7 @@
 
 static uint NPFSlopeCost(AyStarNode* current)
 {
-	TileIndex next = current->tile + TileOffsByDiagDir(TrackdirToExitdir(current->direction));
+	TileIndex next = current->tile + TileOffsByDiagDir(TrackdirToExitdir((Trackdir)current->direction));
 	int x,y;
 	int8 z1,z2;
 
@@ -294,7 +294,7 @@
 
 	/* Check for turns. Road vehicles only really drive diagonal, turns are
 	 * represented by non-diagonal tracks */
-	if (!IsDiagonalTrackdir(current->direction))
+	if (!IsDiagonalTrackdir((Trackdir)current->direction))
 		cost += _patches.npf_road_curve_penalty;
 
 	NPFMarkTile(tile);
@@ -411,7 +411,7 @@
 {
 	/* It's not worth caching the result with NPF_FLAG_IS_TARGET here as below,
 	 * since checking the cache not that much faster than the actual check */
-	return IsTileDepotType(current->path.node.tile, as->user_data[NPF_TYPE]) ?
+	return IsTileDepotType(current->path.node.tile, (TransportType)as->user_data[NPF_TYPE]) ?
 		AYSTAR_FOUND_END_NODE : AYSTAR_DONE;
 }
 
@@ -519,8 +519,9 @@
 	DiagDirection src_exitdir = TrackdirToExitdir(src_trackdir);
 	TileIndex dst_tile = INVALID_TILE;
 	int i;
-	TrackdirBits trackdirbits, ts;
-	TransportType type = aystar->user_data[NPF_TYPE];
+	uint32 ts;
+	TrackdirBits trackdirbits;
+	TransportType type = (TransportType)aystar->user_data[NPF_TYPE];
 	bool override_dst_check = false;
 	/* Initialize to 0, so we can jump out (return) somewhere an have no neighbours */
 	aystar->num_neighbours = 0;
@@ -592,13 +593,13 @@
 
 	/* check correct rail type (mono, maglev, etc) */
 	if (type == TRANSPORT_RAIL) {
-		RailType dst_type = GetTileRailType(dst_tile, src_trackdir);
+		RailType dst_type = GetTileRailType(dst_tile, TrackdirToTrack(src_trackdir));
 		if (!HASBIT(aystar->user_data[NPF_RAILTYPES], dst_type))
 			return;
 	}
 
 	/* Check the owner of the tile */
-	if (!VehicleMayEnterTile(aystar->user_data[NPF_OWNER], dst_tile, TrackdirToExitdir(src_trackdir))) {
+	if (!VehicleMayEnterTile((Owner)aystar->user_data[NPF_OWNER], dst_tile, TrackdirToExitdir(src_trackdir))) {
 		return;
 	}
 
@@ -619,7 +620,7 @@
 	} else {
 		ts = GetTileTrackStatus(dst_tile, type);
 	}
-	trackdirbits = ts & TRACKDIR_BIT_MASK; /* Filter out signal status and the unused bits */
+	trackdirbits = (TrackdirBits)(ts & TRACKDIR_BIT_MASK); /* Filter out signal status and the unused bits */
 
 	DEBUG(npf, 4, "Next node: (%d, %d) [%d], possible trackdirs: 0x%X", TileX(dst_tile), TileY(dst_tile), dst_tile, trackdirbits);
 	/* Select only trackdirs we can reach from our current trackdir */
@@ -632,9 +633,7 @@
 	i = 0;
 	/* Enumerate possible track */
 	while (trackdirbits != 0) {
-		Trackdir dst_trackdir;
-		dst_trackdir =  FindFirstBit2x64(trackdirbits);
-		trackdirbits = KillFirstBit2x64(trackdirbits);
+		Trackdir dst_trackdir = RemoveFirstTrackdir(trackdirbits);
 		DEBUG(npf, 5, "Expanded into trackdir: %d, remaining trackdirs: 0x%X", dst_trackdir, trackdirbits);
 
 		/* Check for oneway signal against us */
@@ -744,7 +743,7 @@
 
 NPFFoundTargetData NPFRouteToStationOrTile(TileIndex tile, Trackdir trackdir, NPFFindStationOrTileData* target, TransportType type, Owner owner, RailTypeMask railtypes)
 {
-	return NPFRouteToStationOrTileTwoWay(tile, trackdir, INVALID_TILE, 0, target, type, owner, railtypes);
+	return NPFRouteToStationOrTileTwoWay(tile, trackdir, INVALID_TILE, INVALID_TRACKDIR, target, type, owner, railtypes);
 }
 
 NPFFoundTargetData NPFRouteToDepotBreadthFirstTwoWay(TileIndex tile1, Trackdir trackdir1, TileIndex tile2, Trackdir trackdir2, TransportType type, Owner owner, RailTypeMask railtypes, uint reverse_penalty)
@@ -768,7 +767,7 @@
 
 NPFFoundTargetData NPFRouteToDepotBreadthFirst(TileIndex tile, Trackdir trackdir, TransportType type, Owner owner, RailTypeMask railtypes)
 {
-	return NPFRouteToDepotBreadthFirstTwoWay(tile, trackdir, INVALID_TILE, 0, type, owner, railtypes, 0);
+	return NPFRouteToDepotBreadthFirstTwoWay(tile, trackdir, INVALID_TILE, INVALID_TRACKDIR, type, owner, railtypes, 0);
 }
 
 NPFFoundTargetData NPFRouteToDepotTrialError(TileIndex tile, Trackdir trackdir, TransportType type, Owner owner, RailTypeMask railtypes)
@@ -832,7 +831,7 @@
 	best_result.best_bird_dist = (uint)-1;
 
 	/* Just iterate the depots in order of increasing distance */
-	while ((current = depots.pop(&depots))) {
+	while ((current = (Depot*)depots.pop(&depots))) {
 		/* Check to see if we already have a path shorter than this
 		 * depot's manhattan distance. HACK: We call DistanceManhattan
 		 * again, we should probably modify the queue to give us that
--- a/src/oldloader.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/oldloader.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -80,6 +80,8 @@
 	OC_END       = 0 ///< End of the whole chunk, all 32bits set to zero
 } OldChunkType;
 
+DECLARE_ENUM_AS_BIT_SET(OldChunkType);
+
 typedef bool OldChunkProc(LoadgameState *ls, int num);
 
 typedef struct OldChunks {
@@ -97,9 +99,9 @@
 static uint32 _bump_assert_value;
 static bool   _read_ttdpatch_flags;
 
-static OldChunkType GetOldChunkType(OldChunkType type)     {return GB(type, 0, 8);}
-static OldChunkType GetOldChunkVarType(OldChunkType type)  {return GB(type, 8, 8) << 8;}
-static OldChunkType GetOldChunkFileType(OldChunkType type) {return GB(type, 16, 8) << 16;}
+static OldChunkType GetOldChunkType(OldChunkType type)     {return (OldChunkType)GB(type, 0, 8);}
+static OldChunkType GetOldChunkVarType(OldChunkType type)  {return (OldChunkType)(GB(type, 8, 8) << 8);}
+static OldChunkType GetOldChunkFileType(OldChunkType type) {return (OldChunkType)(GB(type, 16, 8) << 16);}
 
 static inline byte CalcOldVarLen(OldChunkType type)
 {
@@ -189,10 +191,10 @@
 static bool LoadChunk(LoadgameState *ls, void *base, const OldChunks *chunks)
 {
 	const OldChunks *chunk = chunks;
-	byte *base_ptr = base;
+	byte *base_ptr = (byte*)base;
 
 	while (chunk->type != OC_END) {
-		byte* ptr = chunk->ptr;
+		byte* ptr = (byte*)chunk->ptr;
 		uint i;
 
 		for (i = 0; i < chunk->amount; i++) {
@@ -959,9 +961,9 @@
 
 static bool LoadOldPlayer(LoadgameState *ls, int num)
 {
-	Player *p = GetPlayer(num);
+	Player *p = GetPlayer((PlayerID)num);
 
-	_current_player_id = num;
+	_current_player_id = (PlayerID)num;
 
 	if (!LoadChunk(ls, p, player_chunk)) return false;
 
@@ -996,7 +998,7 @@
 	 * really figured out as of now, p->ai.cur_veh; needed for 'sell vehicle'
 	 * is NULL and the function will crash. To fix this, just change the state
 	 * to some harmless state, like 'loop vehicle'; 1 */
-	if (!IsHumanPlayer(num) && p->ai.state == 20) p->ai.state = 1;
+	if (!IsHumanPlayer((PlayerID)num) && p->ai.state == 20) p->ai.state = 1;
 
 	if (p->is_ai && (!_networking || _network_server) && _ai.enabled)
 		AI_StartNewAI(p->index);
--- a/src/oldpool.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/oldpool.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -5,6 +5,7 @@
 #include "debug.h"
 #include "functions.h"
 #include "oldpool.h"
+#include "helpers.hpp"
 
 /**
  * Clean a pool in a safe way (does free all blocks)
@@ -49,11 +50,11 @@
 	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);
 
 	/* Increase the poolsize */
-	pool->blocks = realloc(pool->blocks, sizeof(pool->blocks[0]) * (pool->current_blocks + 1));
+	ReallocT(&pool->blocks, pool->current_blocks + 1);
 	if (pool->blocks == NULL) error("Pool: (%s) could not allocate memory for blocks", pool->name);
 
 	/* Allocate memory to the new block item */
-	pool->blocks[pool->current_blocks] = malloc(pool->item_size * (1 << pool->block_size_bits));
+	MallocT(&pool->blocks[pool->current_blocks], 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);
 
--- a/src/oldpool.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/oldpool.h	Mon Jan 15 20:14:06 2007 +0000
@@ -16,11 +16,11 @@
  *  please try to avoid manual calls!
  */
 struct OldMemoryPool {
-	const char* const name;     ///< Name of the pool (just for debugging)
+	const char* name;     ///< Name of the pool (just for debugging)
 
-	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
-	const uint item_size;       ///< How many bytes one block is
+	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
 
 	/// Pointer to a function that is called after a new block is added
 	OldMemoryPoolNewBlock *new_block_proc;
--- a/src/openttd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/openttd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -1,6 +1,7 @@
 /* $Id$ */
 
 #include "stdafx.h"
+#define VARDEF
 #include "string.h"
 #include "table/strings.h"
 #include "debug.h"
@@ -10,8 +11,8 @@
 #include "map.h"
 #include "tile.h"
 #include "void_map.h"
+#include "helpers.hpp"
 
-#define VARDEF
 #include "openttd.h"
 #include "bridge_map.h"
 #include "functions.h"
@@ -73,7 +74,7 @@
 void DeleteAllPlayerStations(void);
 
 extern void SetDifficultyLevel(int mode, GameOptions *gm_opt);
-extern void DoStartupNewPlayer(bool is_ai);
+extern Player* DoStartupNewPlayer(bool is_ai);
 extern void ShowOSErrorBox(const char *buf);
 
 /* TODO: usrerror() for errors which are not of an internal nature but
@@ -119,7 +120,7 @@
 	fseek(in, 0, SEEK_END);
 	len = ftell(in);
 	fseek(in, 0, SEEK_SET);
-	if (len > maxsize || (mem = malloc(len + 1)) == NULL) {
+	if (len > maxsize || !MallocT(&mem, len + 1)) {
 		fclose(in);
 		return NULL;
 	}
@@ -135,9 +136,9 @@
 	return mem;
 }
 
+extern const char _openttd_revision[];
 static void showhelp(void)
 {
-	extern const char _openttd_revision[];
 	char buf[4096], *p;
 
 	p = buf;
@@ -175,25 +176,26 @@
 }
 
 
-typedef struct {
+struct MyGetOptData {
 	char *opt;
 	int numleft;
 	char **argv;
 	const char *options;
-	char *cont;
-} MyGetOptData;
+	const char *cont;
 
-static void MyGetOptInit(MyGetOptData *md, int argc, char **argv, const char *options)
-{
-	md->cont = NULL;
-	md->numleft = argc;
-	md->argv = argv;
-	md->options = options;
-}
+	MyGetOptData(int argc, char **argv, const char *options)
+	{
+		opt = NULL;
+		numleft = argc;
+		this->argv = argv;
+		this->options = options;
+		cont = NULL;
+	}
+};
 
 static int MyGetOpt(MyGetOptData *md)
 {
-	char *s,*r,*t;
+	const char *s,*r,*t;
 
 	s = md->cont;
 	if (s != NULL)
@@ -226,7 +228,7 @@
 							md->argv++;
 						}
 					}
-					md->opt = t;
+					md->opt = (char*)t;
 					md->cont = NULL;
 					return *s;
 				}
@@ -244,7 +246,7 @@
 
 static void ParseResolution(int res[2], const char *s)
 {
-	char *t = strchr(s, 'x');
+	const char *t = strchr(s, 'x');
 	if (t == NULL) {
 		ShowInfoF("Invalid resolution '%s'", s);
 		return;
@@ -308,7 +310,7 @@
 	}
 
 	_pause = 0;
-	SetLocalPlayer(0);
+	SetLocalPlayer(PLAYER_FIRST);
 	/* Make sure you can't scroll in the menu */
 	_scrolling_viewport = 0;
 	_cursor.fix_at = false;
@@ -324,7 +326,6 @@
 
 int ttd_main(int argc, char *argv[])
 {
-	MyGetOptData mgo;
 	int i;
 	const char *optformat;
 	char musicdriver[16], sounddriver[16], videodriver[16];
@@ -356,7 +357,8 @@
 #endif
 	;
 
-	MyGetOptInit(&mgo, argc-1, argv+1, optformat);
+	MyGetOptData mgo(argc-1, argv+1, optformat);
+
 	while ((i = MyGetOpt(&mgo)) != -1) {
 		switch (i) {
 		case 'm': ttd_strlcpy(musicdriver, mgo.opt, sizeof(musicdriver)); break;
@@ -512,7 +514,7 @@
 			ParseConnectionString(&player, &port, network_conn);
 
 			if (player != NULL) {
-				_network_playas = atoi(player);
+				_network_playas = (PlayerID)atoi(player);
 
 				if (_network_playas != PLAYER_SPECTATOR) {
 					_network_playas--;
@@ -628,7 +630,7 @@
 	/* Create a single player */
 	DoStartupNewPlayer(false);
 
-	SetLocalPlayer(0);
+	SetLocalPlayer(PLAYER_FIRST);
 	_current_player = _local_player;
 	DoCommandP(0, (_patches.autorenew << 15 ) | (_patches.autorenew_months << 16) | 4, _patches.autorenew_money, NULL, CMD_SET_AUTOREPLACE);
 
@@ -708,7 +710,7 @@
 	StartupEngines();
 	StartupDisasters();
 
-	SetLocalPlayer(0);
+	SetLocalPlayer(PLAYER_FIRST);
 	_current_player = _local_player;
 	DoCommandP(0, (_patches.autorenew << 15 ) | (_patches.autorenew_months << 16) | 4, _patches.autorenew_money, NULL, CMD_SET_AUTOREPLACE);
 
@@ -799,7 +801,7 @@
 		} else {
 			/* Update the local player for a loaded game. It is either always
 			 * player #1 (eg 0) or in the case of a dedicated server a spectator */
-			SetLocalPlayer(_network_dedicated ? PLAYER_SPECTATOR : 0);
+			SetLocalPlayer(_network_dedicated ? PLAYER_SPECTATOR : PLAYER_FIRST);
 			DoCommandP(0, 0, 0, NULL, CMD_PAUSE); // decrease pause counter (was increased from opening load dialog)
 #ifdef ENABLE_NETWORK
 			if (_network_server) {
@@ -1096,7 +1098,7 @@
 	Town *t;
 
 	FOR_ALL_TOWNS(t) {
-		t->exclusivity = (byte)-1;
+		t->exclusivity = INVALID_PLAYER;
 	}
 
 	/* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
@@ -1312,8 +1314,8 @@
 		 * becomes player 0, unless we are in the scenario editor where all the
 		 * players are 'invalid'.
 		 */
-		if (!_network_dedicated && IsValidPlayer(0)) {
-			p = GetPlayer(0);
+		if (!_network_dedicated && IsValidPlayer(PLAYER_FIRST)) {
+			p = GetPlayer(PLAYER_FIRST);
 			p->engine_renew        = _patches.autorenew;
 			p->engine_renew_months = _patches.autorenew_months;
 			p->engine_renew_money  = _patches.autorenew_money;
@@ -1375,7 +1377,7 @@
 		for (tile = 0; tile != MapSize(); tile++) {
 			if (IsTileType(tile, MP_TUNNEL)) {
 				if (HASBIT(_m[tile].m5, 7)) { /* Bridge */
-					DiagDirection dd = GB(_m[tile].m5, 0, 2);
+					DiagDirection dd = (DiagDirection)GB(_m[tile].m5, 0, 2);
 					SB(_m[tile].m5, 0, 2, 0);
 					if (GB(_m[tile].m5, 2, 2) == 0) { /* Railway Bridge */
 						SetTileType(tile, MP_RAILWAY_BRIDGE);
@@ -1421,7 +1423,7 @@
 				continue;
 			}
 			if (v->type == VEH_Train) {
-				v->u.rail.track = 0x40;
+				v->u.rail.track = TRACK_BIT_WORMHOLE;
 			} else {
 				v->u.road.state = 0xFF;
 			}
@@ -1597,10 +1599,9 @@
 	{
 		/* Set up the engine count for all players */
 		Player *players[MAX_PLAYERS];
-		int i;
 		const Vehicle *v;
 
-		for (i = 0; i < MAX_PLAYERS; i++) players[i] = GetPlayer(i);
+		for (PlayerID i = PLAYER_FIRST; i < MAX_PLAYERS; i++) players[i] = GetPlayer(i);
 
 		FOR_ALL_VEHICLES(v) {
 			if (!IsEngineCountable(v)) continue;
@@ -1732,3 +1733,25 @@
 	/* redraw the whole screen */
 	MarkWholeScreenDirty();
 }
+
+HalMusicDriver *_music_driver;
+HalSoundDriver *_sound_driver;
+HalVideoDriver *_video_driver;
+
+byte _dirkeys;        // 1 = left, 2 = up, 4 = right, 8 = down
+bool _fullscreen;
+CursorVars _cursor;
+bool _ctrl_pressed;   // Is Ctrl pressed?
+bool _shift_pressed;  // Is Shift pressed?
+byte _fast_forward;
+bool _left_button_down;
+bool _left_button_clicked;
+bool _right_button_down;
+bool _right_button_clicked;
+DrawPixelInfo _screen;
+bool _exit_game;
+bool _networking;         ///< are we in networking mode?
+byte _game_mode;
+byte _pause;
+int _pal_first_dirty;
+int _pal_last_dirty;
--- a/src/openttd.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/openttd.h	Mon Jan 15 20:14:06 2007 +0000
@@ -8,9 +8,8 @@
 #define VARDEF extern
 #endif
 
-typedef struct Rect {
-	int left,top,right,bottom;
-} Rect;
+#include "hal.h"
+#include "helpers.hpp"
 
 typedef struct Oblong {
 	int x, y;
@@ -22,10 +21,6 @@
 	int height;
 } BoundingRect;
 
-typedef struct Point {
-	int x,y;
-} Point;
-
 typedef struct Pair {
 	int a;
 	int b;
@@ -45,13 +40,11 @@
 typedef struct NewsItem NewsItem;
 typedef struct Industry Industry;
 typedef struct DrawPixelInfo DrawPixelInfo;
-typedef byte PlayerID;
 typedef byte VehicleOrderID;  ///< The index of an order within its current vehicle (not pool related)
 typedef byte CargoID;
 typedef byte LandscapeID;
 typedef uint32 SpriteID;      ///< The number of a sprite, without mapping bits and colortables
 typedef uint32 PalSpriteID;   ///< The number of a sprite plus all the mapping bits and colortables
-typedef uint32 CursorID;
 typedef uint16 EngineID;
 typedef uint16 UnitID;
 typedef uint16 StringID;
@@ -77,7 +70,7 @@
 assert_compile(sizeof(DestinationID) == sizeof(WaypointID));
 assert_compile(sizeof(DestinationID) == sizeof(StationID));
 
-typedef uint32 WindowNumber;
+typedef int32 WindowNumber;
 typedef byte WindowClass;
 
 enum {
@@ -89,12 +82,6 @@
 typedef int32 Date;
 
 
-enum GameModes {
-	GM_MENU,
-	GM_NORMAL,
-	GM_EDITOR
-};
-
 enum SwitchModes {
 	SM_NONE            =  0,
 	SM_NEWGAME         =  1,
@@ -124,6 +111,32 @@
 	IG_DATE_RESET = 1,  /* Reset the date when initializing a game */
 };
 
+enum Owner {
+	PLAYER_INACTIVE_CLIENT = 253,
+	PLAYER_NEW_COMPANY = 254,
+	PLAYER_SPECTATOR = 255,
+	OWNER_BEGIN     = 0x00,
+	PLAYER_FIRST    = 0x00,
+	MAX_PLAYERS     = 8,
+	OWNER_TOWN      = 0x0F, // a town owns the tile
+	OWNER_NONE      = 0x10, // nobody owns the tile
+	OWNER_WATER     = 0x11, // "water" owns the tile
+	OWNER_END       = 0x12,
+	INVALID_OWNER   = 0xFF,
+	INVALID_PLAYER  = 0xFF,
+	/* Player identifiers All players below MAX_PLAYERS are playable
+	* players, above, they are special, computer controlled players */
+};
+
+typedef Owner PlayerID;
+
+DECLARE_POSTFIX_INCREMENT(Owner);
+
+/** Define basic enum properties */
+template <> struct EnumPropsT<Owner> : MakeEnumPropsT<Owner, byte, OWNER_BEGIN, OWNER_END, INVALID_OWNER> {};
+typedef TinyEnumT<Owner> OwnerByte;
+typedef OwnerByte PlayerByte;
+
 
 typedef enum TransportTypes {
 	/* These constants are for now linked to the representation of bridges
@@ -132,6 +145,7 @@
 	 * accessing tunnels and bridges. For now, you should just not change
 	 * the values for road and rail.
 	 */
+	TRANSPORT_BEGIN = 0,
 	TRANSPORT_RAIL = 0,
 	TRANSPORT_ROAD = 1,
 	TRANSPORT_WATER, // = 2
@@ -139,6 +153,11 @@
 	INVALID_TRANSPORT = 0xff,
 } TransportType;
 
+/** Define basic enum properties */
+template <> struct EnumPropsT<TransportType> : MakeEnumPropsT<TransportType, byte, TRANSPORT_BEGIN, TRANSPORT_END, INVALID_TRANSPORT> {};
+typedef TinyEnumT<TransportType> TransportTypeByte;
+
+
 typedef struct TileInfo {
 	uint x;
 	uint y;
--- a/src/order.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/order.h	Mon Jan 15 20:14:06 2007 +0000
@@ -10,11 +10,13 @@
 
 enum {
 	INVALID_VEH_ORDER_ID = 0xFF,
-	INVALID_ORDER        = 0xFFFF,
 };
 
+static const OrderID INVALID_ORDER = 0xFFFF;
+
 /* Order types */
-enum OrderTypes {
+enum OrderType {
+	OT_BEGIN         = 0,
 	OT_NOTHING       = 0,
 	OT_GOTO_STATION  = 1,
 	OT_GOTO_DEPOT    = 2,
@@ -22,9 +24,14 @@
 	OT_LEAVESTATION  = 4,
 	OT_DUMMY         = 5,
 	OT_GOTO_WAYPOINT = 6,
+	OT_END
 };
+
 /* It needs to be 8bits, because we save and load it as such */
-typedef uint8 OrderType;
+/** Define basic enum properties */
+template <> struct EnumPropsT<OrderType> : MakeEnumPropsT<OrderType, byte, OT_BEGIN, OT_END, OT_END> {};
+typedef TinyEnumT<OrderType> OrderTypeByte;
+
 
 /* Order flags -- please use OFB instead OF and use HASBIT/SETBIT/CLEARBIT */
 
@@ -82,7 +89,7 @@
  * - REF_SHEDULE (all REFs are currently limited to 16 bits!!)
  */
 typedef struct Order {
-	OrderType type;
+	OrderTypeByte type;
 	uint8  flags;
 	DestinationID dest;   ///< The destionation of the order.
 
--- a/src/order_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/order_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -38,7 +38,7 @@
 Order UnpackOldOrder(uint16 packed)
 {
 	Order order;
-	order.type    = GB(packed, 0, 4);
+	order.type    = (OrderType)GB(packed, 0, 4);
 	order.flags   = GB(packed, 4, 4);
 	order.dest    = GB(packed, 8, 8);
 	order.next    = NULL;
@@ -65,7 +65,7 @@
 static Order UnpackVersion4Order(uint16 packed)
 {
 	Order order;
-	order.type  = GB(packed, 0, 4);
+	order.type  = (OrderType)GB(packed, 0, 4);
 	order.flags = GB(packed, 4, 4);
 	order.dest  = GB(packed, 8, 8);
 	order.next  = NULL;
@@ -359,12 +359,12 @@
 
 	if (flags & DC_EXEC) {
 		Vehicle *u;
-		Order *new = AllocateOrder();
-		AssignOrder(new, new_order);
+		Order *new_o = AllocateOrder();
+		AssignOrder(new_o, new_order);
 
 		/* Create new order and link in list */
 		if (v->orders == NULL) {
-			v->orders = new;
+			v->orders = new_o;
 		} else {
 			/* Try to get the previous item (we are inserting above the
 			    selected) */
@@ -375,17 +375,17 @@
 				    But because the orders can be shared, we copy the info over
 				    the v->orders, so we don't have to change the pointers of
 				    all vehicles */
-				SwapOrders(v->orders, new);
+				SwapOrders(v->orders, new_o);
 				/* Now update the next pointers */
-				v->orders->next = new;
+				v->orders->next = new_o;
 			} else if (order == NULL) {
 				/* 'sel' is a non-existing order, add him to the end */
 				order = GetLastVehicleOrder(v);
-				order->next = new;
+				order->next = new_o;
 			} else {
 				/* Put the new order in between */
-				new->next = order->next;
-				order->next = new;
+				new_o->next = order->next;
+				order->next = new_o;
 			}
 		}
 
@@ -616,7 +616,7 @@
 				 * whether we are not going to a depot as there are three
 				 * cases where the full load flag can be active and only
 				 * one case where the flag is used for depot orders. In the
-				 * other cases for the OrderType the flags are not used,
+				 * other cases for the OrderTypeByte the flags are not used,
 				 * so do not care and those orders should not be active
 				 * when this function is called.
 				 */
@@ -1273,6 +1273,6 @@
 	}
 }
 
-const ChunkHandler _order_chunk_handlers[] = {
+extern const ChunkHandler _order_chunk_handlers[] = {
 	{ 'ORDR', Save_ORDR, Load_ORDR, CH_ARRAY | CH_LAST},
 };
--- a/src/os/macosx/macos.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/os/macosx/macos.h	Mon Jan 15 20:14:06 2007 +0000
@@ -11,9 +11,15 @@
  * the function then adds text that tells the user to update and then report the bug if it's present in the newest version
  * It also quits in a nice way since we call it when we know something happened that will crash OpenTTD (like a needed pointer turns out to be NULL or similar)
  */
-void ShowMacDialog ( const char *title, const char *message, const char *buttonLabel );
-void ShowMacAssertDialog ( const char *function, const char *file, const int line, const char *expression );
-void ShowMacErrorDialog(const char *error);
+#ifdef __cplusplus
+extern "C" {
+#endif //__cplusplus
+	void ShowMacDialog ( const char *title, const char *message, const char *buttonLabel );
+	void ShowMacAssertDialog ( const char *function, const char *file, const int line, const char *expression );
+	void ShowMacErrorDialog(const char *error);
+#ifdef __cplusplus
+}
+#endif //__cplusplus
 
 // Since MacOS X users will never see an assert unless they started the game from a terminal
 // we're using a custom assert(e) macro.
--- a/src/os/macosx/macos.m	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/os/macosx/macos.m	Mon Jan 15 20:14:06 2007 +0000
@@ -8,11 +8,7 @@
 #include <mach/machine.h>
 #include <stdio.h>
 #include "../../stdafx.h"
-#include "../../openttd.h"
-#include "../../newgrf.h"
-#include "../../gfx.h"
 #include "../../macros.h"
-#include "../../string.h"
 
 #ifndef CPU_SUBTYPE_POWERPC_970
 #define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
@@ -26,6 +22,8 @@
  * To insure that the crosscompiler still works, let him try any changes before they are committed
  */
 
+void ToggleFullScreen(bool fs);
+
 static char *GetOSString(void)
 {
 	static char buffer[175];
@@ -74,7 +72,7 @@
 	}
 
 	// make a list of used newgrf files
-	if (_first_grffile != NULL) {
+/*	if (_first_grffile != NULL) {
 		char* n = newgrf;
 		const GRFFile* file;
 
@@ -82,9 +80,9 @@
 			n = strecpy(n, " ", lastof(newgrf));
 			n = strecpy(n, file->filename, lastof(newgrf));
 		}
-	} else {
+	} else {*/
 		sprintf(newgrf, "none");
-	}
+//	}
 
 	snprintf(
 		buffer, lengthof(buffer),
--- a/src/os/macosx/splash.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/os/macosx/splash.h	Mon Jan 15 20:14:06 2007 +0000
@@ -5,6 +5,14 @@
 
 #define SPLASH_IMAGE_FILE		"splash.png"
 
-void DisplaySplashImage(void);
+#ifdef __cplusplus
+extern "C" {
+#endif //__cplusplus
+
+	void DisplaySplashImage(void);
+
+#ifdef __cplusplus
+}
+#endif //__cplusplus
 
 #endif
--- a/src/pathfind.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/pathfind.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -114,16 +114,16 @@
 	0x2A,
 };
 
-static const byte _tpf_new_direction[14] = {
-	0, 1, 0, 1, 2, 1,
-	0, 0,
-	2, 3, 3, 2, 3, 0,
+static const DiagDirection _tpf_new_direction[14] = {
+	DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_SE,
+	INVALID_DIAGDIR, INVALID_DIAGDIR,
+	DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NE,
 };
 
-static const byte _tpf_prev_direction[14] = {
-	0, 1, 1, 0, 1, 2,
-	0, 0,
-	2, 3, 2, 3, 0, 3,
+static const DiagDirection _tpf_prev_direction[14] = {
+	DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW,
+	INVALID_DIAGDIR, INVALID_DIAGDIR,
+	DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NE, DIAGDIR_NW,
 };
 
 
@@ -182,7 +182,7 @@
 		}
 
 continue_here:;
-		tpf->the_dir = i + (HASBIT(_otherdir_mask[direction], i) ? 8 : 0);
+		tpf->the_dir = (Trackdir)(i + (HASBIT(_otherdir_mask[direction], i) ? 8 : 0));
 
 		if (!tpf->enum_proc(tile, tpf->userdata, tpf->the_dir, tpf->rd.cur_length, NULL)) {
 			TPFMode2(tpf, tile, _tpf_new_direction[tpf->the_dir]);
@@ -334,7 +334,7 @@
 				i = FIND_FIRST_BIT(bits);
 				bits = KILL_FIRST_BIT(bits);
 
-				tpf->the_dir = (_otherdir_mask[direction] & (byte)(1 << i)) ? (i+8) : i;
+				tpf->the_dir = (Trackdir)((_otherdir_mask[direction] & (byte)(1 << i)) ? (i+8) : i);
 				rd = tpf->rd;
 
 				if (TPFSetTileBit(tpf, tile, tpf->the_dir) &&
@@ -377,7 +377,7 @@
 		i = FIND_FIRST_BIT(bits);
 		bits = KILL_FIRST_BIT(bits);
 
-		tpf->the_dir = (_otherdir_mask[direction] & (byte)(1 << i)) ? (i+8) : i;
+		tpf->the_dir = (Trackdir)((_otherdir_mask[direction] & (byte)(1 << i)) ? (i+8) : i);
 		rd = tpf->rd;
 		if (TPFSetTileBit(tpf, tile, tpf->the_dir) &&
 				!tpf->enum_proc(tile, tpf->userdata, tpf->the_dir, tpf->rd.cur_length, &tpf->rd.pft_var6) ) {
@@ -409,11 +409,11 @@
 	tpf.hasbit_13         = HASBIT(flags, 13);  /* 0x2000 */
 
 
-	tpf.tracktype = (byte)flags;
+	tpf.tracktype = (TransportType)(flags & 0xFF);
 
 	if (HASBIT(flags, 11)) {
 		tpf.rd.pft_var6 = 0xFF;
-		tpf.enum_proc(tile, data, 0, 0, 0);
+		tpf.enum_proc(tile, data, INVALID_TRACKDIR, 0, 0);
 		TPFMode2(&tpf, tile, direction);
 	} else {
 		/* clear the hash_heads */
@@ -429,19 +429,19 @@
 	TileIndex tile;
 	uint16 cur_length; // This is the current length to this tile.
 	uint16 priority; // This is the current length + estimated length to the goal.
-	byte track;
+	TrackdirByte track;
 	byte depth;
 	byte state;
 	byte first_track;
 } StackedItem;
 
-static const byte _new_track[6][4] = {
-{0,    0xff, 8,    0xff,},
-{0xff, 1,    0xff, 9,},
-{0xff, 2,    10,   0xff,},
-{3,    0xff, 0xff, 11,},
-{12,   4,    0xff, 0xff,},
-{0xff, 0xff, 5,    13,},
+static const Trackdir _new_trackdir[6][4] = {
+{TRACKDIR_X_NE,    INVALID_TRACKDIR, TRACKDIR_X_SW,    INVALID_TRACKDIR,},
+{INVALID_TRACKDIR, TRACKDIR_Y_SE,    INVALID_TRACKDIR, TRACKDIR_Y_NW,},
+{INVALID_TRACKDIR, TRACKDIR_UPPER_E, TRACKDIR_UPPER_W, INVALID_TRACKDIR,},
+{TRACKDIR_LOWER_E, INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_LOWER_W,},
+{TRACKDIR_LEFT_N,  TRACKDIR_LEFT_S,  INVALID_TRACKDIR, INVALID_TRACKDIR,},
+{INVALID_TRACKDIR, INVALID_TRACKDIR, TRACKDIR_RIGHT_S, TRACKDIR_RIGHT_N,},
 };
 
 typedef struct HashLink {
@@ -541,7 +541,7 @@
 	}
 
 	if (head != 0xffff) {
-		if (tile == tpf->hash_tile[hash] && (head & 0x3) == dir) {
+		if (tile == tpf->hash_tile[hash] && (head & 0x3) == (uint)dir) {
 
 			// longer length
 			if (length >= (head >> 2)) return false;
@@ -576,7 +576,7 @@
 		uint offs = tpf->hash_tile[hash];
 		do {
 			link = NTP_GET_LINK_PTR(tpf, offs);
-			if (tile == link->tile && (link->typelength & 0x3U) == dir) {
+			if (tile == link->tile && (link->typelength & 0x3U) == (uint)dir) {
 				if (length >= (uint)(link->typelength >> 2)) return false;
 				link->typelength = dir | (length << 2);
 				return true;
@@ -659,8 +659,8 @@
 
 static uint DistanceMoo(TileIndex t0, TileIndex t1)
 {
-	const uint dx = abs(TileX(t0) - TileX(t1));
-	const uint dy = abs(TileY(t0) - TileY(t1));
+	const uint dx = delta(TileX(t0), TileX(t1));
+	const uint dy = delta(TileY(t0), TileY(t1));
 
 	const uint straightTracks = 2 * min(dx, dy); /* The number of straight (not full length) tracks */
 	/* OPTIMISATION:
@@ -687,7 +687,7 @@
 static void NTPEnum(NewTrackPathFinder* tpf, TileIndex tile, DiagDirection direction)
 {
 	TrackBits bits, allbits;
-	uint track;
+	Trackdir track;
 	TileIndex tile_org;
 	StackedItem si;
 	int estimation;
@@ -738,7 +738,7 @@
 				TileIndex end_tile;
 				if (GetBridgeTransportType(tile) != tpf->tracktype) {
 					// wrong track type
-					bits = 0;
+					bits = TRACK_BIT_NONE;
 					break;
 				}
 				// pass the bridge wormhole
@@ -750,7 +750,7 @@
 				FindLengthOfTunnelResult flotr;
 				if (GetTunnelTransportType(tile) != tpf->tracktype) {
 					// wrong track type
-					bits = 0;
+					bits = TRACK_BIT_NONE;
 					break;
 				}
 				// pass the tunnel wormhole
@@ -766,14 +766,14 @@
 					// it is allowed only when we are just at the start of pathfinding (si.first_track == 0xFF)
 					if (GetBridgeRampDirection(tile) == ReverseDiagDir(direction) && si.first_track != 0xFF) {
 						// entered bridge ramp from its back
-						bits = 0;
+						bits = TRACK_BIT_NONE;
 						break;
 					}
 				} else if (IsTileType(tile, MP_TUNNEL)) {
 					// disable entering tunnel from regular track in the opposite direction
 					if (GetTunnelDirection(tile) == ReverseDiagDir(direction)) {
 						// entered tunnel from its back
-						bits = 0;
+						bits = TRACK_BIT_NONE;
 						break;
 					}
 				}
@@ -782,7 +782,7 @@
 			// too long search length? bail out.
 			if (si.cur_length >= tpf->maxlength) {
 				DEBUG(ntp, 1, "Cur_length too big");
-				bits = 0;
+				bits = TRACK_BIT_NONE;
 				break;
 			}
 
@@ -791,14 +791,14 @@
 			if (!(IsTileType(tile, MP_RAILWAY) || IsTileType(tile, MP_RAILWAY_BRIDGE)) || !IsPlainRailTile(tile)) {
 				// We found a tile which is not a normal railway tile or bridge ramp (cbh behaves as normal railway).
 				// Determine which tracks that exist on this tile.
-				bits = GetTileTrackStatus(tile, TRANSPORT_RAIL) & _tpfmode1_and[direction];
-				bits = (bits | (bits >> 8)) & 0x3F;
+				uint32 ts = GetTileTrackStatus(tile, TRANSPORT_RAIL) & _tpfmode1_and[direction];
+				bits = TrackdirBitsToTrackBits((TrackdirBits)(ts & TRACKDIR_BIT_MASK));
 
 				// Check that the tile contains exactly one track
 				if (bits == 0 || KILL_FIRST_BIT(bits) != 0) break;
 
 				if (!HASBIT(tpf->railtypes, IsTileType(tile, MP_STREET) ? GetRailTypeCrossing(tile) : GetRailType(tile))) {
-					bits = 0;
+					bits = TRACK_BIT_NONE;
 					break;
 				}
 
@@ -808,7 +808,7 @@
 				//   bits - bitmask of which track that exist on the tile (exactly one bit is set)
 				//   direction - which direction are we moving in?
 				///////////////////
-				si.track = _new_track[FIND_FIRST_BIT(bits)][direction];
+				si.track = _new_trackdir[FIND_FIRST_BIT(bits)][direction];
 				si.cur_length += _length_of_track[si.track];
 				goto callback_and_continue;
 			}
@@ -821,18 +821,18 @@
 			/* The tile has no reachable tracks => End of rail segment
 			 * or Intersection => End of rail segment. We check this agains all the
 			 * bits, not just reachable ones, to prevent infinite loops. */
-			if (bits == 0 || TracksOverlap(allbits)) break;
+			if (bits == TRACK_BIT_NONE || TracksOverlap(allbits)) break;
 
 			if (!HASBIT(tpf->railtypes, GetRailType(tile))) {
-				bits = 0;
+				bits = TRACK_BIT_NONE;
 				break;
 			}
 
 			/* If we reach here, the tile has exactly one track, and this
 			 track is reachable => Rail segment continues */
 
-			track = _new_track[FIND_FIRST_BIT(bits)][direction];
-			assert(track != 0xff);
+			track = _new_trackdir[FIND_FIRST_BIT(bits)][direction];
+			assert(track != INVALID_TRACKDIR);
 
 			si.cur_length += _length_of_track[track] + warp_length;
 
@@ -848,7 +848,7 @@
 				if (!HasSignalOnTrackdir(tile, track)) {
 					// if one way signal not pointing towards us, stop going in this direction => End of rail segment.
 					if (HasSignalOnTrackdir(tile, ReverseTrackdir(track))) {
-						bits = 0;
+						bits = TRACK_BIT_NONE;
 						break;
 					}
 				} else if (GetSignalStateByTrackdir(tile, track) == SIGNAL_STATE_GREEN) {
@@ -861,7 +861,7 @@
 						// stop going in this direction => End of rail segment.
 						// this is to prevent us from going into a full platform.
 						if (!(si.state&1)) {
-							bits = 0;
+							bits = TRACK_BIT_NONE;
 							break;
 						}
 					}
@@ -885,14 +885,14 @@
 
 			// safety check if we're running around chasing our tail... (infinite loop)
 			if (tile == tile_org) {
-				bits = 0;
+				bits = TRACK_BIT_NONE;
 				break;
 			}
 		}
 
 		// There are no tracks to choose between.
 		// Stop searching in this direction
-		if (bits == 0)
+		if (bits == TRACK_BIT_NONE)
 			continue;
 
 		////////////////
@@ -920,8 +920,9 @@
 		if (si.depth == 0)
 			continue; /* We overflowed our depth. No more searching in this direction. */
 		si.tile = tile;
-		do {
-			si.track = _new_track[FIND_FIRST_BIT(bits)][direction];
+		while (bits != TRACK_BIT_NONE) {
+			Track track = RemoveFirstTrack(bits);
+			si.track = _new_trackdir[track][direction];
 			assert(si.track != 0xFF);
 			si.priority = si.cur_length + estimation;
 
@@ -933,7 +934,7 @@
 
 			tpf->stack[tpf->nstack] = si;
 			HeapifyUp(tpf);
-		} while ((bits = KILL_FIRST_BIT(bits)) != 0);
+		};
 
 		// If this is the first intersection, we need to fill the first_track member.
 		// so the code outside knows which path is better.
@@ -942,11 +943,11 @@
 			assert(tpf->nstack == 1 || tpf->nstack == 2 || tpf->nstack == 3);
 			if (tpf->nstack != 1) {
 				uint32 r = Random();
-				if (r&1) swap_byte(&tpf->stack[0].track, &tpf->stack[1].track);
+				if (r&1) SwapT(&tpf->stack[0].track, &tpf->stack[1].track);
 				if (tpf->nstack != 2) {
-					byte t = tpf->stack[2].track;
-					if (r&2) swap_byte(&tpf->stack[0].track, &t);
-					if (r&4) swap_byte(&tpf->stack[1].track, &t);
+					TrackdirByte t = tpf->stack[2].track;
+					if (r&2) SwapT(&tpf->stack[0].track, &t);
+					if (r&4) SwapT(&tpf->stack[1].track, &t);
 					tpf->stack[2].first_track = tpf->stack[2].track = t;
 				}
 				tpf->stack[0].first_track = tpf->stack[0].track;
--- a/src/pathfind.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/pathfind.h	Mon Jan 15 20:14:06 2007 +0000
@@ -4,6 +4,7 @@
 #define PATHFIND_H
 
 #include "direction.h"
+#include "openttd.h"
 
 enum {
 	STR_FACTOR  = 2,
@@ -14,7 +15,7 @@
 //supported on all archs)
 
 typedef struct TrackPathFinder TrackPathFinder;
-typedef bool TPFEnumProc(TileIndex tile, void *data, int track, uint length, byte *state);
+typedef bool TPFEnumProc(TileIndex tile, void *data, Trackdir trackdir, uint length, byte *state);
 typedef void TPFAfterProc(TrackPathFinder *tpf);
 
 typedef bool NTPEnumProc(TileIndex tile, void *data, int track, uint length);
@@ -51,9 +52,9 @@
 
 	RememberData rd;
 
-	int the_dir;
+	TrackdirByte the_dir;
 
-	byte tracktype;
+	TransportTypeByte tracktype;
 	byte var2;
 	bool disable_tile_hash;
 	bool hasbit_13;
--- a/src/player.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/player.h	Mon Jan 15 20:14:06 2007 +0000
@@ -38,7 +38,7 @@
 
 	byte state_mode;
 	byte banned_tile_count;
-	byte railtype_to_use;
+	RailTypeByte railtype_to_use;
 
 	CargoID cargo_type;
 	byte num_wagons;
@@ -132,7 +132,7 @@
 	bool to_deliver;
 
 	TileIndex depot_tile;
-	byte depot_direction;
+	DiagDirectionByte depot_direction;
 
 	byte amount_veh;       // How many vehicles we are going to build in this route
 	byte cur_veh;          // How many vehicles did we bought?
@@ -166,14 +166,14 @@
 	byte player_money_fraction;
 	byte avail_railtypes;
 	byte block_preview;
-	PlayerID index;
+	PlayerByte index;
 
 	uint16 cargo_types; /* which cargo types were transported the last year */
 
 	TileIndex location_of_house;
 	TileIndex last_build_coordinate;
 
-	PlayerID share_owners[4];
+	PlayerByte share_owners[4];
 
 	Year inaugurated_year;
 	byte num_valid_stat_ent;
@@ -212,15 +212,6 @@
 VARDEF PlayerID _local_player;
 VARDEF PlayerID _current_player;
 
-/* Player identifiers All players below MAX_PLAYERS are playable
- * players, above, they are special, computer controlled players */
-enum Players {
-	PLAYER_INACTIVE_CLIENT = 253,
-	PLAYER_NEW_COMPANY = 254, ///< Command 'player' in Multiplayer to create a new company
-	PLAYER_SPECTATOR   = 255, ///< Spectator in Multiplayer or the player in the scenario editor
-	MAX_PLAYERS        = 8,
-};
-
 VARDEF Player _players[MAX_PLAYERS];
 // NOSAVE: can be determined from player structs
 VARDEF byte _player_colors[MAX_PLAYERS];
@@ -239,7 +230,7 @@
 
 static inline Player* GetPlayer(PlayerID i)
 {
-	assert(i < lengthof(_players));
+	assert(i < (PlayerID)lengthof(_players));
 	return &_players[i];
 }
 
--- a/src/player_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/player_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -148,7 +148,7 @@
 {
 	switch (e->event) {
 	case WE_PAINT: {
-		PlayerID player = w->window_number;
+		PlayerID player = (PlayerID)w->window_number;
 		const Player *p = GetPlayer(player);
 
 		if (player == _local_player) {
@@ -170,7 +170,7 @@
 		case 2: {/* toggle size */
 			byte mode = (byte)WP(w,def_d).data_1;
 			bool stickied = !!(w->flags4 & WF_STICKY);
-			PlayerID player = w->window_number;
+			PlayerID player = (PlayerID)w->window_number;
 			DeleteWindow(w);
 			DoShowPlayerFinances(player, !HASBIT(mode, 0), stickied);
 		} break;
@@ -305,11 +305,11 @@
 	}
 
 	/* Get the first selected livery to use as the default dropdown item */
-	for (scheme = 0; scheme < LS_END; scheme++) {
+	for (scheme = LS_BEGIN; scheme < LS_END; scheme++) {
 		if (HASBIT(WP(w, livery_d).sel, scheme)) break;
 	}
 	if (scheme == LS_END) scheme = LS_DEFAULT;
-	livery = &GetPlayer(w->window_number)->livery[scheme];
+	livery = &GetPlayer((PlayerID)w->window_number)->livery[scheme];
 
 	ShowDropDownMenu(w, _colour_dropdown, widget == 10 ? livery->colour1 : livery->colour2, widget, used_colours, 0);
 }
@@ -326,7 +326,7 @@
 			break;
 
 		case WE_PAINT: {
-			const Player *p = GetPlayer(w->window_number);
+			const Player *p = GetPlayer((PlayerID)w->window_number);
 			LiveryScheme scheme = LS_DEFAULT;
 			int y = 51;
 
@@ -337,7 +337,7 @@
 			SetWindowWidgetDisabledState(w, 12, (WP(w, livery_d).sel == 0));
 
 			if (!(WP(w, livery_d).sel == 0)) {
-				for (scheme = 0; scheme < LS_END; scheme++) {
+				for (scheme = LS_BEGIN; scheme < LS_END; scheme++) {
 					if (HASBIT(WP(w, livery_d).sel, scheme)) break;
 				}
 				if (scheme == LS_END) scheme = LS_DEFAULT;
@@ -383,7 +383,7 @@
 					LiveryScheme scheme;
 
 					RaiseWindowWidget(w, WP(w, livery_d).livery_class + 2);
-					WP(w, livery_d).livery_class = e->we.click.widget - 2;
+					WP(w, livery_d).livery_class = (LiveryClass)(e->we.click.widget - 2);
 					WP(w, livery_d).sel = 0;
 					LowerWindowWidget(w, WP(w, livery_d).livery_class + 2);
 
@@ -413,9 +413,9 @@
 
 				case 13: {
 					LiveryScheme scheme;
-					LiveryScheme j = (e->we.click.pt.y - 48) / 14;
+					LiveryScheme j = (LiveryScheme)((e->we.click.pt.y - 48) / 14);
 
-					for (scheme = 0; scheme <= j; scheme++) {
+					for (scheme = LS_BEGIN; scheme <= j; scheme++) {
 						if (livery_class[scheme] != WP(w, livery_d).livery_class) j++;
 						if (scheme >= LS_END) return;
 					}
@@ -423,7 +423,7 @@
 
 					/* If clicking on the left edge, toggle using the livery */
 					if (e->we.click.pt.x < 10) {
-						DoCommandP(0, j | (2 << 8), !GetPlayer(w->window_number)->livery[j].in_use, NULL, CMD_SET_PLAYER_COLOR);
+						DoCommandP(0, j | (2 << 8), !GetPlayer((PlayerID)w->window_number)->livery[j].in_use, NULL, CMD_SET_PLAYER_COLOR);
 					}
 
 					if (_ctrl_pressed) {
@@ -511,7 +511,7 @@
 		Player *p;
 		LowerWindowWidget(w, WP(w, facesel_d).gender + 5);
 		DrawWindowWidgets(w);
-		p = GetPlayer(w->window_number);
+		p = GetPlayer((PlayerID)w->window_number);
 		DrawPlayerFace(WP(w,facesel_d).face, p->player_color, 2, 16);
 	} break;
 
@@ -675,7 +675,7 @@
 {
 	switch (e->event) {
 		case WE_PAINT: {
-			const Player *p = GetPlayer(w->window_number);
+			const Player *p = GetPlayer((PlayerID)w->window_number);
 			bool local = w->window_number == _local_player;
 
 			SetWindowWidgetHiddenState(w, PCW_WIDGET_NEW_FACE,       !local);
@@ -711,14 +711,14 @@
 
 			SetDParam(0, p->name_1);
 			SetDParam(1, p->name_2);
-			SetDParam(2, GetPlayerNameString((byte)w->window_number, 3));
+			SetDParam(2, GetPlayerNameString((PlayerID)w->window_number, 3));
 
 			DrawWindowWidgets(w);
 
 			SetDParam(0, p->inaugurated_year);
 			DrawString(110, 25, STR_7038_INAUGURATED, 0);
 
-			DrawPlayerVehiclesAmount(w->window_number);
+			DrawPlayerVehiclesAmount((PlayerID)w->window_number);
 
 			DrawString(110,48, STR_7006_COLOR_SCHEME, 0);
 			// Draw company-colour bus
@@ -744,7 +744,7 @@
 					Window *wf = AllocateWindowDescFront(&_select_player_face_desc, w->window_number);
 					if (wf != NULL) {
 						wf->caption_color = w->window_number;
-						WP(wf,facesel_d).face = GetPlayer(wf->window_number)->face;
+						WP(wf,facesel_d).face = GetPlayer((PlayerID)wf->window_number)->face;
 						WP(wf,facesel_d).gender = 0;
 					}
 					break;
@@ -762,7 +762,7 @@
 				}
 
 				case PCW_WIDGET_PRESIDENT_NAME: {
-					const Player *p = GetPlayer(w->window_number);
+					const Player *p = GetPlayer((PlayerID)w->window_number);
 					WP(w, def_d).byte_1 = 0;
 					SetDParam(0, p->president_name_2);
 					ShowQueryString(p->president_name_1, STR_700B_PRESIDENT_S_NAME, 31, 94, w, CS_ALPHANUMERAL);
@@ -770,7 +770,7 @@
 				}
 
 				case PCW_WIDGET_COMPANY_NAME: {
-					Player *p = GetPlayer(w->window_number);
+					Player *p = GetPlayer((PlayerID)w->window_number);
 					WP(w,def_d).byte_1 = 1;
 					SetDParam(0, p->name_2);
 					ShowQueryString(p->name_1, STR_700A_COMPANY_NAME, 31, 150, w, CS_ALPHANUMERAL);
@@ -778,7 +778,7 @@
 				}
 
 				case PCW_WIDGET_BUILD_VIEW_HQ: {
-					TileIndex tile = GetPlayer(w->window_number)->location_of_house;
+					TileIndex tile = GetPlayer((PlayerID)w->window_number)->location_of_house;
 					if (tile == 0) {
 						if ((byte)w->window_number != _local_player)
 							return;
@@ -890,7 +890,7 @@
 {
 	switch (e->event) {
 	case WE_PAINT: {
-		Player *p = GetPlayer(w->window_number);
+		Player *p = GetPlayer((PlayerID)w->window_number);
 		SetDParam(0, p->name_1);
 		SetDParam(1, p->name_2);
 		DrawWindowWidgets(w);
--- a/src/players.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/players.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -483,7 +483,7 @@
 	// Find a free slot
 	FOR_ALL_PLAYERS(p) {
 		if (!p->is_active) {
-			int i = p->index;
+			PlayerID i = p->index;
 			memset(p, 0, sizeof(Player));
 			p->index = i;
 			return p;
@@ -494,9 +494,7 @@
 
 void ResetPlayerLivery(Player *p)
 {
-	LiveryScheme scheme;
-
-	for (scheme = 0; scheme < LS_END; scheme++) {
+	for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
 		p->livery[scheme].in_use  = false;
 		p->livery[scheme].colour1 = p->player_color;
 		p->livery[scheme].colour2 = p->player_color;
@@ -583,10 +581,8 @@
 
 void InitializePlayers(void)
 {
-	uint i;
-
 	memset(_players, 0, sizeof(_players));
-	for (i = 0; i != MAX_PLAYERS; i++) _players[i].index = i;
+	for (PlayerID i = PLAYER_FIRST; i != MAX_PLAYERS; i++) _players[i].index = i;
 	_cur_player_tick_index = 0;
 }
 
@@ -596,7 +592,7 @@
 
 	if (_game_mode == GM_EDITOR) return;
 
-	p = GetPlayer(_cur_player_tick_index);
+	p = GetPlayer((PlayerID)_cur_player_tick_index);
 	_cur_player_tick_index = (_cur_player_tick_index + 1) % MAX_PLAYERS;
 	if (p->name_1 != 0) GenerateCompanyName(p);
 
@@ -614,7 +610,7 @@
 	return STR_EMPTY;
 }
 
-extern void ShowPlayerFinances(int player);
+extern void ShowPlayerFinances(PlayerID player);
 
 void PlayersYearlyLoop(void)
 {
@@ -928,11 +924,11 @@
 	case 2: { /* Delete a player */
 		Player *p;
 
-		if (!IsValidPlayer(p2)) return CMD_ERROR;
+		if (!IsValidPlayer((PlayerID)p2)) return CMD_ERROR;
 
 		if (!(flags & DC_EXEC)) return 0;
 
-		p = GetPlayer(p2);
+		p = GetPlayer((PlayerID)p2);
 
 		/* Only allow removal of HUMAN companies */
 		if (IsHumanPlayer(p->index)) {
@@ -953,8 +949,8 @@
 	} break;
 
 	case 3: { /* Merge a company (#1) into another company (#2), elimination company #1 */
-		PlayerID pid_old = GB(p2,  0, 16);
-		PlayerID pid_new = GB(p2, 16, 16);
+		PlayerID pid_old = (PlayerID)GB(p2,  0, 16);
+		PlayerID pid_new = (PlayerID)GB(p2, 16, 16);
 
 		if (!IsValidPlayer(pid_old) || !IsValidPlayer(pid_new)) return CMD_ERROR;
 
@@ -1323,7 +1319,7 @@
 {
 	int index;
 	while ((index = SlIterateArray()) != -1) {
-		Player *p = GetPlayer(index);
+		Player *p = GetPlayer((PlayerID)index);
 		SaveLoad_PLYR(p);
 		_player_colors[index] = p->player_color;
 		UpdatePlayerMoney32(p);
@@ -1334,6 +1330,6 @@
 	}
 }
 
-const ChunkHandler _player_chunk_handlers[] = {
+extern const ChunkHandler _player_chunk_handlers[] = {
 	{ 'PLYR', Save_PLYR, Load_PLYR, CH_ARRAY | CH_LAST},
 };
--- a/src/queue.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/queue.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -3,6 +3,7 @@
 #include "stdafx.h"
 #include "openttd.h"
 #include "queue.h"
+#include "helpers.hpp"
 
 static void Stack_Clear(Queue* q, bool free_values)
 {
@@ -48,14 +49,15 @@
 	q->free = Stack_Free;
 	q->data.stack.max_size = max_size;
 	q->data.stack.size = 0;
-	q->data.stack.elements = malloc(max_size * sizeof(*q->data.stack.elements));
+	MallocT(&q->data.stack.elements, max_size);
 	q->freeq = false;
 	return q;
 }
 
 Queue* new_Stack(uint max_size)
 {
-	Queue* q = malloc(sizeof(*q));
+	Queue* q;
+	MallocT(&q, 1);
 
 	init_stack(q, max_size);
 	q->freeq = true;
@@ -125,14 +127,15 @@
 	q->data.fifo.max_size = max_size;
 	q->data.fifo.head = 0;
 	q->data.fifo.tail = 0;
-	q->data.fifo.elements = malloc(max_size * sizeof(*q->data.fifo.elements));
+	MallocT(&q->data.fifo.elements, max_size);
 	q->freeq = false;
 	return q;
 }
 
 Queue* new_Fifo(uint max_size)
 {
-	Queue* q = malloc(sizeof(*q));
+	Queue* q;
+	MallocT(&q, 1);
 
 	init_fifo(q, max_size);
 	q->freeq = true;
@@ -166,7 +169,8 @@
 
 static bool InsSort_Push(Queue* q, void* item, int priority)
 {
-	InsSortNode* newnode = malloc(sizeof(*newnode));
+	InsSortNode* newnode;
+	MallocT(&newnode, 1);
 
 	if (newnode == NULL) return false;
 	newnode->item = item;
@@ -220,7 +224,8 @@
 
 Queue* new_InsSort(void)
 {
-	Queue* q = malloc(sizeof(*q));
+	Queue* q;
+	MallocT(&q, 1);
 
 	init_InsSort(q);
 	q->freeq = true;
@@ -299,7 +304,7 @@
 	if (q->data.binaryheap.elements[q->data.binaryheap.size >> BINARY_HEAP_BLOCKSIZE_BITS] == NULL) {
 		/* The currently allocated blocks are full, allocate a new one */
 		assert((q->data.binaryheap.size & BINARY_HEAP_BLOCKSIZE_MASK) == 0);
-		q->data.binaryheap.elements[q->data.binaryheap.size >> BINARY_HEAP_BLOCKSIZE_BITS] = malloc(BINARY_HEAP_BLOCKSIZE * sizeof(*q->data.binaryheap.elements[0]));
+		MallocT(&q->data.binaryheap.elements[q->data.binaryheap.size >> BINARY_HEAP_BLOCKSIZE_BITS], BINARY_HEAP_BLOCKSIZE);
 		q->data.binaryheap.blocks++;
 #ifdef QUEUE_DEBUG
 		printf("[BinaryHeap] Increasing size of elements to %d nodes\n", q->data.binaryheap.blocks *  BINARY_HEAP_BLOCKSIZE);
@@ -427,8 +432,8 @@
 	q->data.binaryheap.size = 0;
 	// We malloc memory in block of BINARY_HEAP_BLOCKSIZE
 	//   It autosizes when it runs out of memory
-	q->data.binaryheap.elements = calloc((max_size - 1) / BINARY_HEAP_BLOCKSIZE + 1, sizeof(*q->data.binaryheap.elements));
-	q->data.binaryheap.elements[0] = malloc(BINARY_HEAP_BLOCKSIZE * sizeof(*q->data.binaryheap.elements[0]));
+	CallocT(&q->data.binaryheap.elements, (max_size - 1) / BINARY_HEAP_BLOCKSIZE + 1);
+	MallocT(&q->data.binaryheap.elements[0], BINARY_HEAP_BLOCKSIZE);
 	q->data.binaryheap.blocks = 1;
 	q->freeq = false;
 #ifdef QUEUE_DEBUG
@@ -438,7 +443,8 @@
 
 Queue* new_BinaryHeap(uint max_size)
 {
-	Queue* q = malloc(sizeof(*q));
+	Queue* q;
+	MallocT(&q, 1);
 
 	init_BinaryHeap(q, max_size);
 	q->freeq = true;
@@ -464,7 +470,7 @@
 	h->hash = hash;
 	h->size = 0;
 	h->num_buckets = num_buckets;
-	h->buckets = malloc(num_buckets * (sizeof(*h->buckets) + sizeof(*h->buckets_in_use)));
+	h->buckets = (HashNode*)malloc(num_buckets * (sizeof(*h->buckets) + sizeof(*h->buckets_in_use)));
 #ifdef HASH_DEBUG
 	debug("Buckets = %p", h->buckets);
 #endif
@@ -475,7 +481,8 @@
 
 Hash* new_Hash(Hash_HashProc* hash, int num_buckets)
 {
-	Hash* h = malloc(sizeof(*h));
+	Hash* h;
+	MallocT(&h, 1);
 
 	init_Hash(h, hash, num_buckets);
 	h->freeh = true;
@@ -709,7 +716,7 @@
 		node = h->buckets + hash;
 	} else {
 		/* Add it after prev */
-		node = malloc(sizeof(*node));
+		MallocT(&node, 1);
 		prev->next = node;
 	}
 	node->next = NULL;
--- a/src/rail.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/rail.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -10,41 +10,41 @@
 /* XXX: Below 3 tables store duplicate data. Maybe remove some? */
 /* Maps a trackdir to the bit that stores its status in the map arrays, in the
  * direction along with the trackdir */
-const byte _signal_along_trackdir[] = {
+extern const byte _signal_along_trackdir[] = {
 	0x80, 0x80, 0x80, 0x20, 0x40, 0x10, 0, 0,
 	0x40, 0x40, 0x40, 0x10, 0x80, 0x20
 };
 
 /* Maps a trackdir to the bit that stores its status in the map arrays, in the
  * direction against the trackdir */
-const byte _signal_against_trackdir[] = {
+extern const byte _signal_against_trackdir[] = {
 	0x40, 0x40, 0x40, 0x10, 0x80, 0x20, 0, 0,
 	0x80, 0x80, 0x80, 0x20, 0x40, 0x10
 };
 
 /* Maps a Track to the bits that store the status of the two signals that can
  * be present on the given track */
-const byte _signal_on_track[] = {
+extern const byte _signal_on_track[] = {
 	0xC0, 0xC0, 0xC0, 0x30, 0xC0, 0x30
 };
 
 /* Maps a diagonal direction to the all trackdirs that are connected to any
  * track entering in this direction (including those making 90 degree turns)
  */
-const TrackdirBits _exitdir_reaches_trackdirs[] = {
+extern const TrackdirBits _exitdir_reaches_trackdirs[] = {
 	TRACKDIR_BIT_X_NE | TRACKDIR_BIT_LOWER_E | TRACKDIR_BIT_LEFT_N,  /* DIAGDIR_NE */
 	TRACKDIR_BIT_Y_SE | TRACKDIR_BIT_LEFT_S  | TRACKDIR_BIT_UPPER_E, /* DIAGDIR_SE */
 	TRACKDIR_BIT_X_SW | TRACKDIR_BIT_UPPER_W | TRACKDIR_BIT_RIGHT_S, /* DIAGDIR_SW */
 	TRACKDIR_BIT_Y_NW | TRACKDIR_BIT_RIGHT_N | TRACKDIR_BIT_LOWER_W  /* DIAGDIR_NW */
 };
 
-const Trackdir _next_trackdir[] = {
+extern const Trackdir _next_trackdir[] = {
 	TRACKDIR_X_NE,  TRACKDIR_Y_SE,  TRACKDIR_LOWER_E, TRACKDIR_UPPER_E, TRACKDIR_RIGHT_S, TRACKDIR_LEFT_S, INVALID_TRACKDIR, INVALID_TRACKDIR,
 	TRACKDIR_X_SW,  TRACKDIR_Y_NW,  TRACKDIR_LOWER_W, TRACKDIR_UPPER_W, TRACKDIR_RIGHT_N, TRACKDIR_LEFT_N
 };
 
 /* Maps a trackdir to all trackdirs that make 90 deg turns with it. */
-const TrackdirBits _track_crosses_trackdirs[] = {
+extern const TrackdirBits _track_crosses_trackdirs[] = {
 	TRACKDIR_BIT_Y_SE     | TRACKDIR_BIT_Y_NW,                                                   /* TRACK_X     */
 	TRACKDIR_BIT_X_NE     | TRACKDIR_BIT_X_SW,                                                   /* TRACK_Y     */
 	TRACKDIR_BIT_RIGHT_N  | TRACKDIR_BIT_RIGHT_S  | TRACKDIR_BIT_LEFT_N  | TRACKDIR_BIT_LEFT_S,  /* TRACK_UPPER */
@@ -54,7 +54,7 @@
 };
 
 /* Maps a track to all tracks that make 90 deg turns with it. */
-const TrackBits _track_crosses_tracks[] = {
+extern const TrackBits _track_crosses_tracks[] = {
 	TRACK_BIT_Y,    /* TRACK_X     */
 	TRACK_BIT_X,    /* TRACK_Y     */
 	TRACK_BIT_VERT, /* TRACK_UPPER */
@@ -65,12 +65,12 @@
 
 /* Maps a trackdir to the (4-way) direction the tile is exited when following
  * that trackdir */
-const DiagDirection _trackdir_to_exitdir[] = {
+extern const DiagDirection _trackdir_to_exitdir[] = {
 	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,
 };
 
-const Trackdir _track_exitdir_to_trackdir[][DIAGDIR_END] = {
+extern const Trackdir _track_exitdir_to_trackdir[][DIAGDIR_END] = {
 	{TRACKDIR_X_NE,     INVALID_TRACKDIR,  TRACKDIR_X_SW,     INVALID_TRACKDIR},
 	{INVALID_TRACKDIR,  TRACKDIR_Y_SE,     INVALID_TRACKDIR,  TRACKDIR_Y_NW},
 	{TRACKDIR_UPPER_E,  INVALID_TRACKDIR,  INVALID_TRACKDIR,  TRACKDIR_UPPER_W},
@@ -79,7 +79,7 @@
 	{TRACKDIR_RIGHT_N,  TRACKDIR_RIGHT_S,  INVALID_TRACKDIR,  INVALID_TRACKDIR}
 };
 
-const Trackdir _track_enterdir_to_trackdir[][DIAGDIR_END] = { // TODO: replace magic with enums
+extern const Trackdir _track_enterdir_to_trackdir[][DIAGDIR_END] = { // TODO: replace magic with enums
 	{TRACKDIR_X_NE,     INVALID_TRACKDIR,  TRACKDIR_X_SW,     INVALID_TRACKDIR},
 	{INVALID_TRACKDIR,  TRACKDIR_Y_SE,     INVALID_TRACKDIR,  TRACKDIR_Y_NW},
 	{INVALID_TRACKDIR,  TRACKDIR_UPPER_E,  TRACKDIR_UPPER_W,  INVALID_TRACKDIR},
@@ -88,7 +88,7 @@
 	{INVALID_TRACKDIR,  INVALID_TRACKDIR,  TRACKDIR_RIGHT_S,  TRACKDIR_RIGHT_N}
 };
 
-const Trackdir _track_direction_to_trackdir[][DIR_END] = {
+extern const Trackdir _track_direction_to_trackdir[][DIR_END] = {
 	{INVALID_TRACKDIR, TRACKDIR_X_NE,     INVALID_TRACKDIR, INVALID_TRACKDIR,  INVALID_TRACKDIR, TRACKDIR_X_SW,     INVALID_TRACKDIR, INVALID_TRACKDIR},
 	{INVALID_TRACKDIR, INVALID_TRACKDIR,  INVALID_TRACKDIR, TRACKDIR_Y_SE,     INVALID_TRACKDIR, INVALID_TRACKDIR,  INVALID_TRACKDIR, TRACKDIR_Y_NW},
 	{INVALID_TRACKDIR, INVALID_TRACKDIR,  TRACKDIR_UPPER_E, INVALID_TRACKDIR,  INVALID_TRACKDIR, INVALID_TRACKDIR,  TRACKDIR_UPPER_W, INVALID_TRACKDIR},
@@ -97,12 +97,12 @@
 	{TRACKDIR_RIGHT_N, INVALID_TRACKDIR,  INVALID_TRACKDIR, INVALID_TRACKDIR,  TRACKDIR_RIGHT_S, INVALID_TRACKDIR,  INVALID_TRACKDIR, INVALID_TRACKDIR}
 };
 
-const Trackdir _dir_to_diag_trackdir[] = {
+extern const Trackdir _dir_to_diag_trackdir[] = {
 	TRACKDIR_X_NE, TRACKDIR_Y_SE, TRACKDIR_X_SW, TRACKDIR_Y_NW,
 };
 
 
-RailType GetTileRailType(TileIndex tile, Trackdir trackdir)
+RailType GetTileRailType(TileIndex tile, Track track)
 {
 	switch (GetTileType(tile)) {
 		case MP_RAILWAY:
--- a/src/rail.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/rail.h	Mon Jan 15 20:14:06 2007 +0000
@@ -9,6 +9,7 @@
 #include "tile.h"
 
 typedef enum RailTypes {
+	RAILTYPE_BEGIN    = 0,
 	RAILTYPE_RAIL     = 0,
 	RAILTYPE_ELECTRIC = 1,
 	RAILTYPE_MONO     = 2,
@@ -19,10 +20,17 @@
 
 typedef byte RailTypeMask;
 
+/** Allow incrementing of Track variables */
+DECLARE_POSTFIX_INCREMENT(RailType);
+/** Define basic enum properties */
+template <> struct EnumPropsT<RailType> : MakeEnumPropsT<RailType, byte, RAILTYPE_BEGIN, RAILTYPE_END, INVALID_RAILTYPE> {};
+typedef TinyEnumT<RailType> RailTypeByte;
+
 
 /** These are used to specify a single track.
  * Can be translated to a trackbit with TrackToTrackbit */
 typedef enum Track {
+	TRACK_BEGIN = 0,
 	TRACK_X     = 0,
 	TRACK_Y     = 1,
 	TRACK_UPPER = 2,
@@ -33,6 +41,12 @@
 	INVALID_TRACK = 0xFF
 } Track;
 
+/** Allow incrementing of Track variables */
+DECLARE_POSTFIX_INCREMENT(Track);
+/** Define basic enum properties */
+template <> struct EnumPropsT<Track> : MakeEnumPropsT<Track, byte, TRACK_BEGIN, TRACK_END, INVALID_TRACK> {};
+typedef TinyEnumT<Track> TrackByte;
+
 
 /** Convert an Axis to the corresponding Track
  * AXIS_X -> TRACK_X
@@ -62,9 +76,18 @@
 	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_MASK    = 0x3FU,
+	TRACK_BIT_WORMHOLE = 0x40U,
+	TRACK_BIT_SPECIAL = 0x80U,
+	INVALID_TRACK_BIT = 0xFF
 } TrackBits;
 
+/** Define basic enum properties */
+template <> struct EnumPropsT<TrackBits> : MakeEnumPropsT<TrackBits, byte, TRACK_BIT_NONE, TRACK_BIT_ALL, INVALID_TRACK_BIT> {};
+typedef TinyEnumT<TrackBits> TrackBitsByte;
+
+DECLARE_ENUM_AS_BIT_SET(TrackBits);
+DECLARE_ENUM_AS_BIT_INDEX(Track, TrackBits);
 
 /**
  * Maps a Track to the corresponding TrackBits value
@@ -84,6 +107,7 @@
 /** 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. */
 typedef enum Trackdirs {
+	TRACKDIR_BEGIN    =  0,
 	TRACKDIR_X_NE     =  0,
 	TRACKDIR_Y_SE     =  1,
 	TRACKDIR_UPPER_E  =  2,
@@ -102,6 +126,10 @@
 	INVALID_TRACKDIR  = 0xFF,
 } 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. */
 typedef enum TrackdirBits {
@@ -123,6 +151,12 @@
 	INVALID_TRACKDIR_BIT  = 0xFFFF,
 } TrackdirBits;
 
+/** Define basic enum properties */
+template <> struct EnumPropsT<TrackdirBits> : MakeEnumPropsT<TrackdirBits, uint16, TRACKDIR_BIT_NONE, TRACKDIR_BIT_MASK, INVALID_TRACKDIR_BIT> {};
+typedef TinyEnumT<TrackdirBits> TrackdirBitsShort;
+DECLARE_ENUM_AS_BIT_SET(TrackdirBits);
+DECLARE_ENUM_AS_BIT_INDEX(Trackdir, TrackdirBits);
+
 /** This struct contains all the info that is needed to draw and construct tracks.
  */
 typedef struct RailtypeInfo {
@@ -214,6 +248,58 @@
 static inline TrackdirBits TrackdirToTrackdirBits(Trackdir trackdir) { return (TrackdirBits)(1 << trackdir); }
 
 /**
+* Removes first Track from TrackBits and returns it
+*/
+static inline Track RemoveFirstTrack(TrackBits &tracks)
+{
+	if (tracks != TRACK_BIT_NONE && tracks != INVALID_TRACK_BIT) {
+		Track first = (Track)FIND_FIRST_BIT(tracks);
+		tracks = ClrBitT(tracks, first);
+		return first;
+	}
+	return INVALID_TRACK;
+}
+
+/**
+* Removes first Trackdir from TrackdirBits and returns it
+*/
+static inline Trackdir RemoveFirstTrackdir(TrackdirBits &trackdirs)
+{
+	if (trackdirs != TRACKDIR_BIT_NONE && trackdirs != INVALID_TRACKDIR_BIT) {
+		Trackdir first = (Trackdir)FindFirstBit2x64(trackdirs);
+		trackdirs = ClrBitT(trackdirs, first);
+		return first;
+	}
+	return INVALID_TRACKDIR;
+}
+
+/**
+* Returns first Track from TrackBits or INVALID_TRACK
+*/
+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!
+*/
+static inline Track TrackBitsToTrack(TrackBits tracks)
+{
+	assert (tracks == INVALID_TRACK_BIT || (tracks != TRACK_BIT_NONE && KILL_FIRST_BIT(tracks) == 0));
+	return tracks != INVALID_TRACK_BIT ? (Track)FIND_FIRST_BIT(tracks) : INVALID_TRACK;
+}
+
+/**
+* Returns first Trackdir from TrackdirBits or INVALID_TRACKDIR
+*/
+static inline Trackdir FindFirstTrackdir(TrackdirBits trackdirs)
+{
+	assert((trackdirs & ~TRACKDIR_BIT_MASK) == TRACKDIR_BIT_NONE);
+	return (trackdirs != TRACKDIR_BIT_NONE) ? (Trackdir)FindFirstBit2x64(trackdirs) : INVALID_TRACKDIR;
+}
+
+/**
  * These functions check the validity of Tracks and Trackdirs. assert against
  * them when convenient.
  */
@@ -263,7 +349,9 @@
 /**
  * Maps a trackdir to the reverse trackdir.
  */
-static inline Trackdir ReverseTrackdir(Trackdir trackdir) {
+static inline Trackdir ReverseTrackdir(Trackdir trackdir)
+{
+	assert(trackdir != INVALID_TRACKDIR);
 	return (Trackdir)(trackdir ^ 8);
 }
 
--- a/src/rail_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/rail_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -114,13 +114,13 @@
 	TRACK_BIT_X,
 
 	TRACK_BIT_LEFT,
-	0,
+	TRACK_BIT_NONE,
 	TRACK_BIT_Y,
 	TRACK_BIT_LOWER,
 
 	TRACK_BIT_LOWER,
 	TRACK_BIT_Y,
-	0,
+	TRACK_BIT_NONE,
 	TRACK_BIT_LEFT,
 
 	TRACK_BIT_X,
@@ -130,7 +130,7 @@
 
 // allowed rail for an evenly raised platform
 {
-	0,
+	TRACK_BIT_NONE,
 	TRACK_BIT_LEFT,
 	TRACK_BIT_LOWER,
 	TRACK_BIT_Y | TRACK_BIT_LOWER | TRACK_BIT_LEFT,
@@ -237,7 +237,7 @@
 	int32 cost = 0;
 	int32 ret;
 
-	if (!ValParamRailtype(p1) || !ValParamTrackOrientation(p2)) return CMD_ERROR;
+	if (!ValParamRailtype(p1) || !ValParamTrackOrientation((Track)p2)) return CMD_ERROR;
 	railtype = (RailType)p1;
 	track = (Track)p2;
 
@@ -252,7 +252,7 @@
 			if (!HASBIT(BRIDGE_HORZ_RAMP, tileh)) return CMD_ERROR;
 
 			/* In which case we can assume the tile to be flat */
-			tileh = 0;
+			tileh = SLOPE_FLAT;
 			/* FALL THROUGH */
 		case MP_RAILWAY:
 			if (!CheckTrackCombination(tile, trackbit, flags) ||
@@ -311,7 +311,7 @@
 			/* FALLTHROUGH */
 
 		default:
-			ret = CheckRailSlope(tileh, trackbit, 0, tile);
+			ret = CheckRailSlope(tileh, trackbit, TRACK_BIT_NONE, tile);
 			if (CmdFailed(ret)) return ret;
 			cost += ret;
 
@@ -344,7 +344,7 @@
 	int32 cost = _price.remove_rail;
 	bool crossing = false;
 
-	if (!ValParamTrackOrientation(p2)) return CMD_ERROR;
+	if (!ValParamTrackOrientation((Track)p2)) return CMD_ERROR;
 	trackbit = TrackToTrackBits(track);
 
 	SET_EXPENSES_TYPE(EXPENSES_CONSTRUCTION);
@@ -460,7 +460,7 @@
 	int ey = TileY(end);
 	int dx, dy, trdx, trdy;
 
-	if (!ValParamTrackOrientation(*trackdir)) return CMD_ERROR;
+	if (!ValParamTrackOrientation(TrackdirToTrack(*trackdir))) return CMD_ERROR;
 
 	// calculate delta x,y from start to end tile
 	dx = ex - x;
@@ -483,7 +483,7 @@
 		(trdy >= 0 && dy < 0)
 	) {
 		if (!HASBIT(*trackdir, 3)) { // first direction is invalid, try the other
-			SETBIT(*trackdir, 3); // reverse the direction
+			*trackdir = SetBitT(*trackdir, 3); // reverse the direction
 			trdx = -trdx;
 			trdy = -trdy;
 		} else { // other direction is invalid too, invalid drag
@@ -546,7 +546,7 @@
 		tile += ToTileIndexDiff(_trackdelta[trackdir]);
 
 		// toggle railbit for the non-diagonal tracks
-		if (!IsDiagonalTrackdir(trackdir)) trackdir ^= 1;
+		if (!IsDiagonalTrackdir(trackdir)) trackdir = ToggleBitT(trackdir, 0);
 	}
 
 	return (total_cost == 0) ? CMD_ERROR : total_cost;
@@ -619,14 +619,15 @@
 	if (d == NULL) return CMD_ERROR;
 
 	if (flags & DC_EXEC) {
-		MakeRailDepot(tile, _current_player, p2, p1);
+		DiagDirection dir = (DiagDirection)p2;
+		MakeRailDepot(tile, _current_player, dir, (RailType)p1);
 		MarkTileDirtyByTile(tile);
 
 		d->xy = tile;
 		d->town_index = ClosestTownFromTile(tile, (uint)-1)->index;
 
-		UpdateSignalsOnSegment(tile, p2);
-		YapfNotifyTrackLayoutChange(tile, TrackdirToTrack(DiagdirToDiagTrackdir(p2)));
+		UpdateSignalsOnSegment(tile, dir);
+		YapfNotifyTrackLayoutChange(tile, TrackdirToTrack(DiagdirToDiagTrackdir(dir)));
 	}
 
 	return cost + _price.build_train_depot;
@@ -712,7 +713,7 @@
 					// cycle between normal -> pre -> exit -> combo -> ...
 					SignalType type = GetSignalType(tile);
 
-					SetSignalType(tile, type == SIGTYPE_COMBO ? SIGTYPE_NORMAL : type + 1);
+					SetSignalType(tile, type == SIGTYPE_COMBO ? SIGTYPE_NORMAL : (SignalType)(type + 1));
 				} else {
 					CycleSignalSide(tile, track);
 				}
@@ -750,7 +751,7 @@
 	TileIndex end_tile;
 
 	int mode = p2 & 0x1;
-	Track track = GB(p2, 4, 3);
+	Track track = (Track)GB(p2, 4, 3);
 	Trackdir trackdir = TrackToTrackdir(track);
 	byte semaphores = (HASBIT(p2, 3) ? 8 : 0);
 	byte signal_density = (p2 >> 24);
@@ -809,7 +810,7 @@
 		signal_ctr++;
 
 		// toggle railbit for the non-diagonal tracks (|, -- tracks)
-		if (!IsDiagonalTrackdir(trackdir)) trackdir ^= 1;
+		if (!IsDiagonalTrackdir(trackdir)) trackdir = ToggleBitT(trackdir, 0);
 	}
 
 	return error ? CMD_ERROR : total_cost;
@@ -889,13 +890,14 @@
 
 	// change type.
 	if (exec) {
-		TrackBits tracks;
 		SetRailType(tile, totype);
 		MarkTileDirtyByTile(tile);
 
 		// notify YAPF about the track layout change
-		for (tracks = GetTrackBits(tile); tracks != TRACK_BIT_NONE; tracks = KILL_FIRST_BIT(tracks))
-			YapfNotifyTrackLayoutChange(tile, FIND_FIRST_BIT(tracks));
+		TrackBits tracks = GetTrackBits(tile);
+		while (tracks != TRACK_BIT_NONE) {
+			YapfNotifyTrackLayoutChange(tile, RemoveFirstTrack(tracks));
+		}
 
 		if (IsTileDepotType(tile, TRANSPORT_RAIL)) {
 			Vehicle *v;
@@ -964,7 +966,7 @@
 				default: continue;
 			}
 
-			ret = proc(tile, p2, false);
+			ret = proc(tile, (RailType)p2, false);
 			if (CmdFailed(ret)) continue;
 			cost += ret;
 
@@ -974,7 +976,7 @@
 					_additional_cash_required = ret;
 					return cost - ret;
 				}
-				proc(tile, p2, true);
+				proc(tile, (RailType)p2, true);
 			}
 		}
 	}
@@ -1023,10 +1025,9 @@
 		case RAIL_TILE_SIGNALS:
 		case RAIL_TILE_NORMAL: {
 			TrackBits tracks = GetTrackBits(tile);
-			uint i;
-
-			for_each_bit (i, tracks) {
-				ret = DoCommand(tile, 0, i, flags, CMD_REMOVE_SINGLE_RAIL);
+			while (tracks != TRACK_BIT_NONE) {
+				Track track = RemoveFirstTrack(tracks);
+				ret = DoCommand(tile, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
 				if (CmdFailed(ret)) return CMD_ERROR;
 				cost += ret;
 			}
@@ -1049,7 +1050,7 @@
 
 static void DrawSingleSignal(TileIndex tile, byte condition, uint image, uint pos)
 {
-	bool side = _opt.road_side & _patches.signal_side;
+	bool side = (_opt.road_side != 0) && _patches.signal_side;
 	static const Point SignalPositions[2][12] = {
 		{      /* Signals on the left side */
 		/*  LEFT      LEFT      RIGHT     RIGHT     UPPER     UPPER */
@@ -1225,7 +1226,7 @@
 	(image++, true);
 
 	if (ti->tileh != SLOPE_FLAT) {
-		uint foundation = IsTileType(ti->tile, MP_RAILWAY_BRIDGE) ? ti->tileh : GetRailFoundation(ti->tileh, track);
+		uint foundation = IsTileType(ti->tile, MP_RAILWAY_BRIDGE) ? ti->tileh : (Slope)GetRailFoundation(ti->tileh, track);
 
 		if (foundation != 0) DrawFoundation(ti, foundation);
 
@@ -1441,28 +1442,28 @@
 	int presignal_exits_free;
 
 	// these are used to keep track of the signals that change.
-	byte bit[NUM_SSD_ENTRY];
+	TrackdirByte bit[NUM_SSD_ENTRY];
 	TileIndex tile[NUM_SSD_ENTRY];
 
 	// these are used to keep track of the stack that modifies presignals recursively
 	TileIndex next_tile[NUM_SSD_STACK];
-	byte next_dir[NUM_SSD_STACK];
+	DiagDirectionByte next_dir[NUM_SSD_STACK];
 
 } SetSignalsData;
 
-static bool SetSignalsEnumProc(TileIndex tile, void* data, int track, uint length, byte* state)
+static bool SetSignalsEnumProc(TileIndex tile, void* data, Trackdir trackdir, uint length, byte* state)
 {
-	SetSignalsData* ssd = data;
+	SetSignalsData* ssd = (SetSignalsData*)data;
 
 	if (!(IsTileType(tile, MP_RAILWAY) || IsTileType(tile, MP_RAILWAY_BRIDGE))) return false;
 
 	// the tile has signals?
-	if (HasSignalOnTrack(tile, TrackdirToTrack(track))) {
-		if (HasSignalOnTrackdir(tile, ReverseTrackdir(track))) {
+	if (HasSignalOnTrack(tile, TrackdirToTrack(trackdir))) {
+		if (HasSignalOnTrackdir(tile, ReverseTrackdir(trackdir))) {
 			// yes, add the signal to the list of signals
 			if (ssd->cur != NUM_SSD_ENTRY) {
 				ssd->tile[ssd->cur] = tile; // remember the tile index
-				ssd->bit[ssd->cur] = track; // and the controlling bit number
+				ssd->bit[ssd->cur] = trackdir; // and the controlling bit number
 				ssd->cur++;
 			}
 
@@ -1470,10 +1471,10 @@
 			ssd->has_presignal |= IsPresignalEntry(tile);
 		}
 
-		if (HasSignalOnTrackdir(tile, track) && IsPresignalExit(tile)) {
+		if (HasSignalOnTrackdir(tile, trackdir) && IsPresignalExit(tile)) {
 			// this is an exit signal that points out from the segment
 			ssd->presignal_exits++;
-			if (GetSignalStateByTrackdir(tile, track) != SIGNAL_STATE_RED)
+			if (GetSignalStateByTrackdir(tile, trackdir) != SIGNAL_STATE_RED)
 				ssd->presignal_exits_free++;
 		}
 
@@ -1493,7 +1494,7 @@
 
 static void *SignalVehicleCheckProc(Vehicle *v, void *data)
 {
-	const SignalVehicleCheckStruct* dest = data;
+	const SignalVehicleCheckStruct* dest = (SignalVehicleCheckStruct*)data;
 
 	if (v->type != VEH_Train) return NULL;
 
@@ -1552,7 +1553,7 @@
 
 static void SetSignalsAfterProc(TrackPathFinder *tpf)
 {
-	SetSignalsData *ssd = tpf->userdata;
+	SetSignalsData *ssd = (SetSignalsData*)tpf->userdata;
 	const TrackPathFinderLink* link;
 	uint offs;
 	uint i;
@@ -1588,9 +1589,9 @@
 	}
 }
 
-static const byte _dir_from_track[14] = {
-	0,1,0,1,2,1, 0,0,
-	2,3,3,2,3,0,
+static const DiagDirection _dir_from_track[14] = {
+	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,
 };
 
 
@@ -1947,7 +1948,7 @@
 
 static const byte _fractcoords_behind[4] = { 0x8F, 0x8, 0x80, 0xF8 };
 static const byte _fractcoords_enter[4] = { 0x8A, 0x48, 0x84, 0xA8 };
-static const byte _deltacoord_leaveoffset[8] = {
+static const signed char _deltacoord_leaveoffset[8] = {
 	-1,  0,  1,  0, /* x */
 	 0,  1,  0, -1  /* y */
 };
@@ -1983,7 +1984,7 @@
 	} else if (_fractcoords_enter[dir] == fract_coord) {
 		if (DiagDirToDir(ReverseDiagDir(dir)) == v->direction) {
 			/* enter the depot */
-			v->u.rail.track = 0x80,
+			v->u.rail.track = TRACK_BIT_SPECIAL,
 			v->vehstatus |= VS_HIDDEN; /* hide it */
 			v->direction = ReverseDir(v->direction);
 			if (v->next == NULL) VehicleEnterDepot(v);
@@ -1997,7 +1998,7 @@
 			/* leave the depot? */
 			if ((v = v->next) != NULL) {
 				v->vehstatus &= ~VS_HIDDEN;
-				v->u.rail.track = (DiagDirToAxis(dir) == AXIS_X ? 1 : 2);
+				v->u.rail.track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
 			}
 		}
 	}
@@ -2006,7 +2007,7 @@
 }
 
 
-const TileTypeProcs _tile_type_rail_procs = {
+extern const TileTypeProcs _tile_type_rail_procs = {
 	DrawTile_Track,           /* draw_tile_proc */
 	GetSlopeZ_Track,          /* get_slope_z_proc */
 	ClearTile_Track,          /* clear_tile_proc */
--- a/src/rail_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/rail_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -37,7 +37,7 @@
 	bool dragdrop;
 
 	bool newstations;
-	byte station_class;
+	StationClassIDByte station_class;
 	byte station_type;
 	byte station_count;
 } _railstation;
@@ -107,7 +107,7 @@
 void CcRailDepot(bool success, TileIndex tile, uint32 p1, uint32 p2)
 {
 	if (success) {
-		DiagDirection dir = p2;
+		DiagDirection dir = (DiagDirection)p2;
 
 		SndPlayTileFx(SND_20_SPLAT_2, tile);
 		ResetObjectToPlace();
@@ -834,7 +834,7 @@
 
 		case 20:
 		case 21:
-			_station_show_coverage = e->we.click.widget - 20;
+			_station_show_coverage = (e->we.click.widget != 20);
 			SetWindowWidgetLoweredState(w, 20, !_station_show_coverage);
 			SetWindowWidgetLoweredState(w, 21, _station_show_coverage);
 			SndPlayFx(SND_15_BEEP);
@@ -873,7 +873,7 @@
 
 	case WE_DROPDOWN_SELECT:
 		if (_railstation.station_class != e->we.dropdown.index) {
-			_railstation.station_class = e->we.dropdown.index;
+			_railstation.station_class = (StationClassID)e->we.dropdown.index;
 			_railstation.station_type  = 0;
 			_railstation.station_count = GetNumCustomStations(_railstation.station_class);
 
@@ -1023,7 +1023,7 @@
 			case 5:
 			case 6:
 				RaiseWindowWidget(w, _build_depot_direction + 3);
-				_build_depot_direction = e->we.click.widget - 3;
+				_build_depot_direction = (DiagDirection)(e->we.click.widget - 3);
 				LowerWindowWidget(w, _build_depot_direction + 3);
 				SndPlayFx(SND_15_BEEP);
 				SetWindowDirty(w);
--- a/src/rail_map.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/rail_map.h	Mon Jan 15 20:14:06 2007 +0000
@@ -266,7 +266,7 @@
  * The given trackdir is used when there are (could be) multiple rail types on
  * one tile.
  */
-RailType GetTileRailType(TileIndex tile, Trackdir trackdir);
+RailType GetTileRailType(TileIndex tile, Track track);
 
 
 typedef enum RailGroundType {
--- a/src/road.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/road.h	Mon Jan 15 20:14:06 2007 +0000
@@ -3,7 +3,10 @@
 #ifndef ROAD_H
 #define ROAD_H
 
+#include "helpers.hpp"
+
 typedef enum RoadBits {
+	ROAD_NONE = 0U,
 	ROAD_NW  = 1U,
 	ROAD_SW  = 2U,
 	ROAD_SE  = 4U,
@@ -13,6 +16,8 @@
 	ROAD_ALL = ROAD_X  | ROAD_Y
 } RoadBits;
 
+DECLARE_ENUM_AS_BIT_SET(RoadBits);
+
 static inline RoadBits ComplementRoadBits(RoadBits r)
 {
 	return (RoadBits)(ROAD_ALL ^ r);
--- a/src/road_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/road_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -56,7 +56,7 @@
 	if (_cheats.magic_bulldozer.value) return true;
 
 	// Get a bitmask of which neighbouring roads has a tile
-	n = 0;
+	n = ROAD_NONE;
 	present = GetAnyRoadBits(tile);
 	if (present & ROAD_NE && GetAnyRoadBits(TILE_ADDXY(tile,-1, 0)) & ROAD_SW) n |= ROAD_NE;
 	if (present & ROAD_SE && GetAnyRoadBits(TILE_ADDXY(tile, 0, 1)) & ROAD_NW) n |= ROAD_SE;
@@ -103,7 +103,7 @@
 
 	/* Road pieces are max 4 bitset values (NE, NW, SE, SW) */
 	if (p1 >> 4) return CMD_ERROR;
-	pieces = p1;
+	pieces = (RoadBits)p1;
 
 	if (!IsTileType(tile, MP_STREET)) return CMD_ERROR;
 
@@ -132,8 +132,8 @@
 
 			if (GetTileSlope(tile, NULL) != SLOPE_FLAT  &&
 					(present == ROAD_Y || present == ROAD_X)) {
-				c |= (c & 0xC) >> 2;
-				c |= (c & 0x3) << 2;
+				c |= (RoadBits)((c & 0xC) >> 2);
+				c |= (RoadBits)((c & 0x3) << 2);
 			}
 
 			// limit the bits to delete to the existing bits.
@@ -164,7 +164,7 @@
 
 				MakeRailNormal(tile, GetTileOwner(tile), GetCrossingRailBits(tile), GetRailTypeCrossing(tile));
 				MarkTileDirtyByTile(tile);
-				YapfNotifyTrackLayoutChange(tile, FIND_FIRST_BIT(GetTrackBits(tile)));
+				YapfNotifyTrackLayoutChange(tile, FindFirstTrack(GetTrackBits(tile)));
 			}
 			return _price.remove_road * 2;
 		}
@@ -179,15 +179,15 @@
 static const RoadBits _valid_tileh_slopes_road[][15] = {
 	// set of normal ones
 	{
-		ROAD_ALL, 0, 0,
-		ROAD_X,   0, 0,  // 3, 4, 5
-		ROAD_Y,   0, 0,
-		ROAD_Y,   0, 0,  // 9, 10, 11
-		ROAD_X,   0, 0
+		ROAD_ALL, ROAD_NONE, ROAD_NONE,
+		ROAD_X,   ROAD_NONE, ROAD_NONE,  // 3, 4, 5
+		ROAD_Y,   ROAD_NONE, ROAD_NONE,
+		ROAD_Y,   ROAD_NONE, ROAD_NONE,  // 9, 10, 11
+		ROAD_X,   ROAD_NONE, ROAD_NONE
 	},
 	// allowed road for an evenly raised platform
 	{
-		0,
+		ROAD_NONE,
 		ROAD_SW | ROAD_NW,
 		ROAD_SW | ROAD_SE,
 		ROAD_Y  | ROAD_SW,
@@ -216,8 +216,8 @@
 	if (IsSteepSlope(tileh)) {
 		if (existing == 0) {
 			// force full pieces.
-			*pieces |= (*pieces & 0xC) >> 2;
-			*pieces |= (*pieces & 0x3) << 2;
+			*pieces |= (RoadBits)((*pieces & 0xC) >> 2);
+			*pieces |= (RoadBits)((*pieces & 0x3) << 2);
 			if (*pieces == ROAD_X || *pieces == ROAD_Y) return _price.terraform;
 		}
 		return CMD_ERROR;
@@ -239,8 +239,8 @@
 	// 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)) {
 		// force full pieces.
-		*pieces |= (*pieces & 0xC) >> 2;
-		*pieces |= (*pieces & 0x3) << 2;
+		*pieces |= (RoadBits)((*pieces & 0xC) >> 2);
+		*pieces |= (RoadBits)((*pieces & 0x3) << 2);
 		if (*pieces == ROAD_X || *pieces == ROAD_Y) return _price.terraform;
 	}
 	return CMD_ERROR;
@@ -255,7 +255,7 @@
 {
 	int32 cost = 0;
 	int32 ret;
-	RoadBits existing = 0;
+	RoadBits existing = ROAD_NONE;
 	RoadBits pieces;
 	Slope tileh;
 
@@ -264,7 +264,7 @@
 	/* Road pieces are max 4 bitset values (NE, NW, SE, SW) and town can only be non-zero
 	 * if a non-player is building the road */
 	if ((p1 >> 4) || (IsValidPlayer(_current_player) && p2 != 0) || !IsValidTownID(p2)) return CMD_ERROR;
-	pieces = p1;
+	pieces = (RoadBits)p1;
 
 	tileh = GetTileSlope(tile, NULL);
 
@@ -325,7 +325,7 @@
 			if (!EnsureNoVehicle(tile)) return CMD_ERROR;
 
 			if (flags & DC_EXEC) {
-				YapfNotifyTrackLayoutChange(tile, FIND_FIRST_BIT(GetTrackBits(tile)));
+				YapfNotifyTrackLayoutChange(tile, FindFirstTrack(GetTrackBits(tile)));
 				MakeRoadCrossing(tile, _current_player, GetTileOwner(tile), roaddir, GetRailType(tile), p2);
 				MarkTileDirtyByTile(tile);
 			}
@@ -382,7 +382,7 @@
 	if (exec) {
 		SetRailTypeCrossing(tile, totype);
 		MarkTileDirtyByTile(tile);
-		YapfNotifyTrackLayoutChange(tile, FIND_FIRST_BIT(GetCrossingRailBits(tile)));
+		YapfNotifyTrackLayoutChange(tile, FindFirstTrack(GetCrossingRailBits(tile)));
 	}
 
 	return _price.build_rail >> 1;
@@ -540,7 +540,7 @@
 		dep->xy = tile;
 		dep->town_index = ClosestTownFromTile(tile, (uint)-1)->index;
 
-		MakeRoadDepot(tile, _current_player, p1);
+		MakeRoadDepot(tile, _current_player, (DiagDirection)p1);
 		MarkTileDirtyByTile(tile);
 	}
 	return cost + _price.build_road_depot;
@@ -1048,7 +1048,7 @@
 }
 
 
-const TileTypeProcs _tile_type_road_procs = {
+extern const TileTypeProcs _tile_type_road_procs = {
 	DrawTile_Road,           /* draw_tile_proc */
 	GetSlopeZ_Road,          /* get_slope_z_proc */
 	ClearTile_Road,          /* clear_tile_proc */
--- a/src/road_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/road_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -28,8 +28,8 @@
 
 static byte _place_road_flag;
 
-static byte _road_depot_orientation;
-static byte _road_station_picker_orientation;
+static DiagDirection _road_depot_orientation;
+static DiagDirection _road_station_picker_orientation;
 
 void CcPlaySound1D(bool success, TileIndex tile, uint32 p1, uint32 p2)
 {
@@ -83,7 +83,7 @@
 	if (success) {
 		SndPlayTileFx(SND_1F_SPLAT, tile);
 		ResetObjectToPlace();
-		BuildRoadOutsideStation(tile, p1);
+		BuildRoadOutsideStation(tile, (DiagDirection)p1);
 	}
 }
 
@@ -388,7 +388,7 @@
 		switch (e->we.click.widget) {
 		case 3: case 4: case 5: case 6:
 			RaiseWindowWidget(w, _road_depot_orientation + 3);
-			_road_depot_orientation = e->we.click.widget - 3;
+			_road_depot_orientation = (DiagDirection)(e->we.click.widget - 3);
 			LowerWindowWidget(w, _road_depot_orientation + 3);
 			SndPlayFx(SND_15_BEEP);
 			SetWindowDirty(w);
@@ -454,10 +454,10 @@
 
 		image = (w->window_class == WC_BUS_STATION) ? 0x47 : 0x43;
 
-		StationPickerDrawSprite(103, 35, 0, image);
-		StationPickerDrawSprite(103, 85, 0, image+1);
-		StationPickerDrawSprite(35, 85, 0, image+2);
-		StationPickerDrawSprite(35, 35, 0, image+3);
+		StationPickerDrawSprite(103, 35, RAILTYPE_BEGIN, image);
+		StationPickerDrawSprite(103, 85, RAILTYPE_BEGIN, image+1);
+		StationPickerDrawSprite(35, 85, RAILTYPE_BEGIN, image+2);
+		StationPickerDrawSprite(35, 35, RAILTYPE_BEGIN, image+3);
 
 		DrawStationCoverageAreaText(2, 146,
 			((w->window_class == WC_BUS_STATION) ? (1<<CT_PASSENGERS) : ~(1<<CT_PASSENGERS)),
@@ -469,14 +469,14 @@
 		switch (e->we.click.widget) {
 		case 3: case 4: case 5: case 6:
 			RaiseWindowWidget(w, _road_station_picker_orientation + 3);
-			_road_station_picker_orientation = e->we.click.widget - 3;
+			_road_station_picker_orientation = (DiagDirection)(e->we.click.widget - 3);
 			LowerWindowWidget(w, _road_station_picker_orientation + 3);
 			SndPlayFx(SND_15_BEEP);
 			SetWindowDirty(w);
 			break;
 		case 7: case 8:
 			RaiseWindowWidget(w, _station_show_coverage + 7);
-			_station_show_coverage = e->we.click.widget - 7;
+			_station_show_coverage = (e->we.click.widget != 7);
 			LowerWindowWidget(w, _station_show_coverage + 7);
 			SndPlayFx(SND_15_BEEP);
 			SetWindowDirty(w);
@@ -555,6 +555,6 @@
 
 void InitializeRoadGui(void)
 {
-	_road_depot_orientation = 3;
-	_road_station_picker_orientation = 3;
+	_road_depot_orientation = DIAGDIR_NW;
+	_road_station_picker_orientation = DIAGDIR_NW;
 }
--- a/src/road_map.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/road_map.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -23,17 +23,17 @@
 			}
 
 		case MP_STATION:
-			if (!IsRoadStopTile(tile)) return 0;
+			if (!IsRoadStopTile(tile)) return ROAD_NONE;
 			return DiagDirToRoadBits(GetRoadStopDir(tile));
 
 		case MP_TUNNEL:
-			if (GetTunnelTransportType(tile) != TRANSPORT_ROAD) return 0;
+			if (GetTunnelTransportType(tile) != TRANSPORT_ROAD) return ROAD_NONE;
 			return DiagDirToRoadBits(ReverseDiagDir(GetTunnelDirection(tile)));
 
 		case MP_STREET_BRIDGE:
 			return DiagDirToRoadBits(ReverseDiagDir(GetBridgeRampDirection(tile)));
 
-		default: return 0;
+		default: return ROAD_NONE;
 	}
 }
 
@@ -44,9 +44,9 @@
 
 	// 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)) {
-		return 0;
+		return TRACK_BIT_NONE;
 	}
 
 	r = GetTileTrackStatus(tile, TRANSPORT_ROAD);
-	return (byte)(r | (r >> 8));
+	return (TrackBits)(byte)(r | (r >> 8));
 }
--- a/src/roadveh_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/roadveh_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -1,7 +1,6 @@
 /* $Id$ */
 
 #include "stdafx.h"
-#include <limits.h>
 #include "openttd.h"
 #include "debug.h"
 #include "functions.h"
@@ -144,7 +143,7 @@
 		const RoadVehicleInfo *rvi = RoadVehInfo(p1);
 
 		v->unitnumber = unit_num;
-		v->direction = 0;
+		v->direction = INVALID_DIR;
 		v->owner = _current_player;
 
 		v->tile = tile;
@@ -296,19 +295,19 @@
 typedef struct RoadFindDepotData {
 	uint best_length;
 	TileIndex tile;
-	byte owner;
+	OwnerByte owner;
 } RoadFindDepotData;
 
 static const DiagDirection _road_pf_directions[] = {
-	DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_SE, 255, 255,
-	DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NE, 255, 255
+	DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_SE, INVALID_DIAGDIR, INVALID_DIAGDIR,
+	DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NE, INVALID_DIAGDIR, INVALID_DIAGDIR
 };
 
-static bool EnumRoadSignalFindDepot(TileIndex tile, void* data, int track, uint length, byte* state)
+static bool EnumRoadSignalFindDepot(TileIndex tile, void* data, Trackdir trackdir, uint length, byte* state)
 {
-	RoadFindDepotData* rfdd = data;
+	RoadFindDepotData* rfdd = (RoadFindDepotData*)data;
 
-	tile += TileOffsByDiagDir(_road_pf_directions[track]);
+	tile += TileOffsByDiagDir(_road_pf_directions[trackdir]);
 
 	if (IsTileType(tile, MP_STREET) &&
 			GetRoadTileType(tile) == ROAD_TILE_DEPOT &&
@@ -341,13 +340,12 @@
 		/* We do not search in two directions here, why should we? We can't reverse right now can we? */
 	} else {
 		RoadFindDepotData rfdd;
-		DiagDirection i;
 
 		rfdd.owner = v->owner;
 		rfdd.best_length = (uint)-1;
 
 		/* search in all directions */
-		for (i = 0; i != 4; i++) {
+		for (DiagDirection i = DIAGDIR_BEGIN; i != DIAGDIR_END; i++) {
 			FollowTrack(tile, 0x2000 | TRANSPORT_ROAD, i, EnumRoadSignalFindDepot, NULL, &rfdd);
 		}
 
@@ -564,7 +562,7 @@
 
 static void* EnumCheckRoadVehCrashTrain(Vehicle* v, void* data)
 {
-	const Vehicle* u = data;
+	const Vehicle* u = (Vehicle*)data;
 
 	return
 		v->type == VEH_Train &&
@@ -789,7 +787,7 @@
 	static const int8 dist_x[] = { -4, -8, -4, -1, 4, 8, 4, 1 };
 	static const int8 dist_y[] = { -4, -1, 4, 8, 4, 1, -4, -8 };
 
-	const RoadVehFindData* rvf = data;
+	const RoadVehFindData* rvf = (RoadVehFindData*)data;
 
 	short x_diff = v->x_pos - rvf->x;
 	short y_diff = v->y_pos - rvf->y;
@@ -818,7 +816,7 @@
 	rvf.y = y;
 	rvf.dir = dir;
 	rvf.veh = v;
-	u = VehicleFromPos(TileVirtXY(x, y), &rvf, EnumCheckRoadVehClose);
+	u = (Vehicle*)VehicleFromPos(TileVirtXY(x, y), &rvf, EnumCheckRoadVehClose);
 
 	// This code protects a roadvehicle from being blocked for ever
 	//  If more than 1480 / 74 days a road vehicle is blocked, it will
@@ -900,8 +898,8 @@
 static Direction RoadVehGetNewDirection(const Vehicle* v, int x, int y)
 {
 	static const Direction _roadveh_new_dir[] = {
-		DIR_N , DIR_NW, DIR_W , 0,
-		DIR_NE, DIR_N , DIR_SW, 0,
+		DIR_N , DIR_NW, DIR_W , INVALID_DIR,
+		DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
 		DIR_E , DIR_SE, DIR_S
 	};
 
@@ -914,13 +912,13 @@
 
 static Direction RoadVehGetSlidingDirection(const Vehicle* v, int x, int y)
 {
-	Direction new = RoadVehGetNewDirection(v, x, y);
-	Direction old = v->direction;
+	Direction new_dir = RoadVehGetNewDirection(v, x, y);
+	Direction old_dir = v->direction;
 	DirDiff delta;
 
-	if (new == old) return old;
-	delta = (DirDifference(new, old) > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
-	return ChangeDir(old, delta);
+	if (new_dir == old_dir) return old_dir;
+	delta = (DirDifference(new_dir, old_dir) > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
+	return ChangeDir(old_dir, delta);
 }
 
 typedef struct OvertakeData {
@@ -932,7 +930,7 @@
 
 static void* EnumFindVehToOvertake(Vehicle* v, void* data)
 {
-	const OvertakeData* od = data;
+	const OvertakeData* od = (OvertakeData*)data;
 
 	return
 		v->tile == od->tile && v->type == VEH_Road && v != od->u && v != od->v ?
@@ -1025,9 +1023,9 @@
 	uint mindist;
 } FindRoadToChooseData;
 
-static bool EnumRoadTrackFindDist(TileIndex tile, void* data, int track, uint length, byte* state)
+static bool EnumRoadTrackFindDist(TileIndex tile, void* data, Trackdir trackdir, uint length, byte* state)
 {
-	FindRoadToChooseData* frd = data;
+	FindRoadToChooseData* frd = (FindRoadToChooseData*)data;
 	uint dist = DistanceManhattan(tile, frd->dest);
 
 	if (dist <= frd->mindist) {
@@ -1133,7 +1131,7 @@
 	} else if (_patches.new_pathfinding_all) {
 		NPFFindStationOrTileData fstd;
 		NPFFoundTargetData ftd;
-		byte trackdir;
+		Trackdir trackdir;
 
 		NPFFillWithOrderData(&fstd, v);
 		trackdir = DiagdirToDiagTrackdir(enterdir);
@@ -1215,7 +1213,7 @@
 	} else {
 		// use NPF
 		NPFFindStationOrTileData fstd;
-		byte trackdir = GetVehicleTrackdir(v);
+		Trackdir trackdir = GetVehicleTrackdir(v);
 		assert(trackdir != 0xFF);
 
 		fstd.dest_coords = tile;
@@ -1363,7 +1361,7 @@
 // switch to another tile
 	if (rd.x & 0x80) {
 		TileIndex tile = v->tile + TileOffsByDiagDir(rd.x & 3);
-		int dir = RoadFindPathToDest(v, tile, rd.x & 3);
+		int dir = RoadFindPathToDest(v, tile, (DiagDirection)(rd.x & 3));
 		uint32 r;
 		Direction newdir;
 		const RoadDriveEntry *rdp;
@@ -1428,7 +1426,7 @@
 	}
 
 	if (rd.x & 0x40) {
-		int dir = RoadFindPathToDest(v, v->tile, rd.x & 3);
+		int dir = RoadFindPathToDest(v, v->tile, (DiagDirection)(rd.x & 3));
 		uint32 r;
 		int tmp;
 		Direction newdir;
--- a/src/saveload.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/saveload.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -30,7 +30,7 @@
 #include "variables.h"
 #include <setjmp.h>
 
-const uint16 SAVEGAME_VERSION = 43;
+extern const uint16 SAVEGAME_VERSION = 43;
 uint16 _sl_version;       /// the major savegame version identifier
 byte   _sl_minor_version; /// the minor savegame version, DO NOT USE!
 
@@ -511,7 +511,7 @@
 		case SLE_VAR_STR:
 		case SLE_VAR_STRQ:
 			str = *(const char**)ptr;
-			len = -1;
+			len = SIZE_MAX;
 			break;
 		case SLE_VAR_STRB:
 		case SLE_VAR_STRBQ:
@@ -538,12 +538,12 @@
 			default: NOT_REACHED();
 			case SLE_VAR_STRB:
 			case SLE_VAR_STRBQ:
-				len = SlCalcNetStringLen(ptr, length);
+				len = SlCalcNetStringLen((char*)ptr, length);
 				break;
 			case SLE_VAR_STR:
 			case SLE_VAR_STRQ:
 				ptr = *(char**)ptr;
-				len = SlCalcNetStringLen(ptr, -1);
+				len = SlCalcNetStringLen((char*)ptr, SIZE_MAX);
 				break;
 		}
 
@@ -568,7 +568,7 @@
 			case SLE_VAR_STR:
 			case SLE_VAR_STRQ: /* Malloc'd string, free previous incarnation, and allocate */
 				free(*(char**)ptr);
-				*(char**)ptr = malloc(len + 1); // terminating '\0'
+				*(char**)ptr = (char*)malloc(len + 1); // terminating '\0'
 				ptr = *(char**)ptr;
 				SlCopyBytes(ptr, len);
 				break;
@@ -714,9 +714,9 @@
 		case SL_REF: /* Reference variable, translate */
 			/// @todo XXX - another artificial limitof 65K elements of pointers?
 			if (_sl.save) { // XXX - read/write pointer as uint16? What is with higher indeces?
-				SlWriteUint16(ReferenceToInt(*(void**)ptr, conv));
+				SlWriteUint16(ReferenceToInt(*(void**)ptr, (SLRefType)conv));
 			} else {
-				*(void**)ptr = IntToReference(SlReadUint16(), conv);
+				*(void**)ptr = IntToReference(SlReadUint16(), (SLRefType)conv);
 			}
 			break;
 		case SL_ARR: SlArray(ptr, sld->length, conv); break;
@@ -1397,7 +1397,7 @@
  * saving takes Aaaaages */
 void SaveFileStart(void)
 {
-	_ts.ff_state = _fast_forward;
+	_ts.ff_state = (_fast_forward != 0);
 	_fast_forward = false;
 	if (_cursor.sprite == SPR_CURSOR_MOUSE) SetMouseCursor(SPR_CURSOR_ZZZ);
 
@@ -1525,7 +1525,7 @@
 
 	_sl.bufe = _sl.bufp = NULL;
 	_sl.offs_base = 0;
-	_sl.save = mode;
+	_sl.save = (mode != 0);
 	_sl.includes = _desc_includes;
 	_sl.chs = _chunk_handlers;
 
--- a/src/saveload.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/saveload.h	Mon Jan 15 20:14:06 2007 +0000
@@ -3,6 +3,12 @@
 #ifndef SAVELOAD_H
 #define SAVELOAD_H
 
+#ifdef SIZE_MAX
+#undef SIZE_MAX
+#endif
+
+#define SIZE_MAX ((size_t)-1)
+
 typedef enum SaveOrLoadResult {
 	SL_OK     = 0, // completed successfully
 	SL_ERROR  = 1, // error that was caught before internal structures were modified
--- a/src/screenshot.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/screenshot.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -13,6 +13,7 @@
 #include "screenshot.h"
 #include "variables.h"
 #include "date.h"
+#include "helpers.hpp"
 
 char _screenshot_format_name[8];
 uint _num_screenshot_formats;
@@ -118,7 +119,7 @@
 	maxlines = clamp(65536 / padw, 16, 128);
 
 	// now generate the bitmap bits
-	buff = malloc(padw * maxlines); // by default generate 128 lines at a time.
+	MallocT(&buff, padw * maxlines); // by default generate 128 lines at a time.
 	if (buff == NULL) {
 		fclose(f);
 		return false;
@@ -225,7 +226,7 @@
 	maxlines = clamp(65536 / w, 16, 128);
 
 	// now generate the bitmap bits
-	buff = malloc(w * maxlines); // by default generate 128 lines at a time.
+	MallocT(&buff, w * maxlines); // by default generate 128 lines at a time.
 	if (buff == NULL) {
 		png_destroy_write_struct(&png_ptr, &info_ptr);
 		fclose(f);
@@ -322,7 +323,7 @@
 	maxlines = clamp(65536 / w, 16, 128);
 
 	// now generate the bitmap bits
-	buff = malloc(w * maxlines); // by default generate 128 lines at a time.
+	MallocT(&buff, w * maxlines); // by default generate 128 lines at a time.
 	if (buff == NULL) {
 		fclose(f);
 		return false;
--- a/src/settings.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/settings.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -40,6 +40,7 @@
 #include "genworld.h"
 #include "date.h"
 #include "rail.h"
+#include "helpers.hpp"
 #ifdef WITH_FREETYPE
 #include "gfx.h"
 #include "fontcache.h"
@@ -74,7 +75,7 @@
 	SettingsMemoryPool *p;
 	if (minsize < 4096 - 12) minsize = 4096 - 12;
 
-	p = malloc(sizeof(SettingsMemoryPool) - 1 + minsize);
+	p = (SettingsMemoryPool*)malloc(sizeof(SettingsMemoryPool) - 1 + minsize);
 	p->pos = 0;
 	p->size = minsize;
 	p->next = NULL;
@@ -111,7 +112,7 @@
 
 static void *pool_strdup(SettingsMemoryPool **pool, const char *mem, uint size)
 {
-	byte *p = pool_alloc(pool, size + 1);
+	byte *p = (byte*)pool_alloc(pool, size + 1);
 	p[size] = 0;
 	memcpy(p, mem, size);
 	return p;
@@ -168,9 +169,9 @@
 // allocate an ini group object
 static IniGroup *ini_group_alloc(IniFile *ini, const char *grpt, int len)
 {
-	IniGroup *grp = pool_alloc(&ini->pool, sizeof(IniGroup));
+	IniGroup *grp = (IniGroup*)pool_alloc(&ini->pool, sizeof(IniGroup));
 	grp->ini = ini;
-	grp->name = pool_strdup(&ini->pool, grpt, len);
+	grp->name = (char*)pool_strdup(&ini->pool, grpt, len);
 	if (!strcmp(grp->name, "newgrf") || !strcmp(grp->name, "servers") || !strcmp(grp->name, "bans")) {
 		grp->type = IGT_LIST;
 	} else {
@@ -187,8 +188,8 @@
 
 static IniItem *ini_item_alloc(IniGroup *group, const char *name, int len)
 {
-	IniItem *item = pool_alloc(&group->ini->pool, sizeof(IniItem));
-	item->name = pool_strdup(&group->ini->pool, name, len);
+	IniItem *item = (IniItem*)pool_alloc(&group->ini->pool, sizeof(IniItem));
+	item->name = (char*)pool_strdup(&group->ini->pool, name, len);
 	item->next = NULL;
 	item->comment = NULL;
 	item->value = NULL;
@@ -235,7 +236,7 @@
 			if (ns > a) {
 				a = max(a, 128);
 				do a*=2; while (a < ns);
-				comment = realloc(comment, comment_alloc = a);
+				ReallocT(&comment, comment_alloc = a);
 			}
 			pos = comment_size;
 			comment_size += (e - s + 1);
@@ -254,7 +255,7 @@
 			s++; // skip [
 			group = ini_group_alloc(ini, s, e - s);
 			if (comment_size) {
-				group->comment = pool_strdup(&ini->pool, comment, comment_size);
+				group->comment = (char*)pool_strdup(&ini->pool, comment, comment_size);
 				comment_size = 0;
 			}
 		} else if (group) {
@@ -264,7 +265,7 @@
 			// it's an item in an existing group
 			item = ini_item_alloc(group, s, t-s);
 			if (comment_size) {
-				item->comment = pool_strdup(&ini->pool, comment, comment_size);
+				item->comment = (char*)pool_strdup(&ini->pool, comment, comment_size);
 				comment_size = 0;
 			}
 
@@ -279,7 +280,7 @@
 			if (e > t && e[-1] == '\"') e--;
 			*e = '\0';
 
-			item->value = pool_strdup(&ini->pool, t, e - t);
+			item->value = (char*)pool_strdup(&ini->pool, t, e - t);
 		} else {
 			// it's an orphan item
 			ShowInfoF("ini: '%s' outside of group", buffer);
@@ -287,7 +288,7 @@
 	}
 
 	if (comment_size > 0) {
-		ini->comment = pool_strdup(&ini->pool, comment, comment_size);
+		ini->comment = (char*)pool_strdup(&ini->pool, comment, comment_size);
 		comment_size = 0;
 	}
 
@@ -311,7 +312,7 @@
 
 	// otherwise make a new one
 	group = ini_group_alloc(ini, name, len);
-	group->comment = pool_strdup(&ini->pool, "\n", 1);
+	group->comment = (char*)pool_strdup(&ini->pool, "\n", 1);
 	return group;
 }
 
@@ -603,6 +604,7 @@
 
 	case SDT_STRING:
 	case SDT_INTLIST: return str;
+	default: break;
 	}
 
 	return NULL;
@@ -704,7 +706,7 @@
 			switch (GetVarMemType(sld->conv)) {
 				case SLE_VAR_STRB:
 				case SLE_VAR_STRBQ:
-					if (p != NULL) ttd_strlcpy((char*)ptr, p, sld->length);
+					if (p != NULL) ttd_strlcpy((char*)ptr, (const char*)p, sld->length);
 					break;
 				case SLE_VAR_STR:
 				case SLE_VAR_STRQ:
@@ -719,7 +721,7 @@
 			break;
 
 		case SDT_INTLIST: {
-			if (!load_intlist(p, ptr, sld->length, GetVarMemType(sld->conv)))
+			if (!load_intlist((const char*)p, ptr, sld->length, GetVarMemType(sld->conv)))
 				ShowInfoF("ini: error in array '%s'", sdb->name);
 			break;
 		}
@@ -782,7 +784,7 @@
 			case SDT_MANYOFMANY:
 				switch (GetVarMemType(sld->conv)) {
 				case SLE_VAR_BL:
-					if (*(bool*)ptr == (bool)(unsigned long)p) continue;
+					if (*(bool*)ptr == (p != NULL)) continue;
 					break;
 				case SLE_VAR_I8:
 				case SLE_VAR_U8:
@@ -838,7 +840,7 @@
 		}
 
 		/* The value is different, that means we have to write it to the ini */
-		item->value = pool_strdup(&ini->pool, buf, strlen(buf));
+		item->value = (char*)pool_strdup(&ini->pool, buf, strlen(buf));
 	}
 }
 
@@ -945,12 +947,12 @@
  * place) and you DON'T have to increase the savegame version. */
 
 #define NSD_GENERAL(name, def, cmd, guiflags, min, max, interval, many, str, proc)\
-	{name, (const void*)(def), cmd, guiflags, min, max, interval, many, str, proc}
+	{name, (const void*)(def), {cmd}, {guiflags}, min, max, interval, many, str, proc}
 
 /* Macros for various objects to go in the configuration file.
  * This section is for global variables */
 #define SDTG_GENERAL(name, sdt_cmd, sle_cmd, type, flags, guiflags, var, length, def, min, max, interval, full, str, proc, from, to)\
-{NSD_GENERAL(name, def, sdt_cmd, guiflags, min, max, interval, full, str, proc), SLEG_GENERAL(sle_cmd, var, type | flags, length, from, to)}
+	{NSD_GENERAL(name, def, sdt_cmd, guiflags, min, max, interval, full, str, proc), SLEG_GENERAL(sle_cmd, var, type | flags, length, from, to)}
 
 #define SDTG_CONDVAR(name, type, flags, guiflags, var, def, min, max, interval, str, proc, from, to)\
 	SDTG_GENERAL(name, SDT_NUMX, SL_VAR, type, flags, guiflags, var, 0, def, min, max, interval, NULL, str, proc, from, to)
@@ -983,9 +985,9 @@
 	SDTG_CONDMMANY(name, type, flags, guiflags, var, def, full, str, proc, 0, SL_MAX_VERSION)
 
 #define SDTG_CONDNULL(length, from, to)\
-	{{"", NULL, 0, 0, 0, 0, 0, NULL, STR_NULL, NULL}, SLEG_CONDNULL(length, from, to)}
+	{{"", NULL, {0}, {0}, 0, 0, 0, NULL, STR_NULL, NULL}, SLEG_CONDNULL(length, from, to)}
 
-#define SDTG_END() {{NULL, NULL, 0, 0, 0, 0, 0, NULL, STR_NULL, NULL}, SLEG_END()}
+#define SDTG_END() {{NULL, NULL, {0}, {0}, 0, 0, 0, NULL, STR_NULL, NULL}, SLEG_END()}
 
 /* Macros for various objects to go in the configuration file.
  * This section is for structures where their various members are saved */
@@ -1032,9 +1034,9 @@
 	SDT_CONDMMANY(base, var, type, 0, SL_MAX_VERSION, flags, guiflags, def, full, str, proc)
 
 #define SDT_CONDNULL(length, from, to)\
-	{{"", NULL, 0, 0, 0, 0, 0, NULL, STR_NULL, NULL}, SLE_CONDNULL(length, from, to)}
+	{{"", NULL, {0}, {0}, 0, 0, 0, NULL, STR_NULL, NULL}, SLE_CONDNULL(length, from, to)}
 
-#define SDT_END() {{NULL, NULL, 0, 0, 0, 0, 0, NULL, STR_NULL, NULL}, SLE_END()}
+#define SDT_END() {{NULL, NULL, {0}, {0}, 0, 0, 0, NULL, STR_NULL, NULL}, SLE_END()}
 
 /* Shortcuts for macros below. Logically if we don't save the value
  * we also don't sync it in a network game */
@@ -1507,7 +1509,8 @@
 	if (group == NULL) return NULL;
 
 	for (item = group->item; item != NULL; item = item->next) {
-		GRFConfig *c = calloc(1, sizeof(*c));
+		GRFConfig *c;
+		CallocT(&c, 1);
 		c->filename = strdup(item->name);
 
 		/* Parse parameters */
@@ -1566,7 +1569,7 @@
 		GRFBuildParamList(params, c, lastof(params));
 
 		*item = ini_item_alloc(group, c->filename, strlen(c->filename));
-		(*item)->value = pool_strdup(&ini->pool, params, strlen(params));
+		(*item)->value = (char*)pool_strdup(&ini->pool, params, strlen(params));
 		item = &(*item)->next;
 	}
 }
@@ -1843,7 +1846,7 @@
 	_patches = _patches_newgame; /* backwards compatibility */
 }
 
-const ChunkHandler _setting_chunk_handlers[] = {
+extern const ChunkHandler _setting_chunk_handlers[] = {
 	{ 'OPTS', Save_OPTS, Load_OPTS, CH_RIFF},
 	{ 'PATS', Save_PATS, Load_PATS, CH_RIFF | CH_LAST},
 };
--- a/src/settings.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/settings.h	Mon Jan 15 20:14:06 2007 +0000
@@ -9,31 +9,42 @@
  * with the SLE_ (SLE_VAR/SLE_FILE) enums in saveload.h
  * @see VarTypes
  * @see SettingDescBase */
-enum SettingDescType {
+enum SettingDescTypeLong {
 	/* 4 bytes allocated a maximum of 16 types for GenericType */
+	SDT_BEGIN       = 0,
 	SDT_NUMX        = 0, // any number-type
 	SDT_BOOLX       = 1, // a boolean number
 	SDT_ONEOFMANY   = 2, // bitmasked number where only ONE bit may be set
 	SDT_MANYOFMANY  = 3, // bitmasked number where MULTIPLE bits may be set
 	SDT_INTLIST     = 4, // list of integers seperated by a comma ','
 	SDT_STRING      = 5, // string with a pre-allocated buffer
+	SDT_END,
 	/* 10 more possible primitives */
 };
 
-enum SettingGuiFlag {
+template <> struct EnumPropsT<SettingDescTypeLong> : MakeEnumPropsT<SettingDescTypeLong, byte, SDT_BEGIN, SDT_END, SDT_END> {};
+typedef TinyEnumT<SettingDescTypeLong> SettingDescType;
+
+
+enum SettingGuiFlagLong {
 	/* 8 bytes allocated for a maximum of 8 flags
 	 * Flags directing saving/loading of a variable */
+	SGF_NONE = 0,
 	SGF_0ISDISABLED  = 1 << 0, ///< a value of zero means the feature is disabled
 	SGF_NOCOMMA      = 1 << 1, ///< number without any thousand seperators (no formatting)
 	SGF_MULTISTRING  = 1 << 2, ///< the value represents a limited number of string-options (internally integer)
 	SGF_NETWORK_ONLY = 1 << 3, ///< this setting only applies to network games
 	SGF_CURRENCY     = 1 << 4, ///< the number represents money, so when reading value multiply by exchange rate
+	SGF_END          = 1 << 5,
 	/* 3 more possible flags */
 };
 
+DECLARE_ENUM_AS_BIT_SET(SettingGuiFlagLong);
+template <> struct EnumPropsT<SettingGuiFlagLong> : MakeEnumPropsT<SettingGuiFlagLong, byte, SGF_NONE, SGF_END, SGF_END> {};
+typedef TinyEnumT<SettingGuiFlagLong> SettingGuiFlag;
+
+
 typedef int32 OnChange(int32 var);
-typedef byte SettingDescType;
-typedef byte SettingGuiFlag;
 
 typedef struct SettingDescBase {
 	const char *name;       ///< name of the setting. Used in configuration file and for console
--- a/src/settings_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/settings_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -21,6 +21,7 @@
 #include "settings.h"
 #include "vehicle.h"
 #include "date.h"
+#include "helpers.hpp"
 
 static uint32 _difficulty_click_a;
 static uint32 _difficulty_click_b;
@@ -409,8 +410,8 @@
 
 		y = GAMEDIFF_WND_TOP_OFFSET;
 		for (i = 0; i != GAME_DIFFICULTY_NUM; i++) {
-			DrawFrameRect( 5, y,  5 + 8, y + 8, 3, GetBitAndShift(&click_a) ? FR_LOWERED : 0);
-			DrawFrameRect(15, y, 15 + 8, y + 8, 3, GetBitAndShift(&click_b) ? FR_LOWERED : 0);
+			DrawFrameRect( 5, y,  5 + 8, y + 8, 3, GetBitAndShift(&click_a) ? FR_LOWERED : FR_NONE);
+			DrawFrameRect(15, y, 15 + 8, y + 8, 3, GetBitAndShift(&click_b) ? FR_LOWERED : FR_NONE);
 			if (GetBitAndShift(&disabled) || (_networking && !_network_server)) {
 				int color = PALETTE_MODIFIER_GREYOUT | _colour_gradient[COLOUR_YELLOW][2];
 				GfxFillRect( 6, y + 1,  6 + 8, y + 8, color);
@@ -499,7 +500,7 @@
 				if (val != ((int*)&_opt_ptr->diff)[btn])
 					DoCommandP(0, btn, val, NULL, CMD_CHANGE_DIFFICULTY_LEVEL);
 			}
-			DoCommandP(0, -1, _opt_mod_temp.diff_level, NULL, CMD_CHANGE_DIFFICULTY_LEVEL);
+			DoCommandP(0, UINT_MAX, _opt_mod_temp.diff_level, NULL, CMD_CHANGE_DIFFICULTY_LEVEL);
 			DeleteWindow(w);
 			// If we are in the editor, we should reload the economy.
 			//  This way when you load a game, the max loan and interest rate
@@ -693,7 +694,7 @@
 			for (page = &_patches_page[0]; page != endof(_patches_page); page++) {
 				uint i;
 
-				page->entries = malloc(page->num * sizeof(*page->entries));
+				MallocT(&page->entries, page->num);
 				for (i = 0; i != page->num; i++) {
 					uint index;
 					const SettingDesc *sd = GetPatchFromName(page->names[i], &index);
@@ -734,7 +735,7 @@
 				/* Draw checkbox for boolean-value either on/off */
 				bool on = (*(bool*)var);
 
-				DrawFrameRect(x, y, x + 19, y + 8, _bool_ctabs[!!on][!!editable], on ? FR_LOWERED : 0);
+				DrawFrameRect(x, y, x + 19, y + 8, _bool_ctabs[!!on][!!editable], on ? FR_LOWERED : FR_NONE);
 				SetDParam(0, on ? STR_CONFIG_PATCHES_ON : STR_CONFIG_PATCHES_OFF);
 			} else {
 				int32 value;
@@ -930,8 +931,8 @@
 {
 	int color = PALETTE_MODIFIER_GREYOUT | _colour_gradient[COLOUR_YELLOW][2];
 
-	DrawFrameRect(x,      y + 1, x +  9, y + 9, ctab, (state == 1) ? FR_LOWERED : 0);
-	DrawFrameRect(x + 10, y + 1, x + 19, y + 9, ctab, (state == 2) ? FR_LOWERED : 0);
+	DrawFrameRect(x,      y + 1, x +  9, y + 9, ctab, (state == 1) ? FR_LOWERED : FR_NONE);
+	DrawFrameRect(x + 10, y + 1, x + 19, y + 9, ctab, (state == 2) ? FR_LOWERED : FR_NONE);
 	DrawStringCentered(x +  5, y + 1, STR_6819, 0); // [<]
 	DrawStringCentered(x + 15, y + 1, STR_681A, 0); // [>]
 
@@ -961,19 +962,19 @@
 			y += 12;
 
 			// separator
-			DrawFrameRect(10, y + 1, 29, y + 9, 0, GB(clk, 2, 2) ? FR_LOWERED : 0);
+			DrawFrameRect(10, y + 1, 29, y + 9, 0, GB(clk, 2, 2) ? FR_LOWERED : FR_NONE);
 			x = DrawString(35, y + 1, STR_CURRENCY_SEPARATOR, 0);
 			DoDrawString(_str_separator, x + 4, y + 1, 6);
 			y += 12;
 
 			// prefix
-			DrawFrameRect(10, y + 1, 29, y + 9, 0, GB(clk, 4, 2) ? FR_LOWERED : 0);
+			DrawFrameRect(10, y + 1, 29, y + 9, 0, GB(clk, 4, 2) ? FR_LOWERED : FR_NONE);
 			x = DrawString(35, y + 1, STR_CURRENCY_PREFIX, 0);
 			DoDrawString(_custom_currency.prefix, x + 4, y + 1, 6);
 			y += 12;
 
 			// suffix
-			DrawFrameRect(10, y + 1, 29, y + 9, 0, GB(clk, 6, 2) ? FR_LOWERED : 0);
+			DrawFrameRect(10, y + 1, 29, y + 9, 0, GB(clk, 6, 2) ? FR_LOWERED : FR_NONE);
 			x = DrawString(35, y + 1, STR_CURRENCY_SUFFIX, 0);
 			DoDrawString(_custom_currency.suffix, x + 4, y + 1, 6);
 			y += 12;
--- a/src/ship_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/ship_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -29,12 +29,18 @@
 #include "date.h"
 
 static const uint16 _ship_sprites[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D};
-static const byte _ship_sometracks[4] = {0x19, 0x16, 0x25, 0x2A};
 
-static byte GetTileShipTrackStatus(TileIndex tile)
+static const TrackBits _ship_sometracks[4] = {
+	TRACK_BIT_X | TRACK_BIT_LOWER | TRACK_BIT_LEFT,  // 0x19, // DIAGDIR_NE
+	TRACK_BIT_Y | TRACK_BIT_UPPER | TRACK_BIT_LEFT,  // 0x16, // DIAGDIR_SE
+	TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT, // 0x25, // DIAGDIR_SW
+	TRACK_BIT_Y | TRACK_BIT_LOWER | TRACK_BIT_RIGHT, // 0x2A, // DIAGDIR_NW
+};
+
+static TrackBits GetTileShipTrackStatus(TileIndex tile)
 {
 	uint32 r = GetTileTrackStatus(tile, TRANSPORT_WATER);
-	return r | r >> 8;
+	return TrackdirBitsToTrackBits((TrackdirBits)(TRACKDIR_BIT_MASK & (r | r >> 8)));
 }
 
 void DrawShipEngine(int x, int y, EngineID engine, uint32 image_ormod)
@@ -77,7 +83,7 @@
 
 	if (_patches.new_pathfinding_all) {
 		NPFFoundTargetData ftd;
-		byte trackdir = GetVehicleTrackdir(v);
+		Trackdir trackdir = GetVehicleTrackdir(v);
 		ftd = NPFRouteToDepotTrialError(v->tile, trackdir, TRANSPORT_WATER, v->owner, INVALID_RAILTYPE);
 		if (ftd.best_bird_dist == 0) {
 			best_depot = GetDepotByTile(ftd.node.tile); /* Found target */
@@ -350,8 +356,8 @@
 	} else {
 		return;
 	}
-	v->direction    = GB(m, 0, 8);
-	v->u.ship.state = GB(m, 8, 8);
+	v->direction    = (Direction)GB(m, 0, 8);
+	v->u.ship.state = (TrackBits)GB(m, 8, 8);
 	v->vehstatus &= ~VS_HIDDEN;
 
 	v->cur_speed = 0;
@@ -447,10 +453,10 @@
 
 static const byte _pick_shiptrack_table[6] = {1, 3, 2, 2, 0, 0};
 
-static uint FindShipTrack(Vehicle *v, TileIndex tile, int dir, uint bits, TileIndex skiptile, int *track)
+static uint FindShipTrack(Vehicle *v, TileIndex tile, DiagDirection dir, TrackBits bits, TileIndex skiptile, Track *track)
 {
 	PathFindShip pfs;
-	int i, best_track;
+	Track i, best_track;
 	uint best_bird_dist = 0;
 	uint best_length    = 0;
 	uint r;
@@ -459,18 +465,17 @@
 	pfs.dest_coords = v->dest_tile;
 	pfs.skiptile = skiptile;
 
-	best_track = -1;
+	best_track = INVALID_TRACK;
 
 	do {
-		i = FIND_FIRST_BIT(bits);
-		bits = KILL_FIRST_BIT(bits);
+		i = RemoveFirstTrack(bits);
 
 		pfs.best_bird_dist = (uint)-1;
 		pfs.best_length = (uint)-1;
 
-		FollowTrack(tile, 0x3800 | TRANSPORT_WATER, _ship_search_directions[i][dir], (TPFEnumProc*)ShipTrackFollower, NULL, &pfs);
+		FollowTrack(tile, 0x3800 | TRANSPORT_WATER, (DiagDirection)_ship_search_directions[i][dir], (TPFEnumProc*)ShipTrackFollower, NULL, &pfs);
 
-		if (best_track >= 0) {
+		if (best_track != INVALID_TRACK) {
 			if (pfs.best_bird_dist != 0) {
 				/* neither reached the destination, pick the one with the smallest bird dist */
 				if (pfs.best_bird_dist > best_bird_dist) goto bad;
@@ -512,19 +517,19 @@
 /* returns the track to choose on the next tile, or -1 when it's better to
  * reverse. The tile given is the tile we are about to enter, enterdir is the
  * direction in which we are entering the tile */
-static int ChooseShipTrack(Vehicle *v, TileIndex tile, int enterdir, uint tracks)
+static Track ChooseShipTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks)
 {
 	assert(enterdir>=0 && enterdir<=3);
 
 	if (_patches.yapf.ship_use_yapf) {
 		Trackdir trackdir = YapfChooseShipTrack(v, tile, enterdir, tracks);
-		return (trackdir != INVALID_TRACKDIR) ? (int)TrackdirToTrack(trackdir) : -1;
+		return (trackdir != INVALID_TRACKDIR) ? TrackdirToTrack(trackdir) : INVALID_TRACK;
 	} else if (_patches.new_pathfinding_all) {
 		NPFFindStationOrTileData fstd;
 		NPFFoundTargetData ftd;
 		TileIndex src_tile = TILE_ADD(tile, TileOffsByDiagDir(ReverseDiagDir(enterdir)));
-		byte trackdir = GetVehicleTrackdir(v);
-		assert (trackdir != 0xFF); /* Check that we are not in a depot */
+		Trackdir trackdir = GetVehicleTrackdir(v);
+		assert(trackdir != INVALID_TRACKDIR); /* Check that we are not in a depot */
 
 		NPFFillWithOrderData(&fstd, v);
 
@@ -535,21 +540,20 @@
 			the direction we need to take to get there, if ftd.best_bird_dist is not 0,
 			we did not find our target, but ftd.best_trackdir contains the direction leading
 			to the tile closest to our target. */
-			return ftd.best_trackdir & 7; /* TODO: Wrapper function? */
+			return TrackdirToTrack(ftd.best_trackdir); /* TODO: Wrapper function? */
 		} else {
-			return -1; /* Already at target, reverse? */
+			return INVALID_TRACK; /* Already at target, reverse? */
 		}
 	} else {
-		uint b;
 		uint tot_dist, dist;
-		int track;
+		Track track;
 		TileIndex tile2;
 
 		tile2 = TILE_ADD(tile, -TileOffsByDiagDir(enterdir));
 		tot_dist = (uint)-1;
 
 		/* Let's find out how far it would be if we would reverse first */
-		b = GetTileShipTrackStatus(tile2) & _ship_sometracks[ReverseDiagDir(enterdir)] & v->u.ship.state;
+		TrackBits b = GetTileShipTrackStatus(tile2) & _ship_sometracks[ReverseDiagDir(enterdir)] & v->u.ship.state;
 		if (b != 0) {
 			dist = FindShipTrack(v, tile2, ReverseDiagDir(enterdir), b, tile, &track);
 			if (dist != (uint)-1)
@@ -559,18 +563,18 @@
 		dist = FindShipTrack(v, tile, enterdir, tracks, 0, &track);
 		if (dist > tot_dist)
 			/* We could better reverse */
-			return -1;
+			return INVALID_TRACK;
 		return track;
 	}
 }
 
 static const Direction _new_vehicle_direction_table[] = {
-	DIR_N , DIR_NW, DIR_W , 0,
-	DIR_NE, DIR_N , DIR_SW, 0,
+	DIR_N , DIR_NW, DIR_W , INVALID_DIR,
+	DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
 	DIR_E , DIR_SE, DIR_S
 };
 
-static int ShipGetNewDirectionFromTiles(TileIndex new_tile, TileIndex old_tile)
+static Direction ShipGetNewDirectionFromTiles(TileIndex new_tile, TileIndex old_tile)
 {
 	uint offs = (TileY(new_tile) - TileY(old_tile) + 1) * 4 +
 							TileX(new_tile) - TileX(old_tile) + 1;
@@ -578,17 +582,17 @@
 	return _new_vehicle_direction_table[offs];
 }
 
-static int ShipGetNewDirection(Vehicle *v, int x, int y)
+static Direction ShipGetNewDirection(Vehicle *v, int x, int y)
 {
 	uint offs = (y - v->y_pos + 1) * 4 + (x - v->x_pos + 1);
 	assert(offs < 11 && offs != 3 && offs != 7);
 	return _new_vehicle_direction_table[offs];
 }
 
-static int GetAvailShipTracks(TileIndex tile, int dir)
+static TrackBits GetAvailShipTracks(TileIndex tile, int dir)
 {
 	uint32 r = GetTileTrackStatus(tile, TRANSPORT_WATER);
-	return (byte) ((r | r >> 8)) & _ship_sometracks[dir];
+	return (TrackBits)((r | r >> 8) & _ship_sometracks[dir]);
 }
 
 static const byte _ship_subcoord[4][6][3] = {
@@ -632,8 +636,8 @@
 	uint32 r;
 	const byte *b;
 	Direction dir;
-	int track;
-	int tracks;
+	Track track;
+	TrackBits tracks;
 
 	v->tick_counter++;
 
@@ -737,7 +741,7 @@
 
 		// Choose a direction, and continue if we find one
 		track = ChooseShipTrack(v, gp.new_tile, diagdir, tracks);
-		if (track < 0)
+		if (track == INVALID_TRACK)
 			goto reverse_direction;
 
 		b = _ship_subcoord[diagdir][track];
@@ -751,10 +755,10 @@
 
 		if (!(r&0x4)) {
 			v->tile = gp.new_tile;
-			v->u.ship.state = 1 << track;
+			v->u.ship.state = TrackToTrackBits(track);
 		}
 
-		v->direction = b[2];
+		v->direction = (Direction)b[2];
 	}
 
 	/* update image of ship, as well as delta XY */
@@ -872,7 +876,7 @@
 		_new_vehicle_id = v->index;
 
 		v->string_id = STR_SV_SHIP_NAME;
-		v->u.ship.state = 0x80;
+		v->u.ship.state = TRACK_BIT_SPECIAL;
 
 		v->service_interval = _patches.servint_ships;
 		v->date_of_last_service = _date;
--- a/src/signs.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/signs.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -272,6 +272,6 @@
 	_sign_sort_dirty = true;
 }
 
-const ChunkHandler _sign_chunk_handlers[] = {
+extern const ChunkHandler _sign_chunk_handlers[] = {
 	{ 'SIGN', Save_SIGN, Load_SIGN, CH_ARRAY | CH_LAST},
 };
--- a/src/signs.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/signs.h	Mon Jan 15 20:14:06 2007 +0000
@@ -11,7 +11,7 @@
 	int32        x;
 	int32        y;
 	byte         z;
-	PlayerID     owner; // placed by this player. Anyone can delete them though. OWNER_NONE for gray signs from old games.
+	PlayerByte   owner; // placed by this player. Anyone can delete them though. OWNER_NONE for gray signs from old games.
 
 	SignID       index;
 } Sign;
--- a/src/sound.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/sound.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -11,6 +11,7 @@
 #include "viewport.h"
 #include "fileio.h"
 #include "newgrf_sound.h"
+#include "helpers.hpp"
 
 static uint _file_count;
 static FileEntry *_files;
@@ -28,7 +29,7 @@
 
 	FioOpenFile(SOUND_SLOT, filename);
 	count = FioReadDword() / 8;
-	fe = calloc(count, sizeof(*fe));
+	CallocT(&fe, count);
 
 	if (fe == NULL) {
 		_file_count = 0;
@@ -109,7 +110,7 @@
 
 	if (fe->file_size == 0) return false;
 
-	mem = malloc(fe->file_size);
+	MallocT(&mem, fe->file_size);
 	if (mem == NULL) return false;
 
 	FioSeekToFile(fe->file_offset);
--- a/src/sound.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/sound.h	Mon Jan 15 20:14:06 2007 +0000
@@ -3,6 +3,8 @@
 #ifndef SOUND_H
 #define SOUND_H
 
+#include "helpers.hpp"
+
 typedef struct MusicFileSettings {
 	byte playlist;
 	byte music_vol;
@@ -30,7 +32,8 @@
 uint GetNumOriginalSounds(void);
 
 typedef enum SoundFx {
-	SND_02_SPLAT,                          //  0 == 0x00 !
+	SND_BEGIN = 0,
+	SND_02_SPLAT = 0,                          //  0 == 0x00 !
 	SND_03_FACTORY_WHISTLE,
 	SND_04_TRAIN,
 	SND_05_TRAIN_THROUGH_TUNNEL,
@@ -102,9 +105,14 @@
 	SND_45_PLANE_CRASHING,
 	SND_46_PLANE_ENGINE_SPUTTERING,
 	SND_47_MAGLEV_2,
-	SND_48_DISTANT_BIRD                    // 72 == 0x48
+	SND_48_DISTANT_BIRD,                    // 72 == 0x48
+	SND_END
 } SoundFx;
 
+/** Define basic enum properties */
+template <> struct EnumPropsT<SoundFx> : MakeEnumPropsT<SoundFx, byte, SND_BEGIN, SND_END, SND_END> {};
+typedef TinyEnumT<SoundFx> SoundFxByte;
+
 void SndPlayTileFx(SoundFx sound, TileIndex tile);
 void SndPlayVehicleFx(SoundFx sound, const Vehicle *v);
 void SndPlayFx(SoundFx sound);
--- a/src/sound/win32_s.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/sound/win32_s.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -5,6 +5,7 @@
 #include "../driver.h"
 #include "../functions.h"
 #include "../mixer.h"
+#include "../helpers.hpp"
 #include "win32_s.h"
 #include <windows.h>
 #include <mmsystem.h>
@@ -17,7 +18,7 @@
 {
 	hdr->dwBufferLength = _bufsize * 4;
 	hdr->dwFlags = 0;
-	hdr->lpData = malloc(_bufsize * 4);
+	MallocT(&hdr->lpData, _bufsize * 4);
 	if (hdr->lpData == NULL ||
 			waveOutPrepareHeader(_waveout, hdr, sizeof(WAVEHDR)) != MMSYSERR_NOERROR)
 		error("waveOutPrepareHeader failed");
--- a/src/spritecache.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/spritecache.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -8,6 +8,7 @@
 #include "spritecache.h"
 #include "table/sprites.h"
 #include "fileio.h"
+#include "helpers.hpp"
 
 #define SPRITE_CACHE_SIZE 1024*1024
 
@@ -37,7 +38,7 @@
 
 		DEBUG(sprite, 4, "Increasing sprite cache to %d items (%d bytes)", items, items * sizeof(*_spritecache));
 
-		_spritecache = realloc(_spritecache, items * sizeof(*_spritecache));
+		ReallocT(&_spritecache, items);
 
 		if (_spritecache == NULL) {
 			error("Unable to allocate sprite cache of %d items (%d bytes)", items, items * sizeof(*_spritecache));
@@ -132,7 +133,7 @@
 	num  = FioReadWord();
 	type = FioReadByte();
 	if (type == 0xFF) {
-		byte* dest = AllocSprite(num);
+		byte* dest = (byte*)AllocSprite(num);
 
 		sc->ptr = dest;
 		FioReadBlock(dest, num);
@@ -145,7 +146,7 @@
 		byte* dest;
 
 		num = (type & 0x02) ? width * height : num - 8;
-		sprite = AllocSprite(sizeof(*sprite) + num);
+		sprite = (Sprite*)AllocSprite(sizeof(*sprite) + num);
 		sc->ptr = sprite;
 		sprite->info   = type;
 		sprite->height = (id != 142) ? height : 10; // Compensate for a TTD bug
@@ -195,10 +196,10 @@
 }
 
 
-void DupSprite(SpriteID old, SpriteID new)
+void DupSprite(SpriteID old_spr, SpriteID new_spr)
 {
-	SpriteCache *scold = GetSpriteCache(old);
-	SpriteCache *scnew = AllocateSpriteCache(new);
+	SpriteCache *scold = GetSpriteCache(old_spr);
+	SpriteCache *scnew = AllocateSpriteCache(new_spr);
 
 	scnew->file_pos = scold->file_pos;
 	scnew->ptr = NULL;
@@ -306,7 +307,7 @@
 static void DeleteEntryFromSpriteCache(void)
 {
 	SpriteID i;
-	uint best = -1;
+	uint best = UINT_MAX;
 	MemBlock* s;
 	int cur_lru;
 
@@ -403,7 +404,7 @@
 void GfxInitSpriteMem(void)
 {
 	// initialize sprite cache heap
-	if (_spritecache_ptr == NULL) _spritecache_ptr = malloc(SPRITE_CACHE_SIZE);
+	if (_spritecache_ptr == NULL) _spritecache_ptr = (MemBlock*)malloc(SPRITE_CACHE_SIZE);
 
 	// A big free block
 	_spritecache_ptr->size = (SPRITE_CACHE_SIZE - sizeof(MemBlock)) | S_FREE_MASK;
--- a/src/spritecache.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/spritecache.h	Mon Jan 15 20:14:06 2007 +0000
@@ -17,19 +17,19 @@
 
 static inline const Sprite *GetSprite(SpriteID sprite)
 {
-	return GetRawSprite(sprite);
+	return (Sprite*)GetRawSprite(sprite);
 }
 
 static inline const byte *GetNonSprite(SpriteID sprite)
 {
-	return GetRawSprite(sprite);
+	return (byte*)GetRawSprite(sprite);
 }
 
 void GfxInitSpriteMem(void);
 void IncreaseSpriteLRU(void);
 
 bool LoadNextSprite(int load_index, byte file_index);
-void DupSprite(SpriteID old, SpriteID new);
+void DupSprite(SpriteID old_spr, SpriteID new_spr);
 void SkipSprites(uint count);
 
 #endif /* SPRITECACHE_H */
--- a/src/station.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/station.h	Mon Jan 15 20:14:06 2007 +0000
@@ -26,10 +26,11 @@
 } RoadStopType;
 
 enum {
-	INVALID_STATION = 0xFFFF,
 	ROAD_STOP_LIMIT = 16,
 };
 
+static const StationID INVALID_STATION = 0xFFFF;
+
 typedef struct RoadStop {
 	TileIndex xy;
 	bool used;
@@ -64,7 +65,7 @@
 	byte time_since_load;
 	byte time_since_unload;
 	byte delete_ctr;
-	PlayerID owner;
+	PlayerByte owner;
 	byte facilities;
 	byte airport_type;
 
--- a/src/station_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/station_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -33,6 +33,7 @@
 #include "newgrf_station.h"
 #include "yapf/yapf.h"
 #include "date.h"
+#include "helpers.hpp"
 
 typedef enum StationRectModes
 {
@@ -982,7 +983,7 @@
 	if (!ValParamRailtype(p2 & 0xF)) return CMD_ERROR;
 
 	/* unpack parameters */
-	axis = p1 & 1;
+	axis = (Axis)(p1 & 1);
 	numtracks = GB(p1,  8, 8);
 	plat_len  = GB(p1, 16, 8);
 	/* w = length, h = num_tracks */
@@ -1052,7 +1053,7 @@
 	if (GB(p2, 8, 8) >= STAT_CLASS_MAX) return CMD_ERROR;
 
 	/* Check if we can allocate a custom stationspec to this station */
-	statspec = GetCustomStationSpec(GB(p2, 8, 8), GB(p2, 16, 8));
+	statspec = GetCustomStationSpec((StationClassID)GB(p2, 8, 8), GB(p2, 16, 8));
 	specindex = AllocateSpecToStation(statspec, st, flags & DC_EXEC);
 	if (specindex == -1) return CMD_ERROR;
 
@@ -1097,7 +1098,7 @@
 		tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
 		track = AxisToTrack(axis);
 
-		layout_ptr = alloca(numtracks * plat_len);
+		layout_ptr = (byte*)alloca(numtracks * plat_len);
 		GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
 
 		numtracks_orig = numtracks;
@@ -1107,7 +1108,7 @@
 			int w = plat_len;
 			do {
 				byte layout = *layout_ptr++;
-				MakeRailStation(tile, st->owner, st->index, axis, layout, GB(p2, 0, 4));
+				MakeRailStation(tile, st->owner, st->index, axis, layout, (RailType)GB(p2, 0, 4));
 				SetCustomStationSpecIndex(tile, specindex);
 				SetStationTileRandomBits(tile, GB(Random(), 0, 4));
 
@@ -1424,7 +1425,7 @@
 	bool type = !!p2;
 
 	/* Saveguard the parameters */
-	if (!IsValidDiagDirection(p1)) return CMD_ERROR;
+	if (!IsValidDiagDirection((DiagDirection)p1)) return CMD_ERROR;
 
 	SET_EXPENSES_TYPE(EXPENSES_CONSTRUCTION);
 
@@ -1435,7 +1436,7 @@
 	if (CmdFailed(ret)) return ret;
 	cost = ret;
 
-	st = GetStationAround(tile, 1, 1, -1);
+	st = GetStationAround(tile, 1, 1, INVALID_STATION);
 	if (st == CHECK_STATIONS_ERR) return CMD_ERROR;
 
 	/* Find a station close to us */
@@ -1500,7 +1501,7 @@
 
 		StationRect_BeforeAddTile(st, tile, RECT_MODE_TRY);
 
-		MakeRoadStop(tile, st->owner, st->index, type, p1);
+		MakeRoadStop(tile, st->owner, st->index, type ? RS_TRUCK : RS_BUS, (DiagDirection)p1);
 
 		UpdateStationVirtCoordDirty(st);
 		UpdateStationAcceptance(st, false);
@@ -1696,7 +1697,7 @@
 	if (CmdFailed(ret)) return ret;
 	cost = ret;
 
-	st = GetStationAround(tile, w, h, -1);
+	st = GetStationAround(tile, w, h, INVALID_STATION);
 	if (st == CHECK_STATIONS_ERR) return CMD_ERROR;
 
 	/* Find a station close to us */
@@ -1973,7 +1974,7 @@
 	/* middle */
 	st = GetStationAround(
 		tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
-		_dock_w_chk[direction], _dock_h_chk[direction], -1);
+		_dock_w_chk[direction], _dock_h_chk[direction], INVALID_STATION);
 	if (st == CHECK_STATIONS_ERR) return CMD_ERROR;
 
 	/* Find a station close to us */
@@ -2109,7 +2110,7 @@
 
 			/* Ensure the chosen tile layout is valid for this custom station */
 			if (statspec->renderdata != NULL) {
-				t = &statspec->renderdata[tile < statspec->tiles ? tile : GetRailStationAxis(ti->tile)];
+				t = &statspec->renderdata[tile < statspec->tiles ? tile : (uint)GetRailStationAxis(ti->tile)];
 			}
 		}
 	}
@@ -2507,10 +2508,10 @@
 			}
 
 			{
-				int or = ge->rating; // old rating
+				int or_ = ge->rating; // old rating
 
 				// only modify rating in steps of -2, -1, 0, 1 or 2
-				ge->rating = rating = or + clamp(clamp(rating, 0, 255) - or, -2, 2);
+				ge->rating = rating = or_ + clamp(clamp(rating, 0, 255) - or_, -2, 2);
 
 				// if rating is <= 64 and more than 200 items waiting, remove some random amount of goods from the station
 				if (rating <= 64 && waiting >= 200) {
@@ -2932,7 +2933,7 @@
 }
 
 
-const TileTypeProcs _tile_type_station_procs = {
+extern const TileTypeProcs _tile_type_station_procs = {
 	DrawTile_Station,           /* draw_tile_proc */
 	GetSlopeZ_Station,          /* get_slope_z_proc */
 	ClearTile_Station,          /* clear_tile_proc */
@@ -3064,7 +3065,7 @@
 
 	if (st->num_specs != 0) {
 		/* Allocate speclist memory when loading a game */
-		if (st->speclist == NULL) st->speclist = calloc(st->num_specs, sizeof(*st->speclist));
+		if (st->speclist == NULL) CallocT(&st->speclist, st->num_specs);
 		for (i = 0; i < st->num_specs; i++) SlObject(&st->speclist[i], _station_speclist_desc);
 	}
 }
@@ -3155,7 +3156,7 @@
 	}
 }
 
-const ChunkHandler _station_chunk_handlers[] = {
+extern const ChunkHandler _station_chunk_handlers[] = {
 	{ 'STNS', Save_STNS,      Load_STNS,      CH_ARRAY },
 	{ 'ROAD', Save_ROADSTOP,  Load_ROADSTOP,  CH_ARRAY | CH_LAST},
 };
--- a/src/station_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/station_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -18,6 +18,7 @@
 #include "vehicle_gui.h"
 #include "date.h"
 #include "vehicle.h"
+#include "helpers.hpp"
 
 enum StationListWidgets {
 	STATIONLIST_WIDGET_CLOSEBOX = 0,
@@ -156,6 +157,8 @@
 	SL_REBUILD = 0x04,
 } StationListFlags;
 
+DECLARE_ENUM_AS_BIT_SET(StationListFlags);
+
 typedef struct plstations_d {
 	const Station** sort_list;
 	uint16 list_length;
@@ -201,7 +204,7 @@
 	if (!(sl->flags & SL_REBUILD)) return;
 
 	/* Create array for sorting */
-	station_sort = malloc((GetMaxStationIndex() + 1) * sizeof(station_sort[0]));
+	MallocT(&station_sort, GetMaxStationIndex() + 1);
 	if (station_sort == NULL) error("Could not allocate memory for the station-sorting-list");
 
 	DEBUG(misc, 3, "Building station list for player %d", owner);
@@ -228,7 +231,7 @@
 	}
 
 	free((void*)sl->sort_list);
-	sl->sort_list = malloc(n * sizeof(sl->sort_list[0]));
+	MallocT(&sl->sort_list, n);
 	if (n != 0 && sl->sort_list == NULL) error("Could not allocate memory for the station-sorting-list");
 	sl->list_length = n;
 
@@ -260,7 +263,7 @@
 
 static void PlayerStationsWndProc(Window *w, WindowEvent *e)
 {
-	const PlayerID owner = w->window_number;
+	const PlayerID owner = (PlayerID)w->window_number;
 	static byte facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
 	static uint16 cargo_filter = CARGO_ALL_SELECTED;
 	plstations_d *sl = &WP(w, plstations_d);
@@ -432,7 +435,7 @@
 			break;
 		}
 		case STATIONLIST_WIDGET_SORTBY: /*flip sorting method asc/desc*/
-			TOGGLEBIT(sl->flags, 0); //DESC-flag
+			sl->flags ^= SL_ORDER; //DESC-flag
 			sl->flags |= SL_RESORT;
 			w->flags4 |= 5 << WF_TIMEOUT_SHL;
 			LowerWindowWidget(w, STATIONLIST_WIDGET_SORTBY);
@@ -477,7 +480,7 @@
 		if (--sl->resort_timer == 0) {
 			DEBUG(misc, 3, "Periodic rebuild station list player %d", owner);
 			sl->resort_timer = DAY_TICKS * PERIODIC_RESORT_DAYS;
-			sl->flags |= VL_REBUILD;
+			sl->flags |= SL_REBUILD;
 			SetWindowDirty(w);
 		}
 		break;
--- a/src/stdafx.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/stdafx.h	Mon Jan 15 20:14:06 2007 +0000
@@ -7,6 +7,7 @@
 #include <stddef.h>
 #include <string.h>
 #include <stdlib.h>
+#include <limits.h>
 
 // MacOS X will use an NSAlert to display failed assertaions since they're lost unless running from a terminal
 // strgen always runs from terminal and don't need a window for asserts
@@ -103,6 +104,7 @@
 # define WIN32_LEAN_AND_MEAN     // Exclude rarely-used stuff from Windows headers
 # pragma warning(disable: 4244)  // 'conversion' conversion from 'type1' to 'type2', possible loss of data
 # pragma warning(disable: 4761)  // integral size mismatch in argument : conversion supplied
+# pragma warning(disable: 4200)  // nonstandard extension used : zero-sized array in struct/union
 
 # if _MSC_VER >= 1400              // MSVC 2005 safety checks
 #  pragma warning(disable: 4996)   // 'strdup' was declared deprecated
@@ -306,7 +308,4 @@
 # define Point OTTD_AMIGA_POINT
 #endif
 
-#define EXTERN_C_BEGIN extern "C" {
-#define EXTERN_C_END   }
-
 #endif /* STDAFX_H */
--- a/src/strgen/strgen.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/strgen/strgen.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -4,6 +4,7 @@
 #include "../macros.h"
 #include "../string.h"
 #include "../table/control_codes.h"
+#include "../helpers.hpp"
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
@@ -11,6 +12,8 @@
 
 #if (!defined(WIN32) && !defined(WIN64)) || defined(__CYGWIN__)
 #include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
 #endif
 
 #if defined WIN32 || defined __WATCOMC__
@@ -113,7 +116,7 @@
 
 typedef struct CmdPair {
 	const CmdStruct *a;
-	char *v;
+	const char *v;
 } CmdPair;
 
 typedef struct ParsedCommandStruct {
@@ -842,7 +845,7 @@
 			}
 
 			// Allocate a new LangString
-			ent = calloc(1, sizeof(*ent));
+			CallocT(&ent, 1);
 			_strings[_next_string_id] = ent;
 			ent->index = _next_string_id++;
 			ent->name = strdup(str);
@@ -852,7 +855,8 @@
 		}
 
 		if (casep != NULL) {
-			Case* c = malloc(sizeof(*c));
+			Case* c;
+			MallocT(&c, 1);
 
 			c->caseidx = ResolveCaseName(casep, strlen(casep));
 			c->string = strdup(s);
@@ -881,7 +885,8 @@
 			if (!CheckCommandsMatch(s, ent->english, str)) return;
 
 			if (casep != NULL) {
-				Case* c = malloc(sizeof(*c));
+				Case* c;
+				MallocT(&c, 1);
 
 				c->caseidx = ResolveCaseName(casep, strlen(casep));
 				c->string = strdup(s);
@@ -1021,17 +1026,12 @@
 	out = fopen("tmp.xxx", "w");
 	if (out == NULL) fatal("can't open tmp.xxx");
 
-	fprintf(out, "enum {");
+	fprintf(out, "enum StringIdEnum {");
 
 	lastgrp = 0;
 
 	for (i = 0; i != lengthof(_strings); i++) {
 		if (_strings[i] != NULL) {
-			if (lastgrp != (i >> 11)) {
-				lastgrp = (i >> 11);
-				fprintf(out, "};\n\nenum {");
-			}
-
 			fprintf(out, next == i ? "\t%s,\n" : "\n\t%s = 0x%X,\n", _strings[i]->name, i);
 			next = i + 1;
 		}
--- a/src/string.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/string.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -6,6 +6,7 @@
 #include "string.h"
 #include "macros.h"
 #include "table/control_codes.h"
+#include "helpers.hpp"
 
 #include <stdarg.h>
 #include <ctype.h> // required for tolower()
@@ -63,7 +64,7 @@
 	va_start(va, str);
 	len = vsnprintf(buf, lengthof(buf), str, va);
 	va_end(va);
-	p = malloc(len + 1);
+	MallocT(&p, len + 1);
 	if (p != NULL) memcpy(p, buf, len + 1);
 	return p;
 }
--- a/src/strings.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/strings.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -22,6 +22,7 @@
 #include "music.h"
 #include "date.h"
 #include "industry.h"
+#include "helpers.hpp"
 
 #ifdef WIN32
 /* for opendir/readdir/closedir */
@@ -751,7 +752,7 @@
 				//   8bit   - cargo type
 				//   16-bit - cargo count
 				CargoID cargo = GetInt32(&argv);
-				StringID cargo_str = (cargo == CT_INVALID) ? STR_8838_N_A : _cargoc.names_long[cargo];
+				StringID cargo_str = (cargo == CT_INVALID) ? (StringID)STR_8838_N_A : _cargoc.names_long[cargo];
 				buff = GetStringWithArgs(buff, cargo_str, argv++, last);
 				break;
 			}
@@ -1139,7 +1140,7 @@
 
 	{
 		char *lang = str_fmt("%s%s", _paths.lang_dir, _dynlang.ent[lang_index].file);
-		lang_pack = ReadFileToMem(lang, &len, 200000);
+		lang_pack = (LanguagePack*)ReadFileToMem(lang, &len, 200000);
 		free(lang);
 	}
 	if (lang_pack == NULL) return false;
@@ -1165,7 +1166,7 @@
 	}
 
 	// Allocate offsets
-	langpack_offs = malloc(tot_count * sizeof(*langpack_offs));
+	MallocT(&langpack_offs, tot_count);
 
 	// Fill offsets
 	s = lang_pack->data;
@@ -1229,7 +1230,7 @@
 	if (dir != NULL) {
 		while ((dirent = readdir(dir)) != NULL) {
 			const char *d_name = FS2OTTD(dirent->d_name);
-			char *t = strrchr(d_name, '.');
+			const char *t = strrchr(d_name, '.');
 
 			if (t != NULL && strcmp(t, ".lng") == 0) {
 				languages[num++] = strdup(d_name);
--- a/src/table/ai_rail.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/table/ai_rail.h	Mon Jan 15 20:14:06 2007 +0000
@@ -12,24 +12,23 @@
 	byte p2;
 	byte p3;
 	byte dir;
-	AiDefaultBlockData data[VARARRAY_SIZE];
+	const AiDefaultBlockData *data;
 } AiDefaultRailBlock;
 
 typedef struct {
 	byte dir;
-	AiDefaultBlockData data[VARARRAY_SIZE];
+	const AiDefaultBlockData *data;
 } AiDefaultRoadBlock;
 
 
-#define MKHDR(a,b,c,d,e) a,b,c,d,e,{
+#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 MKEND              {4, 0, {0, 0}}
 
-static const AiDefaultRailBlock _raildata_ai_0 = {
-	MKHDR(1, 2, 1, 0, 1)
+static const AiDefaultBlockData _raildata_ai_0_data[] = {
 	MKDEPOT(2, -1, 1),
 	MKSTATION(0x15, 0, -1),
 	MKRAIL(0x26, 0, 1),
@@ -37,8 +36,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_1 = {
-	MKHDR(1, 2, 1, 0, 3)
+static const AiDefaultRailBlock _raildata_ai_0 = {
+	1, 2, 1, 0, 1, _raildata_ai_0_data
+};
+
+static const AiDefaultBlockData _raildata_ai_1_data[] = {
 	MKDEPOT(2, -1, -1),
 	MKRAIL(0x26, 0, -1),
 	MKSTATION(0x15, 0, 0),
@@ -46,8 +48,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_2 = {
-	MKHDR(1, 2, 1, 0, 0)
+static const AiDefaultRailBlock _raildata_ai_1 = {
+	1, 2, 1, 0, 3, _raildata_ai_1_data
+};
+
+static const AiDefaultBlockData _raildata_ai_2_data[] = {
 	MKDEPOT(1, -1, -1),
 	MKRAIL(0x15, -1, 0),
 	MKSTATION(0x14, 0, 0),
@@ -55,8 +60,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_3 = {
-	MKHDR(1, 2, 1, 0, 2)
+static const AiDefaultRailBlock _raildata_ai_2 = {
+	1, 2, 1, 0, 0, _raildata_ai_2_data
+};
+
+static const AiDefaultBlockData _raildata_ai_3_data[] = {
 	MKDEPOT(1, 1, -1),
 	MKRAIL(0x15, 1, 0),
 	MKSTATION(0x14, -1, 0),
@@ -64,24 +72,33 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_4 = {
-	MKHDR(1, 2, 2, 0, 255)
+static const AiDefaultRailBlock _raildata_ai_3 = {
+	1, 2, 1, 0, 2, _raildata_ai_3_data
+};
+
+static const AiDefaultBlockData _raildata_ai_4_data[] = {
 	MKSTATION(0x15, 0, 0),
 	MKCLRRAIL(3, 0, -1),
 	MKCLRRAIL(1, 0, 2),
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_5 = {
-	MKHDR(1, 2, 2, 0, 255)
+static const AiDefaultRailBlock _raildata_ai_4 = {
+	1, 2, 2, 0, 255, _raildata_ai_4_data
+};
+
+static const AiDefaultBlockData _raildata_ai_5_data[] = {
 	MKSTATION(0x14, 0, 0),
 	MKCLRRAIL(0, -1, 0),
 	MKCLRRAIL(2, 2, 0),
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_6 = {
-	MKHDR(2, 3, 1, 0, 1)
+static const AiDefaultRailBlock _raildata_ai_5 = {
+	1, 2, 2, 0, 255, _raildata_ai_5_data
+};
+
+static const AiDefaultBlockData _raildata_ai_6_data[] = {
 	MKSTATION(0x27, 0, -2),
 	MKRAIL(0xC2, 0, 1),
 	MKRAIL(0xC2, 1, 1),
@@ -92,8 +109,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_7 = {
-	MKHDR(2, 3, 1, 0, 3)
+static const AiDefaultRailBlock _raildata_ai_6 = {
+	2, 3, 1, 0, 1, _raildata_ai_6_data
+};
+
+static const AiDefaultBlockData _raildata_ai_7_data[] = {
 	MKDEPOT(1, 0, -3),
 	MKRAIL(0x1A, 0, -2),
 	MKRAIL(0x26, 1, -2),
@@ -104,8 +124,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_8 = {
-	MKHDR(2, 3, 1, 0, 2)
+static const AiDefaultRailBlock _raildata_ai_7 = {
+	2, 3, 1, 0, 3, _raildata_ai_7_data
+};
+
+static const AiDefaultBlockData _raildata_ai_8_data[] = {
 	MKSTATION(0x26, -2, 0),
 	MKRAIL(0xC1, 1, 0),
 	MKRAIL(0xC1, 1, 1),
@@ -116,8 +139,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_9 = {
-	MKHDR(2, 3, 1, 0, 0)
+static const AiDefaultRailBlock _raildata_ai_8 = {
+	2, 3, 1, 0, 2, _raildata_ai_8_data
+};
+
+static const AiDefaultBlockData _raildata_ai_9_data[] = {
 	MKDEPOT(2, -3, -1),
 	MKRAIL(0x29, -2, -1),
 	MKRAIL(0x15, -2, 0),
@@ -128,8 +154,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_10 = {
-	MKHDR(2, 3, 2, 0, 255)
+static const AiDefaultRailBlock _raildata_ai_9 = {
+	2, 3, 1, 0, 0, _raildata_ai_9_data
+};
+
+static const AiDefaultBlockData _raildata_ai_10_data[] = {
 	MKRAIL(0x1A, 0, -3),
 	MKRAIL(0x20, 1, -3),
 	MKRAIL(0xC2, 0, -2),
@@ -144,8 +173,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_11 = {
-	MKHDR(2, 3, 2, 0, 255)
+static const AiDefaultRailBlock _raildata_ai_10 = {
+	2, 3, 2, 0, 255, _raildata_ai_10_data
+};
+
+static const AiDefaultBlockData _raildata_ai_11_data[] = {
 	MKRAIL(0x29, -3, 0),
 	MKRAIL(0x10, -3, 1),
 	MKRAIL(0xC1, -2, 0),
@@ -160,8 +192,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_12 = {
-	MKHDR(2, 3, 2, 1, 3)
+static const AiDefaultRailBlock _raildata_ai_11 = {
+	2, 3, 2, 0, 255, _raildata_ai_11_data
+};
+
+static const AiDefaultBlockData _raildata_ai_12_data[] = {
 	MKRAIL(0x88, -1, -3),
 	MKRAIL(0x6, 0, -3),
 	MKRAIL(0x2, -1, -2),
@@ -179,8 +214,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_13 = {
-	MKHDR(2, 3, 2, 1, 0)
+static const AiDefaultRailBlock _raildata_ai_12 = {
+	2, 3, 2, 1, 3, _raildata_ai_12_data
+};
+
+static const AiDefaultBlockData _raildata_ai_13_data[] = {
 	MKRAIL(0x21, -3, 0),
 	MKRAIL(0x50, -3, 1),
 	MKRAIL(0x81, -2, 0),
@@ -198,8 +236,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_14 = {
-	MKHDR(2, 3, 2, 1, 1)
+static const AiDefaultRailBlock _raildata_ai_13 = {
+	2, 3, 2, 1, 0, _raildata_ai_13_data
+};
+
+static const AiDefaultBlockData _raildata_ai_14_data[] = {
 	MKRAIL(0x88, -1, -3),
 	MKRAIL(0x6, 0, -3),
 	MKRAIL(0x2, -1, -2),
@@ -217,8 +258,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_15 = {
-	MKHDR(2, 3, 2, 1, 2)
+static const AiDefaultRailBlock _raildata_ai_14 = {
+	2, 3, 2, 1, 1, _raildata_ai_14_data
+};
+
+static const AiDefaultBlockData _raildata_ai_15_data[] = {
 	MKRAIL(0x21, -3, 0),
 	MKRAIL(0x50, -3, 1),
 	MKRAIL(0x81, -2, 0),
@@ -236,8 +280,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_16 = {
-	MKHDR(1, 3, 1, 0, 1)
+static const AiDefaultRailBlock _raildata_ai_15 = {
+	2, 3, 2, 1, 2, _raildata_ai_15_data
+};
+
+static const AiDefaultBlockData _raildata_ai_16_data[] = {
 	MKSTATION(0x17, 0, -2),
 	MKRAIL(0x1A, 0, 1),
 	MKCLRRAIL(1, 0, 2),
@@ -245,8 +292,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_17 = {
-	MKHDR(1, 3, 1, 0, 3)
+static const AiDefaultRailBlock _raildata_ai_16 = {
+	1, 3, 1, 0, 1, _raildata_ai_16_data
+};
+
+static const AiDefaultBlockData _raildata_ai_17_data[] = {
 	MKCLRRAIL(3, 0, -2),
 	MKRAIL(0x26, 0, -1),
 	MKDEPOT(2, -1, -1),
@@ -254,8 +304,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_18 = {
-	MKHDR(1, 3, 1, 0, 0)
+static const AiDefaultRailBlock _raildata_ai_17 = {
+	1, 3, 1, 0, 3, _raildata_ai_17_data
+};
+
+static const AiDefaultBlockData _raildata_ai_18_data[] = {
 	MKCLRRAIL(0, -2, 0),
 	MKRAIL(0x29, -1, 0),
 	MKDEPOT(3, -1, 1),
@@ -263,8 +316,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_19 = {
-	MKHDR(1, 3, 1, 0, 2)
+static const AiDefaultRailBlock _raildata_ai_18 = {
+	1, 3, 1, 0, 0, _raildata_ai_18_data
+};
+
+static const AiDefaultBlockData _raildata_ai_19_data[] = {
 	MKSTATION(0x16, -2, 0),
 	MKDEPOT(2, 0, -1),
 	MKRAIL(0x20, 1, -1),
@@ -273,8 +329,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_20 = {
-	MKHDR(2, 3, 1, 0, 1)
+static const AiDefaultRailBlock _raildata_ai_19 = {
+	1, 3, 1, 0, 2, _raildata_ai_19_data
+};
+
+static const AiDefaultBlockData _raildata_ai_20_data[] = {
 	MKSTATION(0x26, -2, 0),
 	MKRAIL(0xC1, 1, 0),
 	MKRAIL(0xC1, 1, 1),
@@ -285,8 +344,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_21 = {
-	MKHDR(2, 3, 1, 0, 3)
+static const AiDefaultRailBlock _raildata_ai_20 = {
+	2, 3, 1, 0, 1, _raildata_ai_20_data
+};
+
+static const AiDefaultBlockData _raildata_ai_21_data[] = {
 	MKDEPOT(2, -3, -1),
 	MKRAIL(0x3F, -2, -1),
 	MKRAIL(0x10, -2, 0),
@@ -297,8 +359,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_22 = {
-	MKHDR(2, 3, 1, 0, 0)
+static const AiDefaultRailBlock _raildata_ai_21 = {
+	2, 3, 1, 0, 3, _raildata_ai_21_data
+};
+
+static const AiDefaultBlockData _raildata_ai_22_data[] = {
 	MKSTATION(0x27, 0, -2),
 	MKRAIL(0xC2, 0, 1),
 	MKRAIL(0xC2, 1, 1),
@@ -310,8 +375,11 @@
 	MKEND
 };
 
-static const AiDefaultRailBlock _raildata_ai_23 = {
-	MKHDR(2, 3, 1, 0, 2)
+static const AiDefaultRailBlock _raildata_ai_22 = {
+	2, 3, 1, 0, 0, _raildata_ai_22_data
+};
+
+static const AiDefaultBlockData _raildata_ai_23_data[] = {
 	MKDEPOT(1, 0, -3),
 	MKRAIL(0x1A, 0, -2),
 	MKRAIL(0x29, 1, -2),
@@ -322,7 +390,9 @@
 	MKEND
 };
 
-
+static const AiDefaultRailBlock _raildata_ai_23 = {
+	2, 3, 1, 0, 2, _raildata_ai_23_data
+};
 
 static const AiDefaultRailBlock * const _default_rail_track_data[] = {
 	&_raildata_ai_0,
@@ -356,8 +426,7 @@
 
 #define MKHDR(a) a,{
 
-static const AiDefaultRoadBlock _roaddata_ai_0 = {
-	MKHDR(0)
+static const AiDefaultBlockData _roaddata_ai_0_data[] = {
 	MKDEPOT(2, -1,1),
 	MKSTATION(0x2, -1,0),
 	MKRAIL(0xC, 0,0),
@@ -369,8 +438,11 @@
 	MKEND
 };
 
-static const AiDefaultRoadBlock _roaddata_ai_1 = {
-	MKHDR(0)
+static const AiDefaultRoadBlock _roaddata_ai_0 = {
+	0, _roaddata_ai_0_data
+};
+
+static const AiDefaultBlockData _roaddata_ai_1_data[] = {
 	MKDEPOT(1, 0,-1),
 	MKSTATION(0x1, 1,-1),
 	MKRAIL(0x3, 0,0),
@@ -382,8 +454,11 @@
 	MKEND
 };
 
-static const AiDefaultRoadBlock _roaddata_ai_2 = {
-	MKHDR(0)
+static const AiDefaultRoadBlock _roaddata_ai_1 = {
+	0, _roaddata_ai_1_data
+};
+
+static const AiDefaultBlockData _roaddata_ai_2_data[] = {
 	MKDEPOT(3, 1,1),
 	MKSTATION(0x3, 0,1),
 	MKRAIL(0x6, 0,0),
@@ -395,8 +470,11 @@
 	MKEND
 };
 
-static const AiDefaultRoadBlock _roaddata_ai_3 = {
-	MKHDR(0)
+static const AiDefaultRoadBlock _roaddata_ai_2 = {
+	0, _roaddata_ai_2_data
+};
+
+static const AiDefaultBlockData _roaddata_ai_3_data[] = {
 	MKDEPOT(0, 1,0),
 	MKSTATION(0x0, 1,1),
 	MKRAIL(0x6, 0,0),
@@ -408,8 +486,11 @@
 	MKEND
 };
 
-static const AiDefaultRoadBlock _roaddata_ai_4 = {
-	MKHDR(1)
+static const AiDefaultRoadBlock _roaddata_ai_3 = {
+	0, _roaddata_ai_3_data
+};
+
+static const AiDefaultBlockData _roaddata_ai_4_data[] = {
 	MKSTATION(0x2, -1,0),
 	MKRAIL(0x8, 0,0),
 	MKCLRRAIL(0, 0,-1),
@@ -418,8 +499,11 @@
 	MKEND
 };
 
-static const AiDefaultRoadBlock _roaddata_ai_5 = {
-	MKHDR(1)
+static const AiDefaultRoadBlock _roaddata_ai_4 = {
+	1, _roaddata_ai_4_data
+};
+
+static const AiDefaultBlockData _roaddata_ai_5_data[] = {
 	MKSTATION(0x3, 0,1),
 	MKRAIL(0x4, 0,0),
 	MKCLRRAIL(0, -1,0),
@@ -428,8 +512,11 @@
 	MKEND
 };
 
-static const AiDefaultRoadBlock _roaddata_ai_6 = {
-	MKHDR(1)
+static const AiDefaultRoadBlock _roaddata_ai_5 = {
+	1, _roaddata_ai_5_data
+};
+
+static const AiDefaultBlockData _roaddata_ai_6_data[] = {
 	MKSTATION(0x0, 1,1),
 	MKRAIL(0x2, 0,1),
 	MKCLRRAIL(0, 0,0),
@@ -438,8 +525,11 @@
 	MKEND
 };
 
-static const AiDefaultRoadBlock _roaddata_ai_7 = {
-	MKHDR(1)
+static const AiDefaultRoadBlock _roaddata_ai_6 = {
+	1, _roaddata_ai_6_data
+};
+
+static const AiDefaultBlockData _roaddata_ai_7_data[] = {
 	MKSTATION(0x1, 1,-1),
 	MKRAIL(0x1, 1,0),
 	MKCLRRAIL(0, 0,0),
@@ -448,6 +538,10 @@
 	MKEND
 };
 
+static const AiDefaultRoadBlock _roaddata_ai_7 = {
+	1, _roaddata_ai_7_data
+};
+
 
 static const AiDefaultRoadBlock * const _road_default_block_data[] = {
 	&_roaddata_ai_0,
--- a/src/table/engines.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/table/engines.h	Mon Jan 15 20:14:06 2007 +0000
@@ -490,7 +490,7 @@
  * @param g sound effect
  * @param h refittable
  */
-#define SVI(a, b, c, d, e, f, g, h) { a, b, c, d, e, f, g, h }
+#define SVI(a, b, c, d, e, f, g, h) { a, b, c, d, e, f, {g}, h }
 const ShipVehicleInfo orig_ship_vehicle_info[NUM_SHIP_ENGINES] = {
 	//   image_index  cargo_type     cargo_amount                 refittable
 	//   |    base_cost |              |    running_cost          |
@@ -522,7 +522,7 @@
  * @param h mail_capacity
  * @param i passenger_capacity
  */
-#define AVI(a, b, c, d, e, f, g, h, i) { a, b, c, d, e, f, g, h, i }
+#define AVI(a, b, c, d, e, f, g, h, i) { a, b, c, d, {e}, f, g, h, i }
 #define H 0
 #define P AIR_CTOL
 #define J AIR_CTOL | AIR_FAST
@@ -589,7 +589,7 @@
  * @param f capacity
  * @param g cargo_type
  */
-#define RVI(a, b, c, d, e, f, g) { a, b, c, d, e, f, g }
+#define RVI(a, b, c, d, e, f, g) { a, b, c, {d}, e, f, g }
 const RoadVehicleInfo orig_road_vehicle_info[NUM_ROAD_ENGINES] = {
 	//    image_index       sfx                                 max_speed
 	//    |    base_cost    |                                   |   capacity
--- a/src/table/namegen.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/table/namegen.h	Mon Jan 15 20:14:06 2007 +0000
@@ -1727,6 +1727,9 @@
 	CZA_LONG = 4,
 	CZA_ALL = ~0
 } CzechAllow;
+
+DECLARE_ENUM_AS_BIT_SET(CzechAllow);
+
 // All these flags must be satisfied (in the stem->others direction):
 typedef enum CzechChoose {
 	CZC_NONE = 0, // No requirements.
@@ -1736,6 +1739,8 @@
 	CZC_ANY = ~0
 } CzechChoose;
 
+DECLARE_ENUM_AS_BIT_SET(CzechChoose);
+
 typedef struct CzechNameSubst {
 	CzechGender gender;
 	CzechAllow allow;
--- a/src/table/sprites.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/table/sprites.h	Mon Jan 15 20:14:06 2007 +0000
@@ -1336,6 +1336,9 @@
 };
 
 #define PALETTE_RECOLOR_SPRITE(a) (a << PALETTE_SPRITE_START | PALETTE_MODIFIER_COLOR)
+
+static const PalSpriteID PALETTE_CRASH = PALETTE_RECOLOR_SPRITE(0x324);
+
 enum PaletteSprites {
 	//note: these numbers are already the modified once the renderer needs.
 	//the actual sprite number is the upper 16 bits of the number
@@ -1384,7 +1387,8 @@
 	PALETTE_TO_TRANSPARENT      = 0x322 << PALETTE_SPRITE_START | PALETTE_MODIFIER_TRANSPARENT, //This sets the sprite to transparent
 	//This is used for changing the tubular bridges to the silicon display, or some grayish color
 	PALETTE_TO_STRUCT_GREY      = PALETTE_RECOLOR_SPRITE(0x323),
-	PALETTE_CRASH               = PALETTE_RECOLOR_SPRITE(0x324),  //this changes stuff to the "crash color"
+
+	//XXX - const - PALETTE_CRASH               = PALETTE_RECOLOR_SPRITE(0x324),  //this changes stuff to the "crash color"
 	//XXX another place where structures are colored.
 	//I'm not sure which colors these are
 	PALETTE_59E                 = PALETTE_RECOLOR_SPRITE(0x59E),
--- a/src/table/station_land.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/table/station_land.h	Mon Jan 15 20:14:06 2007 +0000
@@ -1,6 +1,6 @@
 /* $Id$ */
 
-#define TILE_SEQ_END()	{ 0x80, 0, 0, 0, 0, 0, 0 }
+#define TILE_SEQ_END()	{ (byte)0x80, 0, 0, 0, 0, 0, 0 }
 
 static const DrawTileSeqStruct _station_display_datas_0[] = {
 	{  0,  0,  0, 16,  5,  2, SPR_RAIL_PLATFORM_X_REAR  | PALETTE_MODIFIER_COLOR },
@@ -30,7 +30,7 @@
 	{  0,  0,  0, 16,  5,  7, SPR_RAIL_PLATFORM_PILLARS_X_REAR | PALETTE_MODIFIER_COLOR },
 	{  0, 11,  0, 16,  5,  2, SPR_RAIL_PLATFORM_X_FRONT        | PALETTE_MODIFIER_COLOR },
 	{  0,  0, 16, 16, 16, 10, SPR_RAIL_ROOF_STRUCTURE_X_TILE_A | PALETTE_MODIFIER_COLOR },
-	{  0,  0,0x80, 0,  0,  0, SPR_RAIL_ROOF_GLASS_X_TILE_A     | PALETTE_TO_TRANSPARENT },
+	{  0,  0,(byte)0x80, 0,  0,  0, SPR_RAIL_ROOF_GLASS_X_TILE_A     | PALETTE_TO_TRANSPARENT },
 	TILE_SEQ_END()
 };
 
@@ -38,7 +38,7 @@
 	{  0,  0,  0,  5, 16,  2, SPR_RAIL_PLATFORM_PILLARS_Y_REAR | PALETTE_MODIFIER_COLOR },
 	{ 11,  0,  0,  5, 16,  2, SPR_RAIL_PLATFORM_Y_FRONT        | PALETTE_MODIFIER_COLOR },
 	{  0,  0, 16, 16, 16, 10, SPR_RAIL_ROOF_STRUCTURE_Y_TILE_A | PALETTE_MODIFIER_COLOR },
-	{  0,  0,0x80, 0,  0,  0, SPR_RAIL_ROOF_GLASS_Y_TILE_A     | PALETTE_TO_TRANSPARENT },
+	{  0,  0,(byte)0x80, 0,  0,  0, SPR_RAIL_ROOF_GLASS_Y_TILE_A     | PALETTE_TO_TRANSPARENT },
 	TILE_SEQ_END()
 };
 
@@ -46,7 +46,7 @@
 	{  0,  0,  0, 16,  5,  2, SPR_RAIL_PLATFORM_X_REAR          | PALETTE_MODIFIER_COLOR },
 	{  0, 11,  0, 16,  5,  2, SPR_RAIL_PLATFORM_PILLARS_X_FRONT | PALETTE_MODIFIER_COLOR },
 	{  0,  0, 16, 16, 16, 10, SPR_RAIL_ROOF_STRUCTURE_X_TILE_B  | PALETTE_MODIFIER_COLOR },
-	{  0,  0,0x80, 0,  0,  0, SPR_RAIL_ROOF_GLASS_X_TILE_B      | PALETTE_TO_TRANSPARENT },
+	{  0,  0,(byte)0x80, 0,  0,  0, SPR_RAIL_ROOF_GLASS_X_TILE_B      | PALETTE_TO_TRANSPARENT },
 	TILE_SEQ_END()
 };
 
@@ -54,7 +54,7 @@
 	{  0,  0,  0,  5, 16,  2, SPR_RAIL_PLATFORM_Y_REAR          | PALETTE_MODIFIER_COLOR },
 	{ 11,  0,  0,  5, 16,  2, SPR_RAIL_PLATFORM_PILLARS_Y_FRONT | PALETTE_MODIFIER_COLOR },
 	{  0,  0, 16, 16, 16, 10, SPR_RAIL_ROOF_STRUCTURE_Y_TILE_B  | PALETTE_MODIFIER_COLOR },
-	{  0,  0,0x80, 0,  0,  0, SPR_RAIL_ROOF_GLASS_Y_TILE_B      | PALETTE_TO_TRANSPARENT },
+	{  0,  0,(byte)0x80, 0,  0,  0, SPR_RAIL_ROOF_GLASS_Y_TILE_B      | PALETTE_TO_TRANSPARENT },
 	TILE_SEQ_END()
 };
 
--- a/src/table/track_land.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/table/track_land.h	Mon Jan 15 20:14:06 2007 +0000
@@ -1,7 +1,7 @@
 /* $Id$ */
 
 #define TILE_SEQ_LINE(img, dx, dy, sx, sy) { dx, dy, 0, sx, sy, 23, img },
-#define TILE_SEQ_END() { 0x80, 0, 0, 0, 0, 0, 0 }
+#define TILE_SEQ_END() { (byte)0x80, 0, 0, 0, 0, 0, 0 }
 
 
 static const DrawTileSeqStruct _depot_gfx_NE[] = {
--- a/src/table/unmovable_land.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/table/unmovable_land.h	Mon Jan 15 20:14:06 2007 +0000
@@ -10,7 +10,7 @@
 	byte unused;
 } DrawTileUnmovableStruct;
 
-#define TILE_SEQ_END() { 0x80, 0, 0, 0, 0, 0, 0 }
+#define TILE_SEQ_END() { (byte)0x80, 0, 0, 0, 0, 0, 0 }
 
 static const DrawTileUnmovableStruct _draw_tile_unmovable_data[] = {
 	{0xA29, 7, 7, 2, 2, 70, 0},
--- a/src/texteff.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/texteff.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -379,6 +379,6 @@
 }
 
 
-const ChunkHandler _animated_tile_chunk_handlers[] = {
+extern const ChunkHandler _animated_tile_chunk_handlers[] = {
 	{ 'ANIT', SaveLoad_ANIT, SaveLoad_ANIT, CH_RIFF | CH_LAST},
 };
--- a/src/tgp.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/tgp.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -14,6 +14,7 @@
 #include "tgp.h"
 #include "console.h"
 #include "genworld.h"
+#include "helpers.hpp"
 
 /*
  * OTTD Perlin Noise Landscape Generator, aka TerraGenesis Perlin
@@ -190,9 +191,8 @@
 #define A2I(i) ((i) >> amplitude_decimal_bits)
 
 /** Conversion: amplitude_t to height_t */
-#define A2H(a) ((height_decimal_bits < amplitude_decimal_bits) \
-	? ((a) >> (amplitude_decimal_bits - height_decimal_bits)) \
-	: ((a) << (height_decimal_bits - amplitude_decimal_bits)))
+#define A2H(a) ((a) >> (amplitude_decimal_bits - height_decimal_bits))
+
 
 /** Walk through all items of _height_map.h */
 #define FOR_ALL_TILES_IN_HEIGHT(h) for (h = _height_map.h; h < &_height_map.h[_height_map.total_size]; h++)
@@ -239,7 +239,7 @@
 	/* Allocate memory block for height map row pointers */
 	_height_map.total_size = (_height_map.size_x + 1) * (_height_map.size_y + 1);
 	_height_map.dim_x = _height_map.size_x + 1;
-	_height_map.h = calloc(_height_map.total_size, sizeof(*_height_map.h));
+	CallocT(&_height_map.h, _height_map.total_size);
 	if (_height_map.h == NULL) return false;
 
 	/* Iterate through height map initialize values */
@@ -455,7 +455,7 @@
 				break;
 		}
 		/* Transform it back into h_min..h_max space */
-		*h = fheight * (h_max - h_min) + h_min;
+		*h = (height_t)(fheight * (h_max - h_min) + h_min);
 		if (*h < 0) *h = I2H(0);
 		if (*h >= h_max) *h = h_max - 1;
 	}
@@ -472,7 +472,7 @@
 	HeightMapGetMinMaxAvg(&h_min, &h_max, &h_avg);
 
 	/* Allocate histogram buffer and clear its cells */
-	hist_buf = calloc(h_max - h_min + 1, sizeof(*hist_buf));
+	CallocT(&hist_buf, h_max - h_min + 1);
 	/* Fill histogram */
 	hist = HeightMapMakeHistogram(h_min, h_max, hist_buf);
 
@@ -529,14 +529,14 @@
 	int smallest_size = min(_patches.map_x, _patches.map_y);
 	const int margin = 4;
 	uint y, x;
-	uint max_x;
-	uint max_y;
+	double max_x;
+	double max_y;
 
 	/* Lower to sea level */
 	for (y = 0; y <= _height_map.size_y; y++) {
 		/* Top right */
 		max_x = myabs((perlin_coast_noise_2D(_height_map.size_y - y, y, 0.9, 53) + 0.25) * 5 + (perlin_coast_noise_2D(y, y, 0.35, 179) + 1) * 12);
-		max_x = max((smallest_size * smallest_size / 16) + max_x, (smallest_size * smallest_size / 16) + margin - max_x);
+		max_x = dmax((smallest_size * smallest_size / 16) + max_x, (smallest_size * smallest_size / 16) + margin - max_x);
 		if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
 		for (x = 0; x < max_x; x++) {
 			HeightMapXY(x, y) = 0;
@@ -544,7 +544,7 @@
 
 		/* Bottom left */
 		max_x = myabs((perlin_coast_noise_2D(_height_map.size_y - y, y, 0.85, 101) + 0.3) * 6 + (perlin_coast_noise_2D(y, y, 0.45,  67) + 0.75) * 8);
-		max_x = max((smallest_size * smallest_size / 16) + max_x, (smallest_size * smallest_size / 16) + margin - max_x);
+		max_x = dmax((smallest_size * smallest_size / 16) + max_x, (smallest_size * smallest_size / 16) + margin - max_x);
 		if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
 		for (x = _height_map.size_x; x > (_height_map.size_x - 1 - max_x); x--) {
 			HeightMapXY(x, y) = 0;
@@ -555,7 +555,7 @@
 	for (x = 0; x <= _height_map.size_x; x++) {
 		/* Top left */
 		max_y = myabs((perlin_coast_noise_2D(x, _height_map.size_y / 2, 0.9, 167) + 0.4) * 5 + (perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.4, 211) + 0.7) * 9);
-		max_y = max((smallest_size * smallest_size / 16) + max_y, (smallest_size * smallest_size / 16) + margin - max_y);
+		max_y = dmax((smallest_size * smallest_size / 16) + max_y, (smallest_size * smallest_size / 16) + margin - max_y);
 		if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
 		for (y = 0; y < max_y; y++) {
 			HeightMapXY(x, y) = 0;
@@ -564,7 +564,7 @@
 
 		/* Bottom right */
 		max_y = myabs((perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.85, 71) + 0.25) * 6 + (perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.35, 193) + 0.75) * 12);
-		max_y = max((smallest_size * smallest_size / 16) + max_y, (smallest_size * smallest_size / 16) + margin - max_y);
+		max_y = dmax((smallest_size * smallest_size / 16) + max_y, (smallest_size * smallest_size / 16) + margin - max_y);
 		if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
 		for (y = _height_map.size_y; y > (_height_map.size_y - 1 - max_y); y--) {
 			HeightMapXY(x, y) = 0;
--- a/src/thread.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/thread.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -3,6 +3,7 @@
 #include "stdafx.h"
 #include "thread.h"
 #include <stdlib.h>
+#include "helpers.hpp"
 
 #if defined(__AMIGA__) || defined(__MORPHOS__) || defined(NO_THREADS)
 OTTDThread *OTTDCreateThread(OTTDThreadFunc function, void *arg) { return NULL; }
@@ -24,20 +25,21 @@
 
 static void Proxy(void* arg)
 {
-	OTTDThread* t = arg;
+	OTTDThread* t = (OTTDThread*)arg;
 	t->ret = t->func(t->arg);
 }
 
 OTTDThread* OTTDCreateThread(OTTDThreadFunc function, void* arg)
 {
-	OTTDThread* t = malloc(sizeof(*t));
+	OTTDThread* t;
+	MallocT(&t, 1);
 
 	if (t == NULL) return NULL;
 
 	t->func = function;
 	t->arg  = arg;
 	t->thread = _beginthread(Proxy, NULL, 32768, t);
-	if (t->thread != -1) {
+	if (t->thread != (TID)-1) {
 		return t;
 	} else {
 		free(t);
@@ -72,7 +74,8 @@
 
 OTTDThread* OTTDCreateThread(OTTDThreadFunc function, void* arg)
 {
-	OTTDThread* t = malloc(sizeof(*t));
+	OTTDThread* t;
+	MallocT(&t, 1);
 
 	if (t == NULL) return NULL;
 
@@ -113,14 +116,15 @@
 
 static DWORD WINAPI Proxy(LPVOID arg)
 {
-	OTTDThread* t = arg;
+	OTTDThread* t = (OTTDThread*)arg;
 	t->ret = t->func(t->arg);
 	return 0;
 }
 
 OTTDThread* OTTDCreateThread(OTTDThreadFunc function, void* arg)
 {
-	OTTDThread* t = malloc(sizeof(*t));
+	OTTDThread* t;
+	MallocT(&t, 1);
 	DWORD dwThreadId;
 
 	if (t == NULL) return NULL;
--- a/src/tile.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/tile.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -16,7 +16,7 @@
 
 	if (TileX(tile) == MapMaxX() || TileY(tile) == MapMaxY()) {
 		if (h != NULL) *h = 0;
-		return 0;
+		return SLOPE_FLAT;
 	}
 
 	min = a = TileHeight(tile);
@@ -35,7 +35,7 @@
 
 	if (h != NULL) *h = min * TILE_HEIGHT;
 
-	return r;
+	return (Slope)r;
 }
 
 uint GetTileZ(TileIndex tile)
--- a/src/tile.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/tile.h	Mon Jan 15 20:14:06 2007 +0000
@@ -4,6 +4,7 @@
 #define TILE_H
 
 #include "macros.h"
+#include "openttd.h"
 #include "map.h"
 #include "slope.h"
 
--- a/src/town.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/town.h	Mon Jan 15 20:14:06 2007 +0000
@@ -36,7 +36,7 @@
 	// Player ratings as well as a mask that determines which players have a rating.
 	byte have_ratings;
 	uint8 unwanted[MAX_PLAYERS]; // how many months companies aren't wanted by towns (bribe)
-	PlayerID exclusivity;        // which player has exslusivity
+	PlayerByte exclusivity;        // which player has exslusivity
 	uint8 exclusive_counter;     // months till the exclusivity expires
 	int16 ratings[MAX_PLAYERS];
 
--- a/src/town_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/town_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -455,7 +455,7 @@
 static RoadBits GetTownRoadMask(TileIndex tile)
 {
 	TrackBits b = GetAnyRoadTrackBits(tile);
-	RoadBits r = 0;
+	RoadBits r = ROAD_NONE;
 
 	if (b & TRACK_BIT_X)     r |= ROAD_X;
 	if (b & TRACK_BIT_Y)     r |= ROAD_Y;
@@ -603,13 +603,13 @@
 			// That means that the road is only allowed if there is a house
 			//  at any side of the new road.
 		}
-		rcmd = (1 << a) + (1 << b);
+		rcmd = (RoadBits)((1 << a) + (1 << b));
 
 	} else if (block < 5 && !HASBIT(mask,block^2)) {
 		// Continue building on a partial road.
 		// Always OK.
 		_grow_town_result = 0;
-		rcmd = 1 << (block ^ 2);
+		rcmd = (RoadBits)(1 << (block ^ 2));
 	} else {
 		int i;
 
@@ -648,7 +648,7 @@
 		}
 
 		_grow_town_result = 0;
-		rcmd = 1 << i;
+		rcmd = (RoadBits)(1 << i);
 	}
 
 	// Return if a water tile
@@ -720,7 +720,7 @@
 
 		// Exclude the source position from the bitmask
 		// and return if no more road blocks available
-		CLRBIT(mask, (block ^ 2));
+		mask = ClrBitT(mask, (block ^ 2));
 		if (mask == 0)
 			return _grow_town_result;
 
@@ -756,7 +756,7 @@
 	uint a = GB(r, 0, 2);
 	uint b = GB(r, 8, 2);
 	if (a == b) b ^= 2;
-	return (1 << a) + (1 << b);
+	return (RoadBits)((1 << a) + (1 << b));
 }
 
 // Grow the town
@@ -793,7 +793,7 @@
 		if (GetAnyRoadTrackBits(tile) != 0) {
 			int r = GrowTownAtRoad(t, tile);
 			_current_player = old_player;
-			return r;
+			return r != 0;
 		}
 		tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
 	}
@@ -948,7 +948,7 @@
 		t->ratings[i] = 500;
 
 	t->have_ratings = 0;
-	t->exclusivity = (byte)-1;
+	t->exclusivity = INVALID_PLAYER;
 	t->exclusive_counter = 0;
 	t->statues = 0;
 
@@ -1422,7 +1422,7 @@
 	_generating_world = false;
 }
 
-const byte _town_action_costs[8] = {
+extern const byte _town_action_costs[8] = {
 	2, 4, 9, 35, 48, 53, 117, 175
 };
 
@@ -1807,7 +1807,7 @@
 		if (t->road_build_months != 0) t->road_build_months--;
 
 		if (t->exclusive_counter != 0)
-			if (--t->exclusive_counter == 0) t->exclusivity = (byte)-1;
+			if (--t->exclusive_counter == 0) t->exclusivity = INVALID_PLAYER;
 
 		UpdateTownGrowRate(t);
 		UpdateTownAmounts(t);
@@ -1833,7 +1833,7 @@
 	_town_sort_dirty = true;
 }
 
-const TileTypeProcs _tile_type_town_procs = {
+extern const TileTypeProcs _tile_type_town_procs = {
 	DrawTile_Town,           /* draw_tile_proc */
 	GetSlopeZ_Town,          /* get_slope_z_proc */
 	ClearTile_Town,          /* clear_tile_proc */
@@ -1959,6 +1959,6 @@
 }
 
 
-const ChunkHandler _town_chunk_handlers[] = {
+extern const ChunkHandler _town_chunk_handlers[] = {
 	{ 'CITY', Save_TOWN, Load_TOWN, CH_ARRAY | CH_LAST},
 };
--- a/src/town_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/town_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -16,6 +16,7 @@
 #include "player.h"
 #include "network/network.h"
 #include "variables.h"
+#include "helpers.hpp"
 
 static const Widget _town_authority_widgets[] = {
 {   WWT_CLOSEBOX,   RESIZE_NONE,    13,     0,    10,     0,    13, STR_00C5,                 STR_018B_CLOSE_WINDOW},
@@ -409,7 +410,7 @@
 	uint n = 0;
 
 	/* Create array for sorting */
-	_town_sort = realloc((void*)_town_sort, (GetMaxTownIndex() + 1) * sizeof(_town_sort[0]));
+	ReallocT(&_town_sort, GetMaxTownIndex() + 1);
 	if (_town_sort == NULL) error("Could not allocate memory for the town-sorting-list");
 
 	FOR_ALL_TOWNS(t) _town_sort[n++] = t;
--- a/src/train_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/train_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -171,7 +171,7 @@
 		if (u->first == NULL) u->first = v;
 
 		// update the 'first engine'
-		u->u.rail.first_engine = (v == u) ? INVALID_ENGINE : first_engine;
+		u->u.rail.first_engine = (v == u) ? (EngineID)INVALID_ENGINE : first_engine;
 		u->u.rail.railtype = GetEngine(u->engine_type)->railtype;
 
 		if (IsTrainEngine(u)) first_engine = u->engine_type;
@@ -424,6 +424,8 @@
 			case RAILTYPE_MAGLEV:
 				force = power / 25;
 				break;
+
+			default: NOT_REACHED();
 		}
 	} else {
 		//"kickoff" acceleration
@@ -466,7 +468,7 @@
 	if (HASBIT(v->u.rail.flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
 
 	if (is_custom_sprite(img)) {
-		base = GetCustomVehicleSprite(v, direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(img));
+		base = GetCustomVehicleSprite(v, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(img)));
 		if (base != 0) return base;
 		img = orig_rail_vehicle_info[v->engine_type].image_index;
 	}
@@ -501,7 +503,7 @@
 		x += 15;
 		image = 0;
 		if (is_custom_sprite(img)) {
-			image = GetCustomVehicleIcon(engine, 2);
+			image = GetCustomVehicleIcon(engine, DIR_E);
 			if (image == 0) img = orig_rail_vehicle_info[engine].image_index;
 		}
 		if (image == 0) {
@@ -646,7 +648,7 @@
 			v->z_pos = GetSlopeZ(x,y);
 			v->owner = _current_player;
 			v->z_height = 6;
-			v->u.rail.track = 0x80;
+			v->u.rail.track = TRACK_BIT_SPECIAL;
 			v->vehstatus = VS_HIDDEN | VS_DEFPAL;
 
 			v->subtype = 0;
@@ -719,7 +721,7 @@
 	u->y_pos = v->y_pos;
 	u->z_pos = v->z_pos;
 	u->z_height = 6;
-	u->u.rail.track = 0x80;
+	u->u.rail.track = TRACK_BIT_SPECIAL;
 	u->vehstatus = v->vehstatus & ~VS_STOPPED;
 	u->subtype = 0;
 	SetMultiheaded(u);
@@ -807,7 +809,7 @@
 			v->y_pos = y;
 			v->z_pos = GetSlopeZ(x,y);
 			v->z_height = 6;
-			v->u.rail.track = 0x80;
+			v->u.rail.track = TRACK_BIT_SPECIAL;
 			v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
 			v->spritenum = rvi->image_index;
 			v->cargo_type = rvi->cargo_type;
@@ -903,7 +905,7 @@
 }
 
 /* Used to check if the train is inside the depot and verifying that the VS_STOPPED flag is set */
-inline int CheckTrainStoppedInDepot(const Vehicle *v)
+int CheckTrainStoppedInDepot(const Vehicle *v)
 {
 	return CheckTrainInDepot(v, true);
 }
@@ -1593,8 +1595,8 @@
 		}
 
 		/* swap variables */
-		swap_byte(&a->u.rail.track, &b->u.rail.track);
-		swap_byte(&a->direction, &b->direction);
+		SwapT(&a->u.rail.track, &b->u.rail.track);
+		SwapT(&a->direction, &b->direction);
 
 		/* toggle direction */
 		if (!(a->u.rail.track & 0x80)) a->direction = ReverseDir(a->direction);
@@ -2110,7 +2112,7 @@
 		if (IsTileDepotType(v->tile, TRANSPORT_RAIL) || IsTunnelTile(v->tile)) continue;
 
 		// No sparks for electric vehicles on nonelectrified tracks
-		if (!HasPowerOnRail(v->u.rail.railtype, GetTileRailType(v->tile, GetVehicleTrackdir(v)))) continue;
+		if (!HasPowerOnRail(v->u.rail.railtype, GetTileRailType(v->tile, TrackdirToTrack(GetVehicleTrackdir(v))))) continue;
 
 		if (effect_type == 0) {
 			// Use default effect type for engine class.
@@ -2177,6 +2179,7 @@
 
 		case RAILTYPE_MONO: SndPlayVehicleFx(SND_47_MAGLEV_2, v); break;
 		case RAILTYPE_MAGLEV: SndPlayVehicleFx(SND_41_MAGLEV, v); break;
+		default: NOT_REACHED();
 	}
 }
 
@@ -2214,8 +2217,8 @@
 	InvalidateWindowClasses(WC_TRAINS_LIST);
 	TrainPlayLeaveStationSound(v);
 
-	v->u.rail.track = 1;
-	if (v->direction & 2) v->u.rail.track = 2;
+	v->u.rail.track = TRACK_BIT_X;
+	if (v->direction & 2) v->u.rail.track = TRACK_BIT_Y;
 
 	v->vehstatus &= ~VS_HIDDEN;
 	v->cur_speed = 0;
@@ -2236,10 +2239,10 @@
 	StationID station_index; // station index we're heading for
 	uint best_bird_dist;
 	uint best_track_dist;
-	byte best_track;
+	TrackdirByte best_track;
 } TrainTrackFollowerData;
 
-static bool NtpCallbFindStation(TileIndex tile, TrainTrackFollowerData *ttfd, int track, uint length)
+static bool NtpCallbFindStation(TileIndex tile, TrainTrackFollowerData *ttfd, Trackdir track, uint length)
 {
 	// heading for nowhere?
 	if (ttfd->dest_coords == 0) return false;
@@ -2308,10 +2311,10 @@
 static const byte _pick_track_table[6] = {1, 3, 2, 2, 0, 0};
 
 /* choose a track */
-static byte ChooseTrainTrack(Vehicle* v, TileIndex tile, DiagDirection enterdir, TrackdirBits trackdirbits)
+static Track ChooseTrainTrack(Vehicle* v, TileIndex tile, DiagDirection enterdir, TrackBits tracks)
 {
 	TrainTrackFollowerData fd;
-	uint best_track;
+	Track best_track;
 	// pathfinders are able to tell that route was only 'guessed'
 	bool path_not_found = false;
 
@@ -2319,17 +2322,17 @@
 	TIC()
 #endif
 
-	assert((trackdirbits & ~0x3F) == 0);
+	assert((tracks & ~0x3F) == 0);
 
 	/* quick return in case only one possible track is available */
-	if (KILL_FIRST_BIT(trackdirbits) == 0) return FIND_FIRST_BIT(trackdirbits);
+	if (KILL_FIRST_BIT(tracks) == 0) return FindFirstTrack(tracks);
 
 	if (_patches.yapf.rail_use_yapf) {
-		Trackdir trackdir = YapfChooseRailTrack(v, tile, enterdir, trackdirbits, &path_not_found);
+		Trackdir trackdir = YapfChooseRailTrack(v, tile, enterdir, tracks, &path_not_found);
 		if (trackdir != INVALID_TRACKDIR) {
 			best_track = TrackdirToTrack(trackdir);
 		} else {
-			best_track = FIND_FIRST_BIT(TrackdirBitsToTrackBits(trackdirbits));
+			best_track = FindFirstTrack(tracks);
 		}
 	} else if (_patches.new_pathfinding_all) { /* Use a new pathfinding for everything */
 		void* perf = NpfBeginInterval();
@@ -2350,7 +2353,7 @@
 			/* We are already at our target. Just do something */
 			//TODO: maybe display error?
 			//TODO: go straight ahead if possible?
-			best_track = FIND_FIRST_BIT(trackdirbits);
+			best_track = FindFirstTrack(tracks);
 		} else {
 			/* If ftd.best_bird_dist is 0, we found our target and ftd.best_trackdir contains
 			the direction we need to take to get there, if ftd.best_bird_dist is not 0,
@@ -2372,7 +2375,7 @@
 		/* New train pathfinding */
 		fd.best_bird_dist = (uint)-1;
 		fd.best_track_dist = (uint)-1;
-		fd.best_track = 0xFF;
+		fd.best_track = INVALID_TRACKDIR;
 
 		NewTrainPathfind(tile - TileOffsByDiagDir(enterdir), v->dest_tile,
 			v->u.rail.compatible_railtypes, enterdir, (NTPEnumProc*)NtpCallbFindStation, &fd);
@@ -2382,9 +2385,9 @@
 
 		if (fd.best_track == 0xff) {
 			// blaha
-			best_track = FIND_FIRST_BIT(trackdirbits);
+			best_track = FindFirstTrack(tracks);
 		} else {
-			best_track = fd.best_track & 7;
+			best_track = TrackdirToTrack(fd.best_track);
 		}
 
 		time = NpfEndInterval(perf);
@@ -2451,7 +2454,7 @@
 	} else if (_patches.new_pathfinding_all) { /* Use a new pathfinding for everything */
 		NPFFindStationOrTileData fstd;
 		NPFFoundTargetData ftd;
-		byte trackdir, trackdir_rev;
+		Trackdir trackdir, trackdir_rev;
 		Vehicle* last = GetLastVehicleInChain(v);
 
 		NPFFillWithOrderData(&fstd, v);
@@ -2477,7 +2480,7 @@
 			fd.best_bird_dist = (uint)-1;
 			fd.best_track_dist = (uint)-1;
 
-			NewTrainPathfind(v->tile, v->dest_tile, v->u.rail.compatible_railtypes, reverse ^ i, (NTPEnumProc*)NtpCallbFindStation, &fd);
+			NewTrainPathfind(v->tile, v->dest_tile, v->u.rail.compatible_railtypes, (DiagDirection)(reverse ^ i), (NTPEnumProc*)NtpCallbFindStation, &fd);
 
 			if (best_track != -1) {
 				if (best_bird_dist != 0) {
@@ -2769,8 +2772,8 @@
 }
 
 static const Direction _new_vehicle_direction_table[11] = {
-	DIR_N , DIR_NW, DIR_W , 0,
-	DIR_NE, DIR_N , DIR_SW, 0,
+	DIR_N , DIR_NW, DIR_W , INVALID_DIR,
+	DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
 	DIR_E , DIR_SE, DIR_S
 };
 
@@ -2886,7 +2889,7 @@
 }
 
 static const DiagDirection _otherside_signal_directions[] = {
-	DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_SE, 0, 0,
+	DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_SE, INVALID_DIAGDIR, INVALID_DIAGDIR,
 	DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NE
 };
 
@@ -2907,7 +2910,7 @@
 
 static void *FindTrainCollideEnum(Vehicle *v, void *data)
 {
-	const TrainCollideChecker* tcc = data;
+	const TrainCollideChecker* tcc = (TrainCollideChecker*)data;
 
 	if (v != tcc->v &&
 			v != tcc->v_skip &&
@@ -2969,7 +2972,7 @@
 	tcc.v_skip = v->next;
 
 	/* find colliding vehicle */
-	realcoll = VehicleFromPos(TileVirtXY(v->x_pos, v->y_pos), &tcc, FindTrainCollideEnum);
+	realcoll = (Vehicle*)VehicleFromPos(TileVirtXY(v->x_pos, v->y_pos), &tcc, FindTrainCollideEnum);
 	if (realcoll == NULL) return;
 
 	coll = GetFirstVehicleInChain(realcoll);
@@ -3006,7 +3009,7 @@
 
 static void *CheckVehicleAtSignal(Vehicle *v, void *data)
 {
-	const VehicleAtSignalData* vasd = data;
+	const VehicleAtSignalData* vasd = (VehicleAtSignalData*)data;
 
 	if (v->type == VEH_Train && IsFrontEngine(v) && v->tile == vasd->tile) {
 		DirDiff diff = ChangeDirDiff(DirDifference(v->direction, vasd->direction), DIRDIFF_90RIGHT);
@@ -3021,12 +3024,12 @@
 	Vehicle *prev;
 	GetNewVehiclePosResult gp;
 	uint32 r, tracks,ts;
-	int i;
+	Trackdir i;
 	DiagDirection enterdir;
 	Direction dir;
 	Direction newdir;
 	Direction chosen_dir;
-	byte chosen_track;
+	TrackBits chosen_track;
 	byte old_z;
 
 	/* For every vehicle after and including the given vehicle */
@@ -3103,7 +3106,7 @@
 		}
 		if (entering_new_tile && !in_tunnel_or_bridge) {
 			/* A new tile is about to be entered. */
-			byte bits;
+			TrackBits bits;
 
 			/* Get the status of the tracks in the new tile and mask
 			 * away the bits that aren't reachable. */
@@ -3113,14 +3116,14 @@
 			 * Now, the lower byte contains the track status, and the byte at bit 16 contains
 			 * the signal status. */
 			tracks = ts | (ts >> 8);
-			bits = tracks & 0xFF;
+			bits = (TrackBits)(tracks & TRACK_BIT_MASK);
 			if ((_patches.new_pathfinding_all || _patches.yapf.rail_use_yapf) && _patches.forbid_90_deg && prev == NULL) {
 				/* We allow wagons to make 90 deg turns, because forbid_90_deg
 				 * can be switched on halfway a turn */
-				bits &= ~TrackCrossesTracks(FIND_FIRST_BIT(v->u.rail.track));
+				bits &= ~TrackCrossesTracks(FindFirstTrack(v->u.rail.track));
 			}
 
-			if (bits == 0) {
+			if (bits == TRACK_BIT_NONE) {
 				DEBUG(misc, 2, "%x == 0", bits);
 				goto invalid_rail;
 			}
@@ -3144,7 +3147,7 @@
 				static byte _matching_tracks[8] = {0x30, 1, 0xC, 2, 0x30, 1, 0xC, 2};
 
 				/* The wagon is active, simply follow the prev vehicle. */
-				chosen_track = (byte)(_matching_tracks[GetDirectionToVehicle(prev, gp.x, gp.y)] & bits);
+				chosen_track = (TrackBits)(_matching_tracks[GetDirectionToVehicle(prev, gp.x, gp.y)] & bits);
 			}
 
 			/* make sure chosen track is a valid track */
@@ -3155,7 +3158,7 @@
 				const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
 				gp.x = (gp.x & ~0xF) | b[0];
 				gp.y = (gp.y & ~0xF) | b[1];
-				chosen_dir = b[2];
+				chosen_dir = (Direction)b[2];
 			}
 
 			/* Call the landscape function and tell it that the vehicle entered the tile */
@@ -3175,7 +3178,7 @@
 			if (!(r&0x4)) {
 				v->tile = gp.new_tile;
 
-				if (GetTileRailType(gp.new_tile, chosen_track) != GetTileRailType(gp.old_tile, v->u.rail.track)) {
+				if (GetTileRailType(gp.new_tile, FindFirstTrack(chosen_track)) != GetTileRailType(gp.old_tile, FindFirstTrack(v->u.rail.track))) {
 					TrainPowerChanged(GetFirstVehicleInChain(v));
 				}
 
@@ -3222,7 +3225,7 @@
 	/* We're in front of a red signal ?? */
 		/* find the first set bit in ts. need to do it in 2 steps, since
 		 * FIND_FIRST_BIT only handles 6 bits at a time. */
-		i = FindFirstBit2x64(ts);
+		i = FindFirstTrackdir((TrackdirBits)(uint16)ts);
 
 		if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
 			v->cur_speed = 0;
@@ -3472,6 +3475,7 @@
 		case DIR_SE: x = y;            break;
 		case DIR_S : x = x + y - 8;    break;
 		case DIR_W : x = ~y + x + 8;   break;
+		default: break;
 	}
 
 	if (GB(ts, 0, 16) != 0) {
--- a/src/tree_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/tree_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -28,20 +28,20 @@
 {
 	switch (_opt.landscape) {
 		case LT_NORMAL:
-			return seed * TREE_COUNT_TEMPERATE / 256 + TREE_TEMPERATE;
+			return (TreeType)(seed * TREE_COUNT_TEMPERATE / 256 + TREE_TEMPERATE);
 
 		case LT_HILLY:
-			return seed * TREE_COUNT_SUB_ARCTIC / 256 + TREE_SUB_ARCTIC;
+			return (TreeType)(seed * TREE_COUNT_SUB_ARCTIC / 256 + TREE_SUB_ARCTIC);
 
 		case LT_DESERT:
 			switch (GetTropicZone(tile)) {
-				case TROPICZONE_INVALID: return seed * TREE_COUNT_SUB_TROPICAL / 256 + TREE_SUB_TROPICAL;
-				case TROPICZONE_DESERT:  return (seed > 12) ? TREE_INVALID : TREE_CACTUS;
-				default:                 return seed * TREE_COUNT_RAINFOREST / 256 + TREE_RAINFOREST;
+				case TROPICZONE_INVALID: return (TreeType)(seed * TREE_COUNT_SUB_TROPICAL / 256 + TREE_SUB_TROPICAL);
+				case TROPICZONE_DESERT:  return (TreeType)((seed > 12) ? TREE_INVALID : TREE_CACTUS);
+				default:                 return (TreeType)(seed * TREE_COUNT_RAINFOREST / 256 + TREE_RAINFOREST);
 			}
 
 		default:
-			return seed * TREE_COUNT_TOYLAND / 256 + TREE_TOYLAND;
+			return (TreeType)(seed * TREE_COUNT_TOYLAND / 256 + TREE_TOYLAND);
 	}
 }
 
@@ -55,10 +55,10 @@
 		// above snowline?
 		if (_opt.landscape == LT_HILLY && GetTileZ(tile) > _opt.snow_line) {
 			SetTreeGroundDensity(tile, TREE_GROUND_SNOW_DESERT, 3);
-			SetTreeCounter(tile, GB(r, 24, 3));
+			SetTreeCounter(tile, (TreeGround)GB(r, 24, 3));
 		} else {
-			SetTreeGroundDensity(tile, GB(r, 28, 1), 0);
-			SetTreeCounter(tile, GB(r, 24, 4));
+			SetTreeGroundDensity(tile, (TreeGround)GB(r, 28, 1), 0);
+			SetTreeCounter(tile, (TreeGround)GB(r, 24, 4));
 		}
 	}
 }
@@ -116,7 +116,7 @@
 			continue;
 
 		/* Not too much height difference */
-		if (myabs(GetTileZ(cur_tile) - height) > 2) continue;
+		if (delta(GetTileZ(cur_tile), height) > 2) continue;
 
 		/* Place one tree and quit */
 		PlaceTree(cur_tile, r);
@@ -278,7 +278,7 @@
 								ChangeTownRating(t, RATING_TREE_UP_STEP, RATING_TREE_MAXIMUM);
 						}
 
-						treetype = p1;
+						treetype = (TreeType)p1;
 						if (treetype == TREE_INVALID) {
 							treetype = GetRandomTreeType(tile, GB(Random(), 24, 8));
 							if (treetype == TREE_INVALID) treetype = TREE_CACTUS;
@@ -408,7 +408,7 @@
 static uint GetSlopeZ_Trees(TileIndex tile, uint x, uint y)
 {
 	uint z;
-	uint tileh = GetTileSlope(tile, &z);
+	Slope tileh = GetTileSlope(tile, &z);
 
 	return z + GetPartialZ(x & 0xF, y & 0xF, tileh);
 }
@@ -654,7 +654,7 @@
 }
 
 
-const TileTypeProcs _tile_type_trees_procs = {
+extern const TileTypeProcs _tile_type_trees_procs = {
 	DrawTile_Trees,           /* draw_tile_proc */
 	GetSlopeZ_Trees,          /* get_slope_z_proc */
 	ClearTile_Trees,          /* clear_tile_proc */
--- a/src/tree_map.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/tree_map.h	Mon Jan 15 20:14:06 2007 +0000
@@ -35,14 +35,14 @@
 static inline TreeType GetTreeType(TileIndex t)
 {
 	assert(IsTileType(t, MP_TREES));
-	return _m[t].m3;
+	return (TreeType)_m[t].m3;
 }
 
 
 static inline TreeGround GetTreeGround(TileIndex t)
 {
 	assert(IsTileType(t, MP_TREES));
-	return GB(_m[t].m2, 4, 2);
+	return (TreeGround)GB(_m[t].m2, 4, 2);
 }
 
 
--- a/src/tunnel_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/tunnel_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -107,8 +107,8 @@
 
 	if (flags & DC_EXEC) {
 		if (GB(p1, 9, 1) == TRANSPORT_RAIL) {
-			MakeRailTunnel(start_tile, _current_player, direction,                 GB(p1, 0, 4));
-			MakeRailTunnel(end_tile,   _current_player, ReverseDiagDir(direction), GB(p1, 0, 4));
+			MakeRailTunnel(start_tile, _current_player, direction,                 (RailType)GB(p1, 0, 4));
+			MakeRailTunnel(end_tile,   _current_player, ReverseDiagDir(direction), (RailType)GB(p1, 0, 4));
 			UpdateSignalsOnSegment(start_tile, direction);
 			YapfNotifyTrackLayoutChange(start_tile, AxisToTrack(DiagDirToAxis(direction)));
 		} else {
@@ -399,7 +399,7 @@
 		dir = GetTunnelDirection(tile);
 		vdir = DirToDiagDir(v->direction);
 
-		if (v->u.rail.track != 0x40 && dir == vdir) {
+		if (v->u.rail.track != TRACK_BIT_WORMHOLE && dir == vdir) {
 			if (IsFrontEngine(v) && fc == _tunnel_fractcoord_1[dir]) {
 				if (!PlayVehicleSound(v, VSE_TUNNEL) && v->spritenum < 4) {
 					SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, v);
@@ -408,7 +408,7 @@
 			}
 			if (fc == _tunnel_fractcoord_2[dir]) {
 				v->tile = tile;
-				v->u.rail.track = 0x40;
+				v->u.rail.track = TRACK_BIT_WORMHOLE;
 				v->vehstatus |= VS_HIDDEN;
 				return 4;
 			}
@@ -417,7 +417,7 @@
 		if (dir == ReverseDiagDir(vdir) && fc == _tunnel_fractcoord_3[dir] && z == 0) {
 			/* We're at the tunnel exit ?? */
 			v->tile = tile;
-			v->u.rail.track = _exit_tunnel_track[dir];
+			v->u.rail.track = (TrackBits)_exit_tunnel_track[dir];
 			assert(v->u.rail.track);
 			v->vehstatus &= ~VS_HIDDEN;
 			return 4;
@@ -457,7 +457,7 @@
 }
 
 
-const TileTypeProcs _tile_type_tunnel_procs = {
+extern const TileTypeProcs _tile_type_tunnel_procs = {
 	DrawTile_Tunnel,           /* draw_tile_proc */
 	GetSlopeZ_Tunnel,          /* get_slope_z_proc */
 	ClearTile_Tunnel,          /* clear_tile_proc */
--- a/src/unix.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/unix.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -127,9 +127,9 @@
 }
 
 #ifdef WITH_COCOA
-void cocoaSetWorkingDirectory(void);
-void cocoaSetupAutoreleasePool(void);
-void cocoaReleaseAutoreleasePool(void);
+extern "C" void cocoaSetWorkingDirectory(void);
+extern "C" void cocoaSetupAutoreleasePool(void);
+extern "C" void cocoaReleaseAutoreleasePool(void);
 #endif
 
 int CDECL main(int argc, char* argv[])
@@ -169,10 +169,10 @@
 {
 	char *s;
 
-	_paths.game_data_dir = malloc(MAX_PATH);
+	MallocT(&_paths.game_data_dir, MAX_PATH);
 	ttd_strlcpy(_paths.game_data_dir, GAME_DATA_DIR, MAX_PATH);
 	#if defined SECOND_DATA_DIR
-	_paths.second_data_dir = malloc(MAX_PATH);
+	MallocT(&_paths.second_data_dir, MAX_PATH);
 	ttd_strlcpy(_paths.second_data_dir, SECOND_DATA_DIR, MAX_PATH);
 	#endif
 
@@ -190,7 +190,7 @@
 
 #else /* not defined(USE_HOMEDIR) */
 
-	_paths.personal_dir = malloc(MAX_PATH);
+	MallocT(&_paths.personal_dir, MAX_PATH);
 	ttd_strlcpy(_paths.personal_dir, PERSONAL_DIR, MAX_PATH);
 
 	// check if absolute or relative path
@@ -226,7 +226,7 @@
 
 #if defined CUSTOM_LANG_DIR
 	// sets the search path for lng files to the custom one
-	_paths.lang_dir = malloc( MAX_PATH );
+	MallocT(&_paths.lang_dir, MAX_PATH );
 	ttd_strlcpy( _paths.lang_dir, CUSTOM_LANG_DIR, MAX_PATH);
 #else
 	_paths.lang_dir = str_fmt("%slang/", _paths.game_data_dir);
--- a/src/unmovable_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/unmovable_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -74,7 +74,7 @@
  * @param p1 unused
  * @param p2 unused
  */
-extern int32 CheckFlatLandBelow(TileIndex tile, uint w, uint h, uint flags, uint invalid_dirs, int *);
+extern int32 CheckFlatLandBelow(TileIndex tile, uint w, uint h, uint flags, uint invalid_dirs, StationID* station);
 int32 CmdBuildCompanyHQ(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 {
 	Player *p = GetPlayer(_current_player);
@@ -183,7 +183,7 @@
 {
 	if (IsOwnedLand(tile)) {
 		uint z;
-		uint tileh = GetTileSlope(tile, &z);
+		Slope tileh = GetTileSlope(tile, &z);
 
 		return z + GetPartialZ(x & 0xF, y & 0xF, tileh);
 	} else {
@@ -397,7 +397,7 @@
 	}
 }
 
-const TileTypeProcs _tile_type_unmovable_procs = {
+extern const TileTypeProcs _tile_type_unmovable_procs = {
 	DrawTile_Unmovable,             /* draw_tile_proc */
 	GetSlopeZ_Unmovable,            /* get_slope_z_proc */
 	ClearTile_Unmovable,            /* clear_tile_proc */
--- a/src/unmovable_map.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/unmovable_map.h	Mon Jan 15 20:14:06 2007 +0000
@@ -26,7 +26,7 @@
 static inline UnmovableType GetUnmovableType(TileIndex t)
 {
 	assert(IsTileType(t, MP_UNMOVABLE));
-	return _m[t].m5;
+	return (UnmovableType)_m[t].m5;
 }
 
 
--- a/src/variables.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/variables.h	Mon Jan 15 20:14:06 2007 +0000
@@ -276,23 +276,15 @@
 VARDEF int _autosave_ctr;
 
 VARDEF byte _display_opt;
-VARDEF byte _pause;
 VARDEF int _caret_timer;
 VARDEF uint32 _news_display_opt;
 VARDEF bool _news_ticker_sound;
-VARDEF byte _game_mode;
 
 VARDEF StringID _error_message;
 VARDEF int32 _additional_cash_required;
 
 VARDEF uint32 _decode_parameters[20];
 
-VARDEF bool _ctrl_pressed;   // Is Ctrl pressed?
-VARDEF bool _shift_pressed;  // Is Shift pressed?
-VARDEF byte _dirkeys;        // 1 = left, 2 = up, 4 = right, 8 = down
-
-VARDEF bool _fullscreen;
-VARDEF bool _fast_forward;
 VARDEF bool _rightclick_emulate;
 
 // IN/OUT parameters to commands
@@ -311,7 +303,6 @@
 // Used when switching from the intro menu.
 VARDEF byte _switch_mode;
 VARDEF StringID _switch_mode_errorstr;
-VARDEF bool _exit_game;
 VARDEF SmallFiosItem _file_to_saveload;
 
 
@@ -406,7 +397,7 @@
 
 /* landscape.c */
 extern const byte _tileh_to_sprite[32];
-extern const byte _inclined_tileh[16];
+extern const Slope _inclined_tileh[16];
 
 extern const TileTypeProcs * const _tile_type_procs[16];
 
--- a/src/vehicle.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/vehicle.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -35,6 +35,7 @@
 #include "date.h"
 #include "newgrf_engine.h"
 #include "newgrf_sound.h"
+#include "helpers.hpp"
 
 #define INVALID_COORD (-0x8000)
 #define GEN_HASH(x, y) ((GB((y), 6, 6) << 6) + GB((x), 7, 6))
@@ -145,7 +146,7 @@
 
 static void *EnsureNoVehicleProcZ(Vehicle *v, void *data)
 {
-	const TileInfo *ti = data;
+	const TileInfo *ti = (const TileInfo*)data;
 
 	if (v->tile != ti->tile || v->type == VEH_Disaster) return NULL;
 	if (v->z_pos > ti->z) return NULL;
@@ -171,7 +172,7 @@
 	ti.tile = tile;
 	ti.z = z;
 
-	return VehicleFromPos(tile, &ti, EnsureNoVehicleProcZ);
+	return (Vehicle*)VehicleFromPos(tile, &ti, EnsureNoVehicleProcZ);
 }
 
 Vehicle *FindVehicleBetween(TileIndex from, TileIndex to, byte z)
@@ -643,7 +644,7 @@
 	// hotfix for desync problem:
 	//  for MP games invalidate the YAPF cache every tick to keep it exactly the same on the server and all clients
 	if (_networking) {
-		YapfNotifyTrackLayoutChange(0, 0);
+		YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK);
 	}
 #endif //ENABLE_NETWORK
 
@@ -1959,7 +1960,7 @@
 
 	if (v->cargo_type == new_cargo_type || CanRefitTo(engine_type, v->cargo_type)) {
 		if (VerifyAutoreplaceRefitForOrders(v, engine_type)) {
-			return v->cargo_type == new_cargo_type ? CT_NO_REFIT : v->cargo_type;
+			return v->cargo_type == new_cargo_type ? (CargoID)CT_NO_REFIT : v->cargo_type;
 		} else {
 			return CT_INVALID;
 		}
@@ -2258,7 +2259,7 @@
 static inline void ExtendVehicleListSize(const Vehicle ***engine_list, uint16 *engine_list_length, uint16 step_size)
 {
 	*engine_list_length = min(*engine_list_length + step_size, GetMaxVehicleIndex() + 1);
-	*engine_list = realloc((void*)*engine_list, (*engine_list_length) * sizeof((*engine_list)[0]));
+	ReallocT((Vehicle ***)/* NO & */engine_list, *engine_list_length);
 }
 
 /** Generates a list of vehicles inside a depot
@@ -2435,7 +2436,7 @@
 		 * We will still make it have room for 50 extra vehicles to prevent having
 		 * to move the whole array if just one vehicle is added later */
 		*length_of_array = n + 50;
-		*sort_list = realloc((void*)*sort_list, (*length_of_array) * sizeof((*sort_list)[0]));
+		ReallocT((Vehicle***)/* NO & */sort_list, (*length_of_array) * sizeof((*sort_list)[0]));
 	}
 
 	return n;
@@ -2460,7 +2461,7 @@
 	/* Send all the vehicles to a depot */
 	for (i = 0; i < n; i++) {
 		const Vehicle *v = sort_list[i];
-		int32 ret = DoCommand(v->tile, v->index, service | DEPOT_DONT_CANCEL, flags, CMD_SEND_TO_DEPOT(type));
+		int32 ret = DoCommand(v->tile, v->index, (service ? 1 : 0) | DEPOT_DONT_CANCEL, flags, CMD_SEND_TO_DEPOT(type));
 
 		/* Return 0 if DC_EXEC is not set this is a valid goto depot command)
 			* In this case we know that at least one vehicle can be sent to a depot
@@ -2505,7 +2506,7 @@
 
 		case VEH_Ship:
 			InvalidateWindowClasses(WC_SHIPS_LIST);
-			v->u.ship.state = 0x80;
+			v->u.ship.state = TRACK_BIT_SPECIAL;
 			RecalcShipStuff(v);
 			break;
 
@@ -2709,7 +2710,7 @@
 
 Trackdir GetVehicleTrackdir(const Vehicle* v)
 {
-	if (v->vehstatus & VS_CRASHED) return 0xFF;
+	if (v->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
 
 	switch (v->type) {
 		case VEH_Train:
@@ -2719,14 +2720,14 @@
 			if (v->u.rail.track == 0x40) /* train in tunnel, so just use his direction and assume a diagonal track */
 				return DiagdirToDiagTrackdir(DirToDiagDir(v->direction));
 
-			return TrackDirectionToTrackdir(FIND_FIRST_BIT(v->u.rail.track),v->direction);
+			return TrackDirectionToTrackdir(FindFirstTrack(v->u.rail.track), v->direction);
 
 		case VEH_Ship:
 			if (IsShipInDepot(v))
 				/* We'll assume the ship is facing outwards */
 				return DiagdirToDiagTrackdir(GetShipDepotDirection(v->tile));
 
-			return TrackDirectionToTrackdir(FIND_FIRST_BIT(v->u.ship.state),v->direction);
+			return TrackDirectionToTrackdir(FindFirstTrack(v->u.ship.state), v->direction);
 
 		case VEH_Road:
 			if (IsRoadVehInDepot(v)) /* We'll assume the road vehicle is facing outwards */
@@ -2736,13 +2737,13 @@
 				return DiagdirToDiagTrackdir(GetRoadStopDir(v->tile)); /* Road vehicle in a station */
 
 			/* If vehicle's state is a valid track direction (vehicle is not turning around) return it */
-			if ((v->u.road.state & 7) < 6) return v->u.road.state;
+			if ((v->u.road.state & 7) < 6) return (Trackdir)v->u.road.state;
 
 			/* Vehicle is turning around, get the direction from vehicle's direction */
 			return DiagdirToDiagTrackdir(DirToDiagDir(v->direction));
 
 		/* case VEH_Aircraft: case VEH_Special: case VEH_Disaster: */
-		default: return 0xFF;
+		default: return INVALID_TRACKDIR;
 	}
 }
 /* Return value has bit 0x2 set, when the vehicle enters a station. Then,
@@ -2780,7 +2781,7 @@
 	if (max > gmax) {
 		gmax = max;
 		free(cache);
-		cache = malloc((max + 1) * sizeof(*cache));
+		MallocT(&cache, max + 1);
 	}
 
 	// Clear the cache
@@ -2908,7 +2909,7 @@
 }
 
 // Save and load of vehicles
-const SaveLoad _common_veh_desc[] = {
+extern const SaveLoad _common_veh_desc[] = {
 	    SLE_VAR(Vehicle, subtype,              SLE_UINT8),
 
 	    SLE_REF(Vehicle, next,                 REF_VEHICLE_OLD),
@@ -3174,7 +3175,7 @@
 	// Write the vehicles
 	FOR_ALL_VEHICLES(v) {
 		SlSetArrayIndex(v->index);
-		SlObject(v, _veh_descs[v->type - 0x10]);
+		SlObject(v, (SaveLoad*)_veh_descs[v->type - 0x10]);
 	}
 }
 
@@ -3191,7 +3192,7 @@
 			error("Vehicles: failed loading savegame: too many vehicles");
 
 		v = GetVehicle(index);
-		SlObject(v, _veh_descs[SlReadByte()]);
+		SlObject(v, (SaveLoad*)_veh_descs[SlReadByte()]);
 
 		/* Old savegames used 'last_station_visited = 0xFF' */
 		if (CheckSavegameVersion(5) && v->last_station_visited == 0xFF)
@@ -3201,7 +3202,7 @@
 			/* Convert the current_order.type (which is a mix of type and flags, because
 			 *  in those versions, they both were 4 bits big) to type and flags */
 			v->current_order.flags = (v->current_order.type & 0xF0) >> 4;
-			v->current_order.type  =  v->current_order.type & 0x0F;
+			v->current_order.type.m_val &= 0x0F;
 		}
 	}
 
@@ -3223,6 +3224,6 @@
 	}
 }
 
-const ChunkHandler _veh_chunk_handlers[] = {
+extern const ChunkHandler _veh_chunk_handlers[] = {
 	{ 'VEHS', Save_VEHS, Load_VEHS, CH_SPARSE_ARRAY | CH_LAST},
 };
--- a/src/vehicle.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/vehicle.h	Mon Jan 15 20:14:06 2007 +0000
@@ -76,9 +76,9 @@
 	// 0xffff == not in train
 	EngineID first_engine;
 
-	byte track;
+	TrackBitsByte track;
 	byte force_proceed;
-	byte railtype;
+	RailTypeByte railtype;
 	RailTypeMask compatible_railtypes;
 
 	byte flags;
@@ -138,7 +138,7 @@
 } VehicleDisaster;
 
 typedef struct VehicleShip {
-	byte state;
+	TrackBitsByte state;
 } VehicleShip;
 
 
@@ -155,7 +155,7 @@
 	StringID string_id;      // Displayed string
 
 	UnitID unitnumber;       // unit number, for display purposes only
-	PlayerID owner;          // which player owns the vehicle?
+	PlayerByte owner;          // which player owns the vehicle?
 
 	TileIndex tile;          // Current tile index
 	TileIndex dest_tile;     // Heading for this tile
@@ -163,7 +163,7 @@
 	int32 x_pos;             // coordinates
 	int32 y_pos;
 	byte z_pos;
-	byte direction;          // facing
+	DirectionByte direction; // facing
 
 	byte spritenum;          // currently displayed sprite index
 	                         // 0xfd == custom sprite, 0xfe == custom second head sprite
@@ -455,9 +455,7 @@
 VARDEF VehicleID _new_vehicle_id;
 VARDEF uint16 _returned_refit_capacity;
 
-enum {
-	INVALID_VEHICLE = 0xFFFF,
-};
+static const VehicleID INVALID_VEHICLE = 0xFFFF;
 
 /**
  * Get the colour map for an engine. This used for unbuilt engines in the user interface.
--- a/src/vehicle_gui.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/vehicle_gui.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -27,6 +27,7 @@
 #include "aircraft.h"
 #include "roadveh.h"
 #include "depot.h"
+#include "helpers.hpp"
 
 typedef struct Sorting {
 	Listing aircraft;
@@ -153,7 +154,7 @@
 {
 	if (!(vl->l.flags & VL_RESORT)) return;
 
-	_internal_sort_order = vl->l.flags & VL_DESC;
+	_internal_sort_order = (vl->l.flags & VL_DESC) != 0;
 	qsort((void*)vl->sort_list, vl->l.list_length, sizeof(vl->sort_list[0]),
 		_vehicle_sorter[vl->l.sort_type]);
 
@@ -206,8 +207,10 @@
 static RefitList *BuildRefitList(const Vehicle *v)
 {
 	uint max_lines = 256;
-	RefitOption *refit = calloc(max_lines, sizeof(*refit));
-	RefitList *list = calloc(1, sizeof(*list));
+	RefitOption *refit;
+	CallocT(&refit, max_lines);
+	RefitList *list;
+	CallocT(&list, 1);
 	Vehicle *u = (Vehicle*)v;
 	uint num_lines = 0;
 	uint i;
@@ -855,12 +858,12 @@
 			if (selected_id[0] != INVALID_ENGINE) {
 				const ShipVehicleInfo* svi = ShipVehInfo(selected_id[0]);
 				CargoID cargo = svi->cargo_type;
-				byte refittable = svi->refittable;
+				bool refittable = svi->refittable;
 
 				for (i = SHIP_ENGINES_INDEX; i < SHIP_ENGINES_INDEX + NUM_SHIP_ENGINES; i++) {
 					if (HASBIT(GetEngine(i)->player_avail, _local_player) && (
 								ShipVehInfo(i)->cargo_type == cargo ||
-								ShipVehInfo(i)->refittable & refittable
+								ShipVehInfo(i)->refittable && refittable
 							)) {
 						if (sel[1] == count2) selected_id[1] = i;
 						count2++;
@@ -1205,7 +1208,7 @@
 		}
 
 		case WE_DROPDOWN_SELECT: /* we have selected a dropdown item in the list */
-			_railtype_selected_in_replace_gui = e->we.dropdown.index;
+			_railtype_selected_in_replace_gui = (RailType)e->we.dropdown.index;
 			/* Reset scrollbar positions */
 			w->vscroll.pos  = 0;
 			w->vscroll2.pos = 0;
@@ -1437,7 +1440,7 @@
 {
 	vehiclelist_d *vl = &WP(w, vehiclelist_d);
 	uint16 window_type = w->window_number & VLW_MASK;
-	PlayerID player = GB(w->window_number, 0, 8);
+	PlayerID player = (PlayerID)GB(w->window_number, 0, 8);
 
 	vl->vehicle_type = GB(w->window_number, 11, 5);
 	vl->length_of_sort_list = 0;
@@ -1550,7 +1553,7 @@
 		default: NOT_REACHED(); break;
 	}
 
-	vl->l.flags = VL_REBUILD | (vl->_sorting->order << (VL_DESC - 1));
+	vl->l.flags = VL_REBUILD | (vl->_sorting->order ? VL_DESC : VL_NONE);
 	vl->l.sort_type = vl->_sorting->criteria;
 	vl->sort_list = NULL;
 	vl->l.resort_timer = DAY_TICKS * PERIODIC_RESORT_DAYS;	// Set up resort timer
--- a/src/video/cocoa_v.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/video/cocoa_v.h	Mon Jan 15 20:14:06 2007 +0000
@@ -5,6 +5,14 @@
 
 #include "../hal.h"
 
+#ifdef __cplusplus
+extern "C" {
+#endif //__cplusplus
+
 extern const HalVideoDriver _cocoa_video_driver;
 
+#ifdef __cplusplus
+} // extern "C"
+#endif //__cplusplus
+
 #endif
--- a/src/video/cocoa_v.m	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/video/cocoa_v.m	Mon Jan 15 20:14:06 2007 +0000
@@ -46,18 +46,11 @@
 # endif
 #endif
 
+
 #include "../stdafx.h"
-#include "../openttd.h"
 #include "../debug.h"
-#include "../functions.h"
-#include "../gfx.h"
 #include "../macros.h"
-#include "../sdl.h"
-#include "../window.h"
-#include "../network/network.h"
-#include "../variables.h"
 #include "../os/macosx/splash.h"
-
 #include "cocoa_v.h"
 #include "cocoa_keys.h"
 
@@ -65,6 +58,7 @@
 #undef Rect
 
 
+
 /* Subclass of NSWindow to fix genie effect and support resize events  */
 @interface OTTD_QuartzWindow : NSWindow
 - (void)miniaturize:(id)sender;
@@ -162,7 +156,7 @@
 	NSQuickDrawView *qdview;
 
 #define MAX_DIRTY_RECTS 100
-	OTTDRect dirty_rects[MAX_DIRTY_RECTS];
+	Rect dirty_rects[MAX_DIRTY_RECTS];
 	int num_dirty_rects;
 
 	uint16 palette16[256];
--- a/src/video/dedicated_v.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/video/dedicated_v.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -277,7 +277,7 @@
 			next_tick = cur_ticks + 30;
 
 			GameLoop();
-			_screen.dst_ptr = _dedicated_video_mem;
+			_screen.dst_ptr = (Pixel*)_dedicated_video_mem;
 			UpdateWindows();
 		}
 		CSleep(1);
--- a/src/video/null_v.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/video/null_v.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -27,7 +27,7 @@
 
 	for (i = 0; i < 1000; i++) {
 		GameLoop();
-		_screen.dst_ptr = _null_video_mem;
+		_screen.dst_ptr = (Pixel*)_null_video_mem;
 		UpdateWindows();
 	}
 }
--- a/src/video/sdl_v.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/video/sdl_v.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -469,7 +469,7 @@
 				(keys[SDLK_DOWN]  ? 8 : 0);
 			GameLoop();
 
-			_screen.dst_ptr = _sdl_screen->pixels;
+			_screen.dst_ptr = (Pixel*)_sdl_screen->pixels;
 			UpdateWindows();
 			if (++pal_tick > 4) {
 				CheckPaletteAnim();
@@ -478,7 +478,7 @@
 			DrawSurfaceToScreen();
 		} else {
 			SDL_CALL SDL_Delay(1);
-			_screen.dst_ptr = _sdl_screen->pixels;
+			_screen.dst_ptr = (Pixel*)_sdl_screen->pixels;
 			DrawTextMessage();
 			DrawMouseCursor();
 			DrawSurfaceToScreen();
--- a/src/video/win32_v.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/video/win32_v.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -42,7 +42,7 @@
 	LOGPALETTE *pal;
 	uint i;
 
-	pal = alloca(sizeof(LOGPALETTE) + (256-1) * sizeof(PALETTEENTRY));
+	pal = (LOGPALETTE*)alloca(sizeof(LOGPALETTE) + (256-1) * sizeof(PALETTEENTRY));
 
 	pal->palVersion = 0x300;
 	pal->palNumEntries = 256;
@@ -169,7 +169,7 @@
 	dc = GetDC(_wnd.main_wnd);
 	dc2 = CreateCompatibleDC(dc);
 
-	old_bmp = SelectObject(dc2, _wnd.dib_sect);
+	old_bmp = (HBITMAP)SelectObject(dc2, _wnd.dib_sect);
 	old_palette = SelectPalette(dc, _wnd.gdi_palette, FALSE);
 	BitBlt(dc, 0, 0, _wnd.width, _wnd.height, dc2, 0, 0, SRCCOPY);
 	SelectPalette(dc, old_palette, TRUE);
@@ -222,7 +222,7 @@
 			BeginPaint(hwnd, &ps);
 			dc = ps.hdc;
 			dc2 = CreateCompatibleDC(dc);
-			old_bmp = SelectObject(dc2, _wnd.dib_sect);
+			old_bmp = (HBITMAP)SelectObject(dc2, _wnd.dib_sect);
 			old_palette = SelectPalette(dc, _wnd.gdi_palette, FALSE);
 
 			if (_pal_last_dirty != -1) {
@@ -358,7 +358,7 @@
 			GetKeyboardState(ks);
 			if (ToUnicode(wParam, 0, ks, &w, 1, 0) != 1) {
 				/* On win9x ToUnicode always fails, so fall back to ToAscii */
-				if (ToAscii(wParam, 0, ks, &w, 0) != 1) w = 0; // no translation was possible
+				if (ToAscii(wParam, 0, ks, (LPWORD)&w, 0) != 1) w = 0; // no translation was possible
 			}
 
 			pressed_key = w | MapWindowsKey(wParam) << 16;
@@ -496,7 +496,7 @@
 		}
 
 		case WM_ACTIVATEAPP:
-			_wnd.has_focus = (bool)wParam;
+			_wnd.has_focus = (wParam != 0);
 			break;
 	}
 	return DefWindowProc(hwnd, msg, wParam, lParam);
@@ -622,13 +622,13 @@
 		_wnd.alloced_bits = NULL;
 	}
 
-	bi = alloca(sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD)*256);
+	bi = (BITMAPINFO*)alloca(sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD)*256);
 	memset(bi, 0, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD)*256);
 	bi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
 
 	if (_wnd.double_size) {
 		w = ALIGN(w, 4);
-		_wnd.alloced_bits = _wnd.buffer_bits = malloc(w * h);
+		_wnd.alloced_bits = _wnd.buffer_bits = (Pixel*)malloc(w * h);
 		w *= 2;
 		h *= 2;
 	}
--- a/src/viewport.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/viewport.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -680,9 +680,7 @@
 				side = 0;
 			} else {
 				TileIndex start = TileVirtXY(_thd.selstart.x, _thd.selstart.y);
-				int diffx = myabs(TileX(start) - TileX(ti->tile));
-				int diffy = myabs(TileY(start) - TileY(ti->tile));
-				side = myabs(diffx - diffy);
+				side = delta(delta(TileX(start), TileX(ti->tile)), delta(TileY(start), TileY(ti->tile)));
 			}
 
 			image = SPR_AUTORAIL_BASE + _AutorailTilehSprite[ti->tileh][_AutorailType[dir][side]];
@@ -838,7 +836,7 @@
 {
 	StringSpriteToDraw *sstd;
 
-	sstd = AddStringToDraw(st->sign.left + 1, st->sign.top + 1, str, st->index, st->facilities);
+	sstd = (StringSpriteToDraw*)AddStringToDraw(st->sign.left + 1, st->sign.top + 1, str, st->index, st->facilities);
 	if (sstd != NULL) {
 		sstd->color = (st->owner == OWNER_NONE || st->facilities == 0) ? 0xE : _player_colors[st->owner];
 		sstd->width = width;
@@ -905,7 +903,7 @@
 {
 	StringSpriteToDraw *sstd;
 
-	sstd = AddStringToDraw(si->sign.left + 1, si->sign.top + 1, str, si->str, 0);
+	sstd = (StringSpriteToDraw*)AddStringToDraw(si->sign.left + 1, si->sign.top + 1, str, si->str, 0);
 	if (sstd != NULL) {
 		sstd->color = (si->owner == OWNER_NONE) ? 14 : _player_colors[si->owner];
 		sstd->width = width;
@@ -972,7 +970,7 @@
 {
 	StringSpriteToDraw *sstd;
 
-	sstd = AddStringToDraw(wp->sign.left + 1, wp->sign.top + 1, str, wp->index, 0);
+	sstd = (StringSpriteToDraw*)AddStringToDraw(wp->sign.left + 1, wp->sign.top + 1, str, wp->index, 0);
 	if (sstd != NULL) {
 		sstd->color = (wp->deleted ? 0xE : 11);
 		sstd->width = width;
@@ -1175,7 +1173,7 @@
 			if (!(_display_opt & DO_TRANS_SIGNS) || ss->string == STR_2806)
 				DrawFrameRect(
 					x, y, x + w, bottom, ss->color,
-					(_display_opt & DO_TRANS_BUILDINGS) ? FR_TRANSPARENT : 0
+					(_display_opt & DO_TRANS_BUILDINGS) ? FR_TRANSPARENT : FR_NONE
 				);
 		}
 
@@ -2318,8 +2316,8 @@
 			int limit = (_thd.sizelimit - 1) * TILE_SIZE;
 			x = sx + clamp(x - sx, -limit, limit);
 			y = sy + clamp(y - sy, -limit, limit);
-			/* Fallthrough */
-		case VPM_X_AND_Y: /* drag an X by Y area */
+			} /* Fallthrough */
+		case VPM_X_AND_Y: { /* drag an X by Y area */
 			if (_patches.measure_tooltip) {
 				static const StringID measure_strings_area[] = {
 					STR_NULL, STR_NULL, STR_MEASURE_AREA, STR_MEASURE_AREA_HEIGHTDIFF
@@ -2327,8 +2325,8 @@
 
 				TileIndex t0 = TileVirtXY(sx, sy);
 				TileIndex t1 = TileVirtXY(x, y);
-				uint dx = abs(TileX(t0) - TileX(t1)) + 1;
-				uint dy = abs(TileY(t0) - TileY(t1)) + 1;
+				uint dx = delta(TileX(t0), TileX(t1)) + 1;
+				uint dy = delta(TileY(t0), TileY(t1)) + 1;
 				byte index = 0;
 				uint params[3];
 
--- a/src/viewport.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/viewport.h	Mon Jan 15 20:14:06 2007 +0000
@@ -139,7 +139,7 @@
 
 
 // common button handler
-bool HandlePlacePushButton(Window *w, int widget, uint32 cursor, int mode, PlaceProc *placeproc);
+bool HandlePlacePushButton(Window *w, int widget, CursorID cursor, int mode, PlaceProc *placeproc);
 
 VARDEF Point _tile_fract_coords;
 
--- a/src/water_cmd.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/water_cmd.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -83,8 +83,8 @@
 		depot->xy = tile;
 		depot->town_index = ClosestTownFromTile(tile, (uint)-1)->index;
 
-		MakeShipDepot(tile,_current_player, DEPOT_NORTH, p1);
-		MakeShipDepot(tile2,_current_player, DEPOT_SOUTH, p1);
+		MakeShipDepot(tile, _current_player, DEPOT_NORTH, (Axis)p1);
+		MakeShipDepot(tile2, _current_player, DEPOT_SOUTH, (Axis)p1);
 		MarkTileDirtyByTile(tile);
 		MarkTileDirtyByTile(tile2);
 	}
@@ -471,7 +471,7 @@
 static uint GetSlopeZ_Water(TileIndex tile, uint x, uint y)
 {
 	uint z;
-	uint tileh = GetTileSlope(tile, &z);
+	Slope tileh = GetTileSlope(tile, &z);
 
 	return z + GetPartialZ(x & 0xF, y & 0xF, tileh);
 }
@@ -673,7 +673,7 @@
 
 	switch (GetWaterTileType(tile)) {
 		case WATER_CLEAR: ts = TRACK_BIT_ALL; break;
-		case WATER_COAST: ts = coast_tracks[GetTileSlope(tile, NULL) & 0xF]; break;
+		case WATER_COAST: ts = (TrackBits)coast_tracks[GetTileSlope(tile, NULL) & 0xF]; break;
 		case WATER_LOCK:  ts = AxisToTrackBits(DiagDirToAxis(GetLockDirection(tile))); break;
 		case WATER_DEPOT: ts = AxisToTrackBits(GetShipDepotAxis(tile)); break;
 		default: return 0;
@@ -715,7 +715,7 @@
 }
 
 
-const TileTypeProcs _tile_type_water_procs = {
+extern const TileTypeProcs _tile_type_water_procs = {
 	DrawTile_Water,           /* draw_tile_proc */
 	GetSlopeZ_Water,          /* get_slope_z_proc */
 	ClearTile_Water,          /* clear_tile_proc */
--- a/src/waypoint.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/waypoint.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -437,6 +437,6 @@
 	}
 }
 
-const ChunkHandler _waypoint_chunk_handlers[] = {
+extern const ChunkHandler _waypoint_chunk_handlers[] = {
 	{ 'CHKP', Save_WAYP, Load_WAYP, CH_ARRAY | CH_LAST},
 };
--- a/src/widget.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/widget.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -206,7 +206,7 @@
 		case WWT_IMGBTN_2: {
 			int img = wi->data;
 			assert(img != 0);
-			DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0);
+			DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE);
 
 			/* show different image when clicked for WWT_IMGBTN_2 */
 			if ((wi->type & WWT_MASK) == WWT_IMGBTN_2 && clicked) img++;
@@ -216,13 +216,13 @@
 
 		case WWT_PANEL: {
 			assert(wi->data == 0);
-			DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0);
+			DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE);
 			goto draw_default;
 		}
 
 		case WWT_TEXTBTN:
 		case WWT_TEXTBTN_2: {
-			DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0);
+			DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE);
 			}
 		/* fall through */
 
@@ -248,7 +248,7 @@
 			int x, amt1, amt2;
 			int color;
 
-			DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0);
+			DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE);
 
 			c = GB(wi->data, 0, 8);
 			amt1 = (wi->right - wi->left + 1) / c;
@@ -296,11 +296,11 @@
 
 			// draw up/down buttons
 			clicked = ((w->flags4 & (WF_SCROLL_UP | WF_HSCROLL | WF_SCROLL2)) == WF_SCROLL_UP);
-			DrawFrameRect(r.left, r.top, r.right, r.top + 9, wi->color, (clicked) ? FR_LOWERED : 0);
+			DrawFrameRect(r.left, r.top, r.right, r.top + 9, wi->color, (clicked) ? FR_LOWERED : FR_NONE);
 			DoDrawString(UPARROW, r.left + 2 + clicked, r.top + clicked, 0x10);
 
 			clicked = (((w->flags4 & (WF_SCROLL_DOWN | WF_HSCROLL | WF_SCROLL2)) == WF_SCROLL_DOWN));
-			DrawFrameRect(r.left, r.bottom - 9, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0);
+			DrawFrameRect(r.left, r.bottom - 9, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE);
 			DoDrawString(DOWNARROW, r.left + 2 + clicked, r.bottom - 9 + clicked, 0x10);
 
 			c1 = _colour_gradient[wi->color&0xF][3];
@@ -317,7 +317,7 @@
 			GfxFillRect(r.left+8, r.top+10, r.left+8, r.bottom-10, c2);
 
 			pt = HandleScrollbarHittest(&w->vscroll, r.top, r.bottom);
-			DrawFrameRect(r.left, pt.x, r.right, pt.y, wi->color, (w->flags4 & (WF_SCROLL_MIDDLE | WF_HSCROLL | WF_SCROLL2)) == WF_SCROLL_MIDDLE ? FR_LOWERED : 0);
+			DrawFrameRect(r.left, pt.x, r.right, pt.y, wi->color, (w->flags4 & (WF_SCROLL_MIDDLE | WF_HSCROLL | WF_SCROLL2)) == WF_SCROLL_MIDDLE ? FR_LOWERED : FR_NONE);
 			break;
 		}
 		case WWT_SCROLL2BAR: {
@@ -328,11 +328,11 @@
 
 			// draw up/down buttons
 			clicked = ((w->flags4 & (WF_SCROLL_UP | WF_HSCROLL | WF_SCROLL2)) == (WF_SCROLL_UP | WF_SCROLL2));
-			DrawFrameRect(r.left, r.top, r.right, r.top + 9, wi->color,  (clicked) ? FR_LOWERED : 0);
+			DrawFrameRect(r.left, r.top, r.right, r.top + 9, wi->color,  (clicked) ? FR_LOWERED : FR_NONE);
 			DoDrawString(UPARROW, r.left + 2 + clicked, r.top + clicked, 0x10);
 
 			clicked = ((w->flags4 & (WF_SCROLL_DOWN | WF_HSCROLL | WF_SCROLL2)) == (WF_SCROLL_DOWN | WF_SCROLL2));
-			DrawFrameRect(r.left, r.bottom - 9, r.right, r.bottom, wi->color,  (clicked) ? FR_LOWERED : 0);
+			DrawFrameRect(r.left, r.bottom - 9, r.right, r.bottom, wi->color,  (clicked) ? FR_LOWERED : FR_NONE);
 			DoDrawString(DOWNARROW, r.left + 2 + clicked, r.bottom - 9 + clicked, 0x10);
 
 			c1 = _colour_gradient[wi->color&0xF][3];
@@ -349,7 +349,7 @@
 			GfxFillRect(r.left+8, r.top+10, r.left+8, r.bottom-10, c2);
 
 			pt = HandleScrollbarHittest(&w->vscroll2, r.top, r.bottom);
-			DrawFrameRect(r.left, pt.x, r.right, pt.y, wi->color, (w->flags4 & (WF_SCROLL_MIDDLE | WF_HSCROLL | WF_SCROLL2)) == (WF_SCROLL_MIDDLE | WF_SCROLL2) ? FR_LOWERED : 0);
+			DrawFrameRect(r.left, pt.x, r.right, pt.y, wi->color, (w->flags4 & (WF_SCROLL_MIDDLE | WF_HSCROLL | WF_SCROLL2)) == (WF_SCROLL_MIDDLE | WF_SCROLL2) ? FR_LOWERED : FR_NONE);
 			break;
 		}
 
@@ -361,11 +361,11 @@
 			assert(r.bottom - r.top == 11); // XXX - to ensure the same sizes are used everywhere!
 
 			clicked = ((w->flags4 & (WF_SCROLL_UP | WF_HSCROLL)) == (WF_SCROLL_UP | WF_HSCROLL));
-			DrawFrameRect(r.left, r.top, r.left + 9, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0);
+			DrawFrameRect(r.left, r.top, r.left + 9, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE);
 			DrawSprite(SPR_ARROW_LEFT, r.left + 1 + clicked, r.top + 1 + clicked);
 
 			clicked = ((w->flags4 & (WF_SCROLL_DOWN | WF_HSCROLL)) == (WF_SCROLL_DOWN | WF_HSCROLL));
-			DrawFrameRect(r.right-9, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0);
+			DrawFrameRect(r.right-9, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE);
 			DrawSprite(SPR_ARROW_RIGHT, r.right - 8 + clicked, r.top + 1 + clicked);
 
 			c1 = _colour_gradient[wi->color&0xF][3];
@@ -383,7 +383,7 @@
 
 			// draw actual scrollbar
 			pt = HandleScrollbarHittest(&w->hscroll, r.left, r.right);
-			DrawFrameRect(pt.x, r.top, pt.y, r.bottom, wi->color, (w->flags4 & (WF_SCROLL_MIDDLE | WF_HSCROLL)) == (WF_SCROLL_MIDDLE | WF_HSCROLL) ? FR_LOWERED : 0);
+			DrawFrameRect(pt.x, r.top, pt.y, r.bottom, wi->color, (w->flags4 & (WF_SCROLL_MIDDLE | WF_HSCROLL)) == (WF_SCROLL_MIDDLE | WF_HSCROLL) ? FR_LOWERED : FR_NONE);
 
 			break;
 		}
@@ -423,7 +423,7 @@
 			assert(r.right - r.left == 11); // XXX - to ensure the same sizes are used everywhere!
 
 			clicked = !!(w->flags4 & WF_STICKY);
-			DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0);
+			DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE);
 			DrawSprite((clicked) ? SPR_PIN_UP : SPR_PIN_DOWN, r.left + 2 + clicked, r.top + 3 + clicked);
 			break;
 		}
@@ -432,7 +432,7 @@
 			assert(r.right - r.left == 11); // XXX - to ensure the same sizes are used everywhere!
 
 			clicked = !!(w->flags4 & WF_SIZING);
-			DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : 0);
+			DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, (clicked) ? FR_LOWERED : FR_NONE);
 			DrawSprite(SPR_WINDOW_RESIZE, r.left + 3 + clicked, r.top + 3 + clicked);
 			break;
 		}
@@ -440,7 +440,7 @@
 		case WWT_CLOSEBOX: {
 			assert(r.right - r.left == 10); // ensure the same sizes are used everywhere
 
-			DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, 0);
+			DrawFrameRect(r.left, r.top, r.right, r.bottom, wi->color, FR_NONE);
 			DrawString(r.left + 2, r.top + 2, STR_00C5, 0);
 			break;
 		}
--- a/src/win32.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/win32.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -1,10 +1,12 @@
 /* $Id$ */
 
 #include "stdafx.h"
+#include "hal.h"
 #include "openttd.h"
 #include "debug.h"
 #include "functions.h"
 #include "macros.h"
+#include "helpers.hpp"
 #include "saveload.h"
 #include "string.h"
 #include "gfx.h"
@@ -447,8 +449,8 @@
 
 	_ident = GetTickCount(); // something pretty unique
 
-	MakeCRCTable(alloca(256 * sizeof(uint32)));
-	_crash_msg = output = LocalAlloc(LMEM_FIXED, 8192);
+	MakeCRCTable((uint32*)alloca(256 * sizeof(uint32)));
+	_crash_msg = output = (char*)LocalAlloc(LMEM_FIXED, 8192);
 
 	{
 		SYSTEMTIME time;
@@ -634,7 +636,7 @@
 	DIR *d;
 
 	if (_global_dir_is_in_use) {
-		d = calloc(1, sizeof(*d));
+		CallocT(&d, 1);
 	} else {
 		_global_dir_is_in_use = true;
 		d = &_global_dir;
@@ -911,7 +913,7 @@
 	char *s, *cfg;
 	wchar_t path[MAX_PATH];
 
-	_paths.personal_dir = _paths.game_data_dir = cfg = malloc(MAX_PATH);
+	_paths.personal_dir = _paths.game_data_dir = cfg = (char*)malloc(MAX_PATH);
 	GetCurrentDirectoryW(MAX_PATH - 1, path);
 	convert_from_fs(path, cfg, MAX_PATH);
 
@@ -962,7 +964,7 @@
 		OpenClipboard(NULL);
 		cbuf = GetClipboardData(CF_UNICODETEXT);
 
-		ptr = GlobalLock(cbuf);
+		ptr = (const char*)GlobalLock(cbuf);
 		ret = convert_from_fs((wchar_t*)ptr, utf8_buf, lengthof(utf8_buf));
 		GlobalUnlock(cbuf);
 		CloseClipboard();
@@ -972,7 +974,7 @@
 		OpenClipboard(NULL);
 		cbuf = GetClipboardData(CF_TEXT);
 
-		ptr = GlobalLock(cbuf);
+		ptr = (const char*)GlobalLock(cbuf);
 		ttd_strlcpy(utf8_buf, ptr, lengthof(utf8_buf));
 		GlobalUnlock(cbuf);
 		CloseClipboard();
--- a/src/window.cpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/window.cpp	Mon Jan 15 20:14:06 2007 +0000
@@ -14,6 +14,7 @@
 #include "variables.h"
 #include "table/sprites.h"
 #include "genworld.h"
+#include "helpers.hpp"
 
 // delta between mouse cursor and upper left corner of dragged window
 static Point _drag_delta;
@@ -312,7 +313,7 @@
 		if (*wz == w) return wz;
 	}
 
-	DEBUG(misc, 3, "Window (class %d, number %d) is not open, probably removed by recursive calls",
+	DEBUG(misc, 3, "Window (cls %d, number %d) is not open, probably removed by recursive calls",
 		w->window_class, w->window_number);
 	return NULL;
 }
@@ -543,7 +544,7 @@
 
 		for (wi = widget; wi->type != WWT_LAST; wi++) index++;
 
-		w->widget = realloc(w->widget, sizeof(*w->widget) * index);
+		ReallocT(&w->widget, index);
 		memcpy(w->widget, widget, sizeof(*w->widget) * index);
 		w->widget_count = index - 1;
 	} else {
@@ -1488,7 +1489,7 @@
  * @param wparam Specifies additional message-specific information
  * @param lparam Specifies additional message-specific information
  */
-void SendWindowMessage(WindowClass wnd_class, WindowNumber wnd_num, uint msg, uint wparam, uint lparam)
+void SendWindowMessage(WindowClass wnd_class, WindowNumber wnd_num, int msg, int wparam, int lparam)
 {
 	Window *w = FindWindowById(wnd_class, wnd_num);
 	if (w != NULL) SendWindowMessageW(w, msg, wparam, lparam);
@@ -1501,7 +1502,7 @@
  * @param wparam Specifies additional message-specific information
  * @param lparam Specifies additional message-specific information
  */
-void SendWindowMessageClass(WindowClass wnd_class, uint msg, uint wparam, uint lparam)
+void SendWindowMessageClass(WindowClass wnd_class, int msg, int wparam, int lparam)
 {
 	Window* const *wz;
 
--- a/src/window.h	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/window.h	Mon Jan 15 20:14:06 2007 +0000
@@ -6,6 +6,8 @@
 #include "macros.h"
 #include "string.h"
 #include "order.h"
+#include "rail.h"
+#include "airport.h"
 
 typedef struct WindowEvent WindowEvent;
 
@@ -38,7 +40,7 @@
      w->resize.width or w->resize.height.
    That was all.. good luck, and enjoy :) -- TrueLight */
 
-enum ResizeFlags {
+typedef enum ResizeFlags {
 	RESIZE_NONE   = 0,
 
 	RESIZE_LEFT   = 1,
@@ -77,12 +79,15 @@
 } Widget;
 
 typedef enum FrameFlags {
+	FR_NONE         = 0x00,
 	FR_TRANSPARENT  = 0x01,  ///< Makes the background transparent if set
 	FR_BORDERONLY   = 0x10,  ///< Draw border only, no background
 	FR_LOWERED      = 0x20,  ///< If set the frame is lowered and the background color brighter (ie. buttons when pressed)
 	FR_DARKENED     = 0x40,  ///< If set the background is darker, allows for lowered frames with normal background color when used with FR_LOWERED (ie. dropdown boxes)
 } FrameFlags;
 
+DECLARE_ENUM_AS_BIT_SET(FrameFlags);
+
 void DrawFrameRect(int left, int top, int right, int bottom, int color, FrameFlags flags);
 
 enum WindowEventCodes {
@@ -165,9 +170,9 @@
 		} keypress;
 
 		struct {
-			uint msg;      // message to be sent
-			uint wparam;   // additional message-specific information
-			uint lparam;   // additional message-specific information
+			int msg;      // message to be sent
+			int wparam;   // additional message-specific information
+			int lparam;   // additional message-specific information
 		} message;
 
 		struct {
@@ -180,80 +185,6 @@
 	} we;
 };
 
-enum WindowKeyCodes {
-	WKC_SHIFT = 0x8000,
-	WKC_CTRL  = 0x4000,
-	WKC_ALT   = 0x2000,
-	WKC_META  = 0x1000,
-
-	// Special ones
-	WKC_NONE        =  0,
-	WKC_ESC         =  1,
-	WKC_BACKSPACE   =  2,
-	WKC_INSERT      =  3,
-	WKC_DELETE      =  4,
-
-	WKC_PAGEUP      =  5,
-	WKC_PAGEDOWN    =  6,
-	WKC_END         =  7,
-	WKC_HOME        =  8,
-
-	// Arrow keys
-	WKC_LEFT        =  9,
-	WKC_UP          = 10,
-	WKC_RIGHT       = 11,
-	WKC_DOWN        = 12,
-
-	// Return & tab
-	WKC_RETURN      = 13,
-	WKC_TAB         = 14,
-
-	// Numerical keyboard
-	WKC_NUM_0       = 16,
-	WKC_NUM_1       = 17,
-	WKC_NUM_2       = 18,
-	WKC_NUM_3       = 19,
-	WKC_NUM_4       = 20,
-	WKC_NUM_5       = 21,
-	WKC_NUM_6       = 22,
-	WKC_NUM_7       = 23,
-	WKC_NUM_8       = 24,
-	WKC_NUM_9       = 25,
-	WKC_NUM_DIV     = 26,
-	WKC_NUM_MUL     = 27,
-	WKC_NUM_MINUS   = 28,
-	WKC_NUM_PLUS    = 29,
-	WKC_NUM_ENTER   = 30,
-	WKC_NUM_DECIMAL = 31,
-
-	// Space
-	WKC_SPACE       = 32,
-
-	// Function keys
-	WKC_F1          = 33,
-	WKC_F2          = 34,
-	WKC_F3          = 35,
-	WKC_F4          = 36,
-	WKC_F5          = 37,
-	WKC_F6          = 38,
-	WKC_F7          = 39,
-	WKC_F8          = 40,
-	WKC_F9          = 41,
-	WKC_F10         = 42,
-	WKC_F11         = 43,
-	WKC_F12         = 44,
-
-	// 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,
-	WKC_PAUSE       = 46,
-
-	// 0-9 are mapped to 48-57
-	// A-Z are mapped to 65-90
-	// a-z are mapped to 97-122
-};
-
 typedef struct WindowDesc {
 	int16 left, top, width, height;
 	WindowClass cls;
@@ -389,8 +320,8 @@
 typedef struct {
 	byte vehicle_type;
 	union {
-		byte railtype;
-		byte acc_planes; // AIRCRAFT_ONLY, ALL, HELICOPTERS_ONLY
+		RailTypeByte railtype;
+		AcceptPlanesByte acc_planes; // AIRCRAFT_ONLY, ALL, HELICOPTERS_ONLY
 	} filter;
 	byte sel_index;  // deprecated value, used for 'unified' ship and road
 	bool descending_sort_order;
@@ -494,11 +425,15 @@
 assert_compile(WINDOW_CUSTOM_SIZE >= sizeof(scroller_d));
 
 typedef enum SortListFlags {
+	VL_NONE    = 0x00,
 	VL_DESC    = 0x01,  // sort descending or ascending
 	VL_RESORT  = 0x02,  // instruct the code to resort the list in the next loop
-	VL_REBUILD = 0x04   // create sort-listing to use for qsort and friends
+	VL_REBUILD = 0x04,  // create sort-listing to use for qsort and friends
+	VL_END     = 0x08
 } SortListFlags;
 
+DECLARE_ENUM_AS_BIT_SET(SortListFlags);
+
 typedef struct Listing {
 	bool order;    // Ascending/descending
 	byte criteria; // Sorting criteria
@@ -596,8 +531,8 @@
 void CallWindowEventNP(Window *w, int event);
 void CallWindowTickEvent(void);
 void SetWindowDirty(const Window *w);
-void SendWindowMessage(WindowClass wnd_class, WindowNumber wnd_num, uint msg, uint wparam, uint lparam);
-void SendWindowMessageClass(WindowClass wnd_class, uint msg, uint wparam, uint lparam);
+void SendWindowMessage(WindowClass wnd_class, WindowNumber wnd_num, int msg, int wparam, int lparam);
+void SendWindowMessageClass(WindowClass wnd_class, int msg, int wparam, int lparam);
 
 Window *FindWindowById(WindowClass cls, WindowNumber number);
 void DeleteWindow(Window *w);
@@ -775,9 +710,6 @@
 void ResetWindowSystem(void);
 int GetMenuItemIndex(const Window *w, int x, int y);
 void InputLoop(void);
-void HandleKeypress(uint32 key);
-void HandleMouseEvents(void);
-void UpdateWindows(void);
 void InvalidateWidget(const Window *w, byte widget_index);
 void InvalidateThisWindowData(Window *w);
 void InvalidateWindowData(WindowClass cls, WindowNumber number);
@@ -816,12 +748,6 @@
 
 VARDEF Point _cursorpos_drag_start;
 
-VARDEF bool _left_button_down;
-VARDEF bool _left_button_clicked;
-
-VARDEF bool _right_button_down;
-VARDEF bool _right_button_clicked;
-
 VARDEF int _scrollbar_start_pos;
 VARDEF int _scrollbar_size;
 VARDEF byte _scroller_click_timeout;
--- a/src/yapf/follow_track.hpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/yapf/follow_track.hpp	Mon Jan 15 20:14:06 2007 +0000
@@ -173,7 +173,7 @@
 
 		// rail transport is possible only on compatible rail types
 		if (IsRailTT()) {
-			RailType rail_type = GetTileRailType(m_new_tile, DiagdirToDiagTrackdir(m_exitdir));
+			RailType rail_type = GetTileRailType(m_new_tile, TrackdirToTrack(DiagdirToDiagTrackdir(m_exitdir)));
 			if (((1 << rail_type) & m_veh->u.rail.compatible_railtypes) == 0) {
 				// incompatible rail type
 				return false;
--- a/src/yapf/track_dir.hpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/yapf/track_dir.hpp	Mon Jan 15 20:14:06 2007 +0000
@@ -3,33 +3,9 @@
 #ifndef  TRACK_DIR_HPP
 #define  TRACK_DIR_HPP
 
-EXTERN_C_BEGIN
 #include "../tile.h"
 #include "../openttd.h"
 #include "../map.h"
 #include "../rail.h"
-EXTERN_C_END
-
-/** Helpers to allow to work with enum as with type safe bit set in C++ */
-#define DECLARE_ENUM_AS_BIT_MASK(mask_t) \
-	FORCEINLINE mask_t operator | (mask_t m1, mask_t m2) {return (mask_t)((int)m1 | m2);} \
-	FORCEINLINE mask_t operator & (mask_t m1, mask_t m2) {return (mask_t)((int)m1 & m2);} \
-	FORCEINLINE mask_t operator ^ (mask_t m1, mask_t m2) {return (mask_t)((int)m1 ^ m2);} \
-	FORCEINLINE mask_t& operator |= (mask_t& m1, mask_t m2) {m1 = m1 | m2; return m1;} \
-	FORCEINLINE mask_t& operator &= (mask_t& m1, mask_t m2) {m1 = m1 & m2; return m1;} \
-	FORCEINLINE mask_t& operator ^= (mask_t& m1, mask_t m2) {m1 = m1 ^ m2; return m1;} \
-	FORCEINLINE mask_t operator ~(mask_t m) {return (mask_t)(~(int)m);}
-
-/** probably redundant enum combining operators (as we have conversion functions) */
-#define DECLARE_ENUM_AS_BIT_INDEX(idx_t, mask_t) \
-	FORCEINLINE mask_t operator << (int m, idx_t i) {return (mask_t)(m << (int)i);} \
-	FORCEINLINE mask_t operator << (mask_t m, int i) {return (mask_t)(((int)m) << i);} \
-	FORCEINLINE mask_t operator >> (mask_t m, int i) {return (mask_t)(((int)m) >> i);}
-
-DECLARE_ENUM_AS_BIT_MASK(TrackBits)
-DECLARE_ENUM_AS_BIT_INDEX(Track, TrackBits)
-
-DECLARE_ENUM_AS_BIT_MASK(TrackdirBits)
-DECLARE_ENUM_AS_BIT_INDEX(Trackdir, TrackdirBits)
 
 #endif /* TRACK_DIR_HPP */
--- a/src/yapf/yapf.hpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/yapf/yapf.hpp	Mon Jan 15 20:14:06 2007 +0000
@@ -7,7 +7,6 @@
 
 #include "track_dir.hpp"
 
-EXTERN_C_BEGIN
 #include "../depot.h"
 #include "../road_map.h"
 #include "../tunnel_map.h"
@@ -22,12 +21,9 @@
 #include "../pathfind.h"
 #include "../waypoint.h"
 #include "../debug.h"
-EXTERN_C_END
 
-EXTERN_C_BEGIN
-	extern Patches _patches_newgame;
-	extern uint64 _rdtsc(void);
-EXTERN_C_END
+extern Patches _patches_newgame;
+extern uint64 _rdtsc(void);
 
 #include <limits.h>
 #include <new>
--- a/src/yapf/yapf_base.hpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/yapf/yapf_base.hpp	Mon Jan 15 20:14:06 2007 +0000
@@ -3,9 +3,7 @@
 #ifndef  YAPF_BASE_HPP
 #define  YAPF_BASE_HPP
 
-EXTERN_C_BEGIN
 #include "../debug.h"
-EXTERN_C_END
 
 #include "fixedsizearray.hpp"
 #include "blob.hpp"
--- a/src/yapf/yapf_common.hpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/yapf/yapf_common.hpp	Mon Jan 15 20:14:06 2007 +0000
@@ -138,8 +138,8 @@
 	 *  adds it to the actual cost from origin and stores the sum to the Node::m_estimate */
 	inline bool PfCalcEstimate(Node& n)
 	{
-		int dx = abs(TileX(n.GetTile()) - TileX(m_destTile));
-		int dy = abs(TileY(n.GetTile()) - TileY(m_destTile));
+		int dx = delta(TileX(n.GetTile()), TileX(m_destTile));
+		int dy = delta(TileY(n.GetTile()), TileY(m_destTile));
 		assert(dx >= 0 && dy >= 0);
 		int dd = min(dx, dy);
 		int dxy = abs(dx - dy);
--- a/src/yapf/yapf_costrail.hpp	Thu Jan 11 13:41:16 2007 +0000
+++ b/src/yapf/yapf_costrail.hpp	Mon Jan 15 20:14:06 2007 +0000
@@ -195,9 +195,7 @@
 		Trackdir trackdir = n.m_key.m_td;
 		TileType tile_type = GetTileType(tile);
 
-		DEBUG(yapf, 3, "PfCalcCost(Node:tile=%04X td=%s; Parent:tile=%04X td=%s)", tile, GetTrackdirName(trackdir), prev_tile, GetTrackdirName(prev_trackdir));
-
-		RailType rail_type = GetTileRailType(tile, trackdir);
+		RailType rail_type = GetTileRailType(tile, TrackdirToTrack(trackdir));
 
 		// detect exit from bridge wormhole
 		Trackdir intermediate_trackdir = INVALID_TRACKDIR;
@@ -286,7 +284,7 @@
 
 			// if rail type changes, finish segment (cached segment can't contain more rail types)
 			{
-				RailType new_rail_type = GetTileRailType(F.m_new_tile, (Trackdir)FindFirstBit2x64(F.m_new_td_bits));
+				RailType new_rail_type = GetTileRailType(F.m_new_tile, TrackdirToTrack(FindFirstTrackdir(F.m_new_td_bits)));
 				if (new_rail_type != rail_type) {
 					DEBUG(yapf, 4, "  end: rail type changes");
 					break;