[Scummvm-git-logs] scummvm master -> 94ddf526f43068925ca914f60934cf5ad53371cf

sev- sev at scummvm.org
Thu Jul 13 18:28:54 CEST 2017


This automated email contains information about 118 new commits which have been
pushed to the 'scummvm' repo located at https://github.com/scummvm/scummvm .

Summary:
94439e2ce3 SLUDGE: Add first classes in scummvm to detect .slg game file
219044abf9 SLUDGE: Add sludge files and make it compile
c4a5af22ea SLUDGE: Add namespace
f2d81f6f5d SLUDGE: Add new debug channels
1aa64b5b0f SLUDGE: Add namespace for file version.h
f5b4cf6803 SLUDGE: Remove inner include of vorbis library
45dcfdfc0b SLUDGE: Replace standard file reading functions by Common functions
f8ca5d14c4 SLUDGE: Replace stream writing functions id backdrop and formatting
9f7d301ef4 SLUDGE: Refactor background loading code
6808650f3e SLUDGE: Refactor png specific functions in backdrop
2dddb900c9 SLUDGE: Use PNGDecoder to read backdrop
ca2ee02496 SLUDGE: code formatting
6e5dec3137 SLUDGE: Fix png displaying
c0822cbc8d SLUDGE: Fix configure.engine
3ae270f709 SLUDGE: Correct ifdef position in backdrop.h
b920f61a11 SLUDGE: Add the slusge specific image decoder
8c59f8deac SLUDGE: Replace sludge stream reading functions by scummvm ones
786e4c3dc3 SLUDGE: Refactor image loading function and apply in backdrop
cfe2e63793 SLUDGE: refactor HSIDecoder out of Imgloader
cd42e483de SLUDGE: complete sprite loading
733e758fcb SLUDGE: move backdrop display code to backdrop.cpp
00b64e01d4 SLUDGE: Add debug channel for fatal msg
54ad266157 SLUDGE: fix sprite loading error
30eef2568c SLUDGE: display sprites with TransparentSurface
a589fac895 SLUDGE: fix sprite flickering by using a full screen surface
414b3c4714 SLUDGE: text display
10ff6994ae SLUDGE: format code and remove oneliners
39c1223856 SLUDGE: add copyright information
dc380b4ba4 SLUDGE: align increment operator
c44b4f3128 SLUDGE: remove implementation of tga.h
a8ccd05315 SLUDGE: header formatting
7430ebe883 SLUDGE: use scummvm int type instead of uint16/32_t
bee42dc52f SLUDGE: remove platform dependent defines
4773aff468 SLUDGE: correct int type
90ea9d0177 SLUDGE: spelling correction in define
83ab05630c SLUDGE: replace int type by scummvm types in utf8
3975fd7215 SLUDGE: remove showSetupWindow
2ca6845962 SLUDGE: use AD_ENTRY1s instead of AD_ENTRY1
d5379c212c SLUDGE: add game file name getter in detection
77d5c7235d SLUDGE: replace sludge colours by pixelformat
839e7fb4d2 SLUDGE: fix unmatched delete[] leaks
78cba75570 SLUDGE: change pixel formats to pointers and fix seg fault
09b4a0675e SLUDGE: remove value setting loop by memset
da842ee14e SLUDGE: remove unused sound files and rename cpp
ef9438065f SLUDGE: play game wav sound in a rough way
51a20af064 SLUDGE: leave MOD sound loading aside
7b2a2123f4 SLUDGE: add new game for testing
747820bbed SLUDGE: get loop sound work for wav and ogg
36d078cfe4 SLUDGE: add sound loop test game
15c7958d57 SLUDGE: add sound loop for wav and ogg
5baae657fd SLUDGE: cache of ended sound in playlist won't be used before handled
bbde5f4bf4 SLUDGE: remove #ifndef of cursor display and formatting code
0eb18c2627 SLUDGE: set to right delay time
536ddf7e89 SLUDGE: change struct texture to Surface
e52dbca7fd SLUDGE: remove unused variable in parallaxLayer
9418891237 SLUDGE: get freeze and unfreeze scene work
43ffa3bcc8 SLUDGE: give a 0.5 opacity for mixOverlay image
ea1f2412ee SLUDGE: get input work by replacing sdl event by scummvm event
82f023d9bd SLUDGE: free surfaces in freeze struct
83926d07a3 SLUDGE: fix error that chracter has no click effect
4b941e16db SLUDGE: remove a low-level graphic loop
387a558ec4 SLUDGE: add dark screen effect
f138547808 SLUDGE: paste image to background
eb9968332e SLUDGE: change background and zByffer restore order in freeze
714196132c SLUDGE: load zBuffer sprites as backdrop copies
f89f1aad4c SLUDGE: formatting code in sprites.cpp
52b627bae6 SLUDGE: use Common::List to reproduce layer effects
03f43f789c SLUDGE: add fall back detection
279a53302a SLUDGE: add game detection for Robin's rescue
e7a22b59f8 SLUDGE: add several debug infos and exit when error
d63953d9ce SLUDGE: free resource when finish reading png sprite
5469aaf8ec SLUDGE: move initGraphics after sludge init
1a27d67123 IMAGE: add flag to skip signature check in png decoder
44d7663a49 SLUDGE: read headless png sprites
e7d1f272dc SLUDGE: set sludge game to 1xScale by default
639f20f168 SLUDGE: fix bug of setting zbuffer before backdrop
15e7f5c48e SLUDGE: fix unmatched delete []
ae54897ff5 SLUDGE: add channel to debug text
3b3c92558b SLUDGE: add game timing
9a57db6b9c SLUDGE: correct text color for png font
082bf55b56 SLUDGE: clean debug info
91d2b5d31e SLUDGE: kill a sprite bank
b5a77c9393 SLUDGE: check point to non transparent part of a character
0e8db2bf0d SLUDGE: add blankscreen effect
874d03f79b SLUDGE: stop a sound by file number
791aedf7a5 Image: extend writePng for 4-byte pixelFormat
8152793d09 SLUDGE: save&load system (without thumbnail and snapshot)
fe773c1beb SLUDGE: replace char* by Common::String for error messages
302c946279 SLUDGE: use U32String to replace sludge utf8 library
53572c8e58 SLUDGE: not to build sludge by default
9560969ea8 SLUDGE: remove shader-related files
1e261d6cd3 SLUDGE: remove unused libs
07e4982027 SLUDGE: remove #ifdef HAVE_GLES2 and clean code in graphics
ee45e15178 SLUDGE: use Common::Point instead of struct POINT
ed09887e84 SLUDGE: remove an unused .h
08304b848a SLUDGE: use Common/debug instead of sludge debug
b8cede684e SLUDGE: remove unused files
cc727710b4 SLUDGE: remove define duplication
f8e1fe0064 SLUDGE: replace int types to scummvm defined ones
2563180f11 SLUDGE: remove math functions defined in sludge
389bd92ab9 SLUDGE: correct #define in header to match file name
076f841526 SLUDGE: fix u32string saving error
d37888ad5f SLUDGE: use read/writeSint16LE instead of get/putSigned
8f2a177cef STREAM: add read/write functions for float LE/BE
38262ad630 SLUDGE: use write/readFloatLB instead of Sludge get/putFloat
9d349e794e SLUDGE: code formatting for **
ae8df00f56 SLUDGE: replace abs() by scummvm ABS()
59ea5e5834 SLUDGE: use Graphics::Surface::drawLine instead of sludge defined drawLine
19ff9f419b SLUDGE: correct loadfile existence check
800987ab95 SLUDGE: replace char *by Common::String
1cd6de22e4 SLUDGE: remove debug code
d6308b9176 SLUDGE: replace utf8 chars by code
91fcdda2d1 SLUDGE: change global Common::String to public var of SludgeEngine
8f618e55ae SLUDGE: move namespace to functionlist.h
3c84965724 SLUDGE: delete a game that doesn't exist any more
6b794d3da7 SLUDGE: remove game settings from Sludge code
ef5e8091f6 SLUDGE: use multiple entries for language selection
94ddf526f4 SLUDGE: remove CommonCode directory to have a flat structure


Commit: 94439e2ce311734bfe7bb5700a6584b7550ea8f9
    https://github.com/scummvm/scummvm/commit/94439e2ce311734bfe7bb5700a6584b7550ea8f9
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Add first classes in scummvm to detect .slg game file

Changed paths:
  A engines/sludge/configure.engine
  A engines/sludge/console.cpp
  A engines/sludge/console.h
  A engines/sludge/detection.cpp
  A engines/sludge/module.mk
  A engines/sludge/sludge.cpp
  A engines/sludge/sludge.h


diff --git a/engines/sludge/configure.engine b/engines/sludge/configure.engine
new file mode 100644
index 0000000..24ae50d
--- /dev/null
+++ b/engines/sludge/configure.engine
@@ -0,0 +1,3 @@
+# This file is included from the main "configure" script
+# add_engine [name] [desc] [build-by-default] [subengines] [base games] [deps]
+add_engine sludge "Sludge" yes
\ No newline at end of file
diff --git a/engines/sludge/console.cpp b/engines/sludge/console.cpp
new file mode 100644
index 0000000..95d70b9
--- /dev/null
+++ b/engines/sludge/console.cpp
@@ -0,0 +1,34 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#include "sludge/console.h"
+
+namespace Sludge {
+
+SludgeConsole::SludgeConsole(SludgeEngine *vm) : GUI::Debugger() {
+	_vm = vm;
+}
+
+SludgeConsole::~SludgeConsole() {
+}
+
+} // End of namespace Sludge
diff --git a/engines/sludge/console.h b/engines/sludge/console.h
new file mode 100644
index 0000000..5f96409
--- /dev/null
+++ b/engines/sludge/console.h
@@ -0,0 +1,44 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef SLUDGE_CONSOLE_H
+#define SLUDGE_CONSOLE_H
+
+#include "gui/debugger.h"
+
+namespace Sludge {
+
+class SludgeEngine;
+
+// Example console class
+class SludgeConsole : public GUI::Debugger {
+public:
+	SludgeConsole(SludgeEngine *vm);
+	virtual ~SludgeConsole(void);
+	
+private:
+	SludgeEngine *_vm;
+};
+
+} // End of namespace Sludge
+
+#endif /* SLUDGE_CONSOLE_H */
diff --git a/engines/sludge/detection.cpp b/engines/sludge/detection.cpp
new file mode 100644
index 0000000..8297165
--- /dev/null
+++ b/engines/sludge/detection.cpp
@@ -0,0 +1,98 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#include "common/debug.h"
+
+#include "engines/advancedDetector.h"
+
+#include "sludge/sludge.h"
+
+namespace Sludge {
+
+struct SludgeGameDescription {
+	ADGameDescription desc;
+
+	int gameType;
+};
+
+int SludgeEngine::getGameType() const { return _gameDescription->gameType; }
+const char *SludgeEngine::getGameId() const { return _gameDescription->desc.gameId;}
+uint32 SludgeEngine::getFeatures() const { return _gameDescription->desc.flags; }
+Common::Language SludgeEngine::getLanguage() const { return _gameDescription->desc.language; }
+
+} // End of namespace Sludge
+
+static const PlainGameDescriptor sludgeGames[] = {
+	{ "sludge", "Sludge Game" },
+	{ "welcome", "Welcome Example" },
+	{ 0, 0 }
+};
+ 
+namespace Sludge {
+static const SludgeGameDescription gameDescriptions[] = {
+	{
+		{
+			"welcome",
+			"",
+			AD_ENTRY1("Welcome.slg", "50445503761cf6684fe3270d0860a4c3"),
+			Common::EN_ANY,
+			Common::kPlatformUnknown,
+			ADGF_NO_FLAGS,
+			GUIO0()
+		},
+		0
+	},
+
+	{ AD_TABLE_END_MARKER, 0 }
+};
+
+} // End of namespace Sludge
+
+class SludgeMetaEngine : public AdvancedMetaEngine {
+public:
+	SludgeMetaEngine() : AdvancedMetaEngine(Sludge::gameDescriptions, sizeof(Sludge::SludgeGameDescription), sludgeGames) {
+		_singleId = "sludge";
+		_maxScanDepth = 1;
+	}
+
+	virtual const char *getName() const {
+		return "Sludge Engine";
+	}
+ 
+	virtual const char *getOriginalCopyright() const {
+		return "Copyright (C) 2000-2014 Hungry Software and contributors";
+	}
+ 
+ 
+	virtual bool createInstance(OSystem *syst, Engine **engine, const ADGameDescription *desc) const {
+		const Sludge::SludgeGameDescription *gd = (const Sludge::SludgeGameDescription *)desc;
+			if (gd) {
+				*engine = new Sludge::SludgeEngine(syst, gd);
+			}
+			return gd != 0;
+	}
+};
+
+#if PLUGIN_ENABLED_DYNAMIC(SLUDGE)
+	REGISTER_PLUGIN_DYNAMIC(SLUDGE, PLUGIN_TYPE_ENGINE, SludgeMetaEngine);
+#else
+	REGISTER_PLUGIN_STATIC(SLUDGE, PLUGIN_TYPE_ENGINE, SludgeMetaEngine);
+#endif
diff --git a/engines/sludge/module.mk b/engines/sludge/module.mk
new file mode 100644
index 0000000..45929cf
--- /dev/null
+++ b/engines/sludge/module.mk
@@ -0,0 +1,17 @@
+MODULE := engines/sludge
+ 
+MODULE_OBJS := \
+	detection.o \
+	sludge.o \
+	console.o
+ 
+MODULE_DIRS += \
+	engines/sludge
+ 
+# This module can be built as a plugin
+ifeq ($(ENABLE_SLUDGE), DYNAMIC_PLUGIN)
+PLUGIN := 1
+endif
+ 
+# Include common rules 
+include $(srcdir)/rules.mk
\ No newline at end of file
diff --git a/engines/sludge/sludge.cpp b/engines/sludge/sludge.cpp
new file mode 100644
index 0000000..9a910b2
--- /dev/null
+++ b/engines/sludge/sludge.cpp
@@ -0,0 +1,74 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#include "common/scummsys.h"
+ 
+#include "common/config-manager.h"
+#include "common/debug.h"
+#include "common/debug-channels.h"
+#include "common/error.h"
+
+#include "engines/util.h"
+
+#include "sludge/sludge.h"
+ 
+namespace Sludge {
+ 
+SludgeEngine::SludgeEngine(OSystem *syst, const SludgeGameDescription *gameDesc)
+ : Engine(syst), _gameDescription(gameDesc), _console(nullptr) {
+ 
+	// register your random source
+	_rnd = new Common::RandomSource("sludge");
+
+	// Add debug channels
+	DebugMan.addDebugChannel(kSludgeDebugScript, "Script", "Script debug level");
+
+	// check init
+	debug("SludgeEngine::SludgeEngine");
+}
+ 
+SludgeEngine::~SludgeEngine() {
+
+	// Dispose resources
+	delete _rnd;
+ 
+	// Remove debug levels
+	DebugMan.clearAllDebugChannels();
+	
+	// Dispose console
+	delete _console;
+}
+ 
+Common::Error SludgeEngine::run() {
+	// init graphics
+	initGraphics(640, 480, false);
+
+	// create console
+	_console = new SludgeConsole(this);
+ 
+	// debug log
+	debug("SludgeEngine::init");
+ 
+	return Common::kNoError;
+}
+ 
+} // End of namespace Sludge
+
diff --git a/engines/sludge/sludge.h b/engines/sludge/sludge.h
new file mode 100644
index 0000000..5fe7c9a
--- /dev/null
+++ b/engines/sludge/sludge.h
@@ -0,0 +1,66 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef SLUDGE_H
+#define SLUDGE_H
+ 
+#include "common/random.h"
+#include "engines/engine.h"
+#include "gui/debugger.h"
+ 
+#include "sludge/console.h"
+
+namespace Sludge {
+ 
+class SludgeConsole;
+ 
+struct SludgeGameDescription;
+
+// debug channels
+enum {
+	kSludgeDebugScript = 1 << 0
+};
+ 
+class SludgeEngine : public Engine {
+protected:
+	// Engine APIs
+	virtual Common::Error run();
+
+public:
+	SludgeEngine(OSystem *syst, const SludgeGameDescription *gameDesc);
+	virtual ~SludgeEngine();
+ 
+	int getGameType() const;
+	const char *getGameId() const;
+	uint32 getFeatures() const;
+	Common::Language getLanguage() const;
+
+	const SludgeGameDescription *_gameDescription;
+ 
+private:
+	SludgeConsole *_console;
+ 	Common::RandomSource *_rnd;
+};
+
+} // End of namespace Sludge
+ 
+#endif


Commit: 219044abf9841461043d6e2acf0d5a48a7c7648b
    https://github.com/scummvm/scummvm/commit/219044abf9841461043d6e2acf0d5a48a7c7648b
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Add sludge files and make it compile

Changed paths:
  A engines/sludge/CommonCode/functionlist.h
  A engines/sludge/CommonCode/specialsettings.h
  A engines/sludge/CommonCode/tga.cpp
  A engines/sludge/CommonCode/tga.h
  A engines/sludge/CommonCode/utf8.cpp
  A engines/sludge/CommonCode/utf8.h
  A engines/sludge/CommonCode/version.h
  A engines/sludge/allfiles.h
  A engines/sludge/backdrop.cpp
  A engines/sludge/backdrop.h
  A engines/sludge/bg_effects.cpp
  A engines/sludge/bg_effects.h
  A engines/sludge/builtin.cpp
  A engines/sludge/builtin.h
  A engines/sludge/color.frag
  A engines/sludge/color.vert
  A engines/sludge/colours.h
  A engines/sludge/csludge.h
  A engines/sludge/cursors.cpp
  A engines/sludge/cursors.h
  A engines/sludge/debug.cpp
  A engines/sludge/debug.h
  A engines/sludge/eglport/eglport.cpp
  A engines/sludge/eglport/eglport.h
  A engines/sludge/errors.h
  A engines/sludge/fileset.cpp
  A engines/sludge/fileset.h
  A engines/sludge/fixScaleSprite.frag
  A engines/sludge/fixScaleSprite.vert
  A engines/sludge/floor.cpp
  A engines/sludge/floor.h
  A engines/sludge/fonttext.cpp
  A engines/sludge/fonttext.h
  A engines/sludge/freeze.cpp
  A engines/sludge/freeze.h
  A engines/sludge/graphics.cpp
  A engines/sludge/graphics.h
  A engines/sludge/helpers.cpp
  A engines/sludge/helpers.h
  A engines/sludge/language.cpp
  A engines/sludge/language.h
  A engines/sludge/libvorbis/COPYING
  A engines/sludge/libvorbis/vorbis_misc.h
  A engines/sludge/libvorbis/vorbis_os.h
  A engines/sludge/libwebm/AUTHORS.TXT
  A engines/sludge/libwebm/LICENSE.TXT
  A engines/sludge/libwebm/PATENTS.TXT
  A engines/sludge/libwebm/mkvparser.cpp
  A engines/sludge/libwebm/mkvparser.hpp
  A engines/sludge/libwebm/mkvreader.cpp
  A engines/sludge/libwebm/mkvreader.hpp
  A engines/sludge/line.cpp
  A engines/sludge/line.h
  A engines/sludge/linuxstuff.cpp
  A engines/sludge/linuxstuff.h
  A engines/sludge/loadsave.cpp
  A engines/sludge/loadsave.h
  A engines/sludge/main_loop.cpp
  A engines/sludge/main_loop.h
  A engines/sludge/memwatch.cpp
  A engines/sludge/memwatch.h
  A engines/sludge/moreio.cpp
  A engines/sludge/moreio.h
  A engines/sludge/movie.cpp
  A engines/sludge/movie.h
  A engines/sludge/newfatal.cpp
  A engines/sludge/newfatal.h
  A engines/sludge/objtypes.cpp
  A engines/sludge/objtypes.h
  A engines/sludge/people.cpp
  A engines/sludge/people.h
  A engines/sludge/platform-dependent.h
  A engines/sludge/region.cpp
  A engines/sludge/region.h
  A engines/sludge/savedata.cpp
  A engines/sludge/savedata.h
  A engines/sludge/scale.frag
  A engines/sludge/scale.vert
  A engines/sludge/scale_noaa.frag
  A engines/sludge/shaders.cpp
  A engines/sludge/shaders.h
  A engines/sludge/sludger.cpp
  A engines/sludge/sludger.h
  A engines/sludge/sound.h
  A engines/sludge/sound_bass.cpp
  A engines/sludge/sound_nosound.cpp
  A engines/sludge/sound_openal.cpp
  A engines/sludge/sprbanks.cpp
  A engines/sludge/sprbanks.h
  A engines/sludge/sprites.cpp
  A engines/sludge/sprites.h
  A engines/sludge/statusba.cpp
  A engines/sludge/statusba.h
  A engines/sludge/stringy.cpp
  A engines/sludge/stringy.h
  A engines/sludge/talk.cpp
  A engines/sludge/talk.h
  A engines/sludge/texture.frag
  A engines/sludge/texture.vert
  A engines/sludge/thumbnail.cpp
  A engines/sludge/thumbnail.h
  A engines/sludge/timing.cpp
  A engines/sludge/timing.h
  A engines/sludge/transition.cpp
  A engines/sludge/transition.h
  A engines/sludge/variable.cpp
  A engines/sludge/variable.h
  A engines/sludge/vid.cpp
  A engines/sludge/vid.h
  A engines/sludge/winstuff.cpp
  A engines/sludge/winstuff.h
  A engines/sludge/yuv.frag
  A engines/sludge/yuv.vert
  A engines/sludge/zbuffer.cpp
  A engines/sludge/zbuffer.h
    engines/sludge/module.mk
    engines/sludge/sludge.cpp


diff --git a/engines/sludge/CommonCode/functionlist.h b/engines/sludge/CommonCode/functionlist.h
new file mode 100644
index 0000000..3d98553
--- /dev/null
+++ b/engines/sludge/CommonCode/functionlist.h
@@ -0,0 +1,175 @@
+/*
+This is the list of the built in functions
+
+true or false states if it's a used function
+in the current version of the engine,
+but that value currently isn't used anywhere
+*/
+
+FUNC(true, say)
+FUNC(true, skipSpeech)
+FUNC(true, statusText)
+FUNC(true, pause)
+FUNC(true, onLeftMouse)
+FUNC(true, onRightMouse)
+FUNC(true, setCursor)
+FUNC(true, addOverlay)
+FUNC(true, addCharacter)
+FUNC(true, playSound)
+FUNC(true, getMouseX)
+FUNC(true, getMouseY)
+FUNC(true, addScreenRegion)
+FUNC(true, onMoveMouse)
+FUNC(true, onFocusChange)
+FUNC(true, getOverObject)
+FUNC(true, blankScreen)
+FUNC(true, moveCharacter)
+FUNC(true, onKeyboard)
+FUNC(true, getObjectX)
+FUNC(true, getObjectY)
+FUNC(true, random)
+FUNC(true, spawnSub)
+FUNC(true, blankArea)
+FUNC(true, hideCharacter)
+FUNC(true, showCharacter)
+FUNC(true, callEvent)
+FUNC(true, removeScreenRegion)
+FUNC(true, animate)
+FUNC(true, turnCharacter)
+FUNC(true, removeAllCharacters)
+FUNC(true, removeAllScreenRegions)
+FUNC(true, setScale)
+FUNC(true, newStack)
+FUNC(true, pushToStack)
+FUNC(true, popFromStack)
+FUNC(true, clearStatus)
+FUNC(true, addStatus)
+FUNC(true, removeLastStatus)
+FUNC(true, lightStatus)
+FUNC(true, getStatusText)
+FUNC(true, setStatusColour)
+FUNC(true, deleteFromStack)
+FUNC(true, freeze)
+FUNC(true, unfreeze)
+FUNC(true, pasteImage)
+FUNC(true, copyStack)
+FUNC(true, completeTimers)
+FUNC(true, setCharacterDrawMode)
+FUNC(true, anim)
+FUNC(true, costume)
+FUNC(true, pickOne)
+FUNC(true, setCostume)
+FUNC(true, wait)
+FUNC(true, somethingSpeaking)
+FUNC(true, substring)
+FUNC(true, stringLength)
+FUNC(true, darkBackground)
+FUNC(true, saveGame)
+FUNC(true, loadGame)
+FUNC(true, quitGame)
+FUNC(true, rename)
+FUNC(true, stackSize)
+FUNC(true, pasteString)
+FUNC(true, startMusic)
+FUNC(true, setDefaultMusicVolume)
+FUNC(true, setMusicVolume)
+FUNC(true, stopMusic)
+FUNC(true, stopSound)
+FUNC(true, setFont)
+FUNC(true, alignStatus)
+FUNC(true, showFloor)
+FUNC(true, showBoxes)
+FUNC(true, positionStatus)
+FUNC(true, setFloor)
+FUNC(true, forceCharacter)
+FUNC(true, jumpCharacter)
+FUNC(true, peekStart)
+FUNC(true, peekEnd)
+FUNC(true, enqueue)
+FUNC(true, setZBuffer)
+FUNC(true, getMatchingFiles)
+FUNC(true, inFont)
+FUNC(true, onLeftMouseUp)
+FUNC(true, onRightMouseUp)
+FUNC(true, loopSound)
+FUNC(true, removeCharacter)
+FUNC(true, stopCharacter)
+FUNC(true, launch)
+FUNC(true, howFrozen)
+FUNC(true, setPasteColour)
+FUNC(true, setLitStatusColour)
+FUNC(true, fileExists)
+FUNC(true, floatCharacter)
+FUNC(true, cancelSub)
+FUNC(true, setCharacterWalkSpeed)
+FUNC(true, deleteAllFromStack)
+FUNC(true, setCharacterExtra)
+FUNC(true, mixOverlay)
+FUNC(true, pasteCharacter)
+FUNC(true, setSceneDimensions)
+FUNC(true, aimCamera)
+FUNC(true, getMouseScreenX)
+FUNC(true, getMouseScreenY)
+FUNC(true, setDefaultSoundVolume)
+FUNC(true, setSoundVolume)
+FUNC(true, setSoundLoopPoints)
+FUNC(true, setSpeechMode)
+FUNC(true, setLightMap)
+FUNC(true, think)
+FUNC(true, getCharacterDirection)
+FUNC(true, isCharacter)
+FUNC(true, isScreenRegion)
+FUNC(true, isMoving)
+FUNC(true, deleteFile)
+FUNC(true, renameFile)
+FUNC(true, hardScroll)
+FUNC(true, stringWidth)
+FUNC(true, setSpeechSpeed)
+FUNC(true, normalCharacter)
+FUNC(true, fetchEvent)
+FUNC(true, transitionLevel)
+FUNC(true, spinCharacter)
+FUNC(true, setFontSpacing)
+FUNC(true, burnString)
+FUNC(true, captureAllKeys)
+FUNC(true, cacheSound)
+FUNC(true, setCharacterSpinSpeed)
+FUNC(true, transitionMode)
+FUNC(false,  _rem_movieStart)
+FUNC(false,  _rem_movieAbort)
+FUNC(false,  _rem_moviePlaying)
+FUNC(false,  _rem_updateDisplay)
+FUNC(true, getSoundCache)
+FUNC(true, saveCustomData)
+FUNC(true, loadCustomData)
+FUNC(true, setCustomEncoding)
+FUNC(true, freeSound)
+FUNC(true, parallaxAdd)
+FUNC(true, parallaxClear)
+FUNC(true, setBlankColour)
+FUNC(true, setBurnColour)
+FUNC(true, getPixelColour)
+FUNC(true, makeFastArray)
+FUNC(true, getCharacterScale)
+FUNC(true, getLanguageID)
+FUNC(false, _rem_launchWith)
+FUNC(true, getFramesPerSecond)
+FUNC(true, showThumbnail)
+FUNC(true, setThumbnailSize)
+FUNC(true, hasFlag)
+FUNC(true, snapshotGrab)
+FUNC(true, snapshotClear)
+FUNC(true, bodgeFilenames)
+FUNC(false,  _rem_registryGetString)
+FUNC(true, quitWithFatalError)
+FUNC(true, _rem_setCharacterAA)
+FUNC(true, _rem_setMaximumAA)
+FUNC(true, setBackgroundEffect)
+FUNC(true, doBackgroundEffect)
+FUNC(true, setCharacterAngleOffset)
+FUNC(true, setCharacterTransparency)
+FUNC(true, setCharacterColourise)
+FUNC(true, zoomCamera)
+FUNC(true, playMovie)
+FUNC(true, stopMovie)
+FUNC(true, pauseMovie)
diff --git a/engines/sludge/CommonCode/specialsettings.h b/engines/sludge/CommonCode/specialsettings.h
new file mode 100644
index 0000000..1e41e4e
--- /dev/null
+++ b/engines/sludge/CommonCode/specialsettings.h
@@ -0,0 +1,8 @@
+#define SPECIAL_REGISTERED      1
+#define SPECIAL_FULLSCREEN      2
+#define SPECIAL_MOUSE_1         4
+#define SPECIAL_SILENT          8
+#define SPECIAL_MOUSE_2         16
+#define SPECIAL_INVISIBLE       32
+#define SPECIAL_HIDELOGO        64
+#define SPECIAL_HIDELOADING     128
diff --git a/engines/sludge/CommonCode/tga.cpp b/engines/sludge/CommonCode/tga.cpp
new file mode 100644
index 0000000..d25ccd9
--- /dev/null
+++ b/engines/sludge/CommonCode/tga.cpp
@@ -0,0 +1,278 @@
+#include <stdio.h>
+
+#include "tga.h"
+
+//FILE * debugFile = fopen ("TGAdebug.txt", "wt");
+
+unsigned short int makeColour (unsigned char r, unsigned char g, unsigned char b) {
+	unsigned short int reply = (unsigned short int) (r >> 3);
+	reply <<= 6;
+	reply += (unsigned short int) (g >> 2);
+	reply <<= 5;
+	reply += (unsigned short int) (b >> 3);
+	return reply & 65503;
+}
+
+int get2bytesReverse (FILE * fp) {
+	int a = fgetc (fp);
+	return a + fgetc (fp) * 256;
+}
+
+int countDown = 0;
+
+bool dither24bitImages = 0;
+
+char ditherArray[4][4] = {{4,12,6,14},{10,0,8,2},{7,15,5,13},{9,3,11,1}};
+
+void grabRGBA (FILE * fp, int bpc, unsigned char & r, unsigned char & g, unsigned char & b, unsigned char & a, palCol thePalette[])
+{
+	int grabbed1, grabbed2;
+	switch (bpc) {
+		case 8:
+			grabbed1 = fgetc (fp);
+			r = thePalette[grabbed1].r;
+			g = thePalette[grabbed1].g;
+			b = thePalette[grabbed1].b;
+			if (r == 255 && g == 0 && b == 255) {
+				r = g = b = a = 0;
+			} else a = 255;
+			break;
+			
+		case 16:
+			grabbed1 = fgetc (fp);
+			grabbed2 = fgetc (fp);
+			if (grabbed2*256+grabbed1 == 31775) {
+				r=g=b=a=0;
+				break;
+			}
+
+			r = ((grabbed2 & 127) << 1),
+			g = ((grabbed1 & 224) >> 2) + (grabbed2 << 6);
+			b = ((grabbed1 & 31) << 3);
+			if (r == 255 && g == 0 && b == 255) {
+				r = g = b = a = 0;
+			} else a = 255;
+			break;
+			
+		case 24:
+			b = fgetc (fp);
+			g = fgetc (fp);
+			r = fgetc (fp);
+			if (r == 255 && g == 0 && b == 255) {
+				r = g = b = a = 0;
+			} else a = 255;
+			break;
+			
+		case 32:
+			b = fgetc (fp);
+			g = fgetc (fp);
+			r = fgetc (fp);
+			a = fgetc (fp);
+			break;		
+	}
+}
+
+
+void grabRGB (FILE * fp, int bpc, unsigned char & r, unsigned char & g, unsigned char & b, palCol thePalette[])
+{
+	int a;
+	int grabbed1, grabbed2;
+	switch (bpc) {
+		case 8:
+		grabbed1 = fgetc (fp);
+		r = thePalette[grabbed1].r;
+		g = thePalette[grabbed1].g;
+		b = thePalette[grabbed1].b;
+		break;
+	
+		case 16:
+		grabbed1 = fgetc (fp);
+		grabbed2 = fgetc (fp);
+		r = ((grabbed2 & 127) << 1),
+		g = ((grabbed1 & 224) >> 2) + (grabbed2 << 6);
+		b = ((grabbed1 & 31) << 3);
+		break;
+				
+		case 24:
+		b = fgetc (fp);
+		g = fgetc (fp);
+		r = fgetc (fp);
+		break;
+		
+		case 32:
+		b = fgetc (fp);
+		g = fgetc (fp);
+		r = fgetc (fp);
+		a = fgetc (fp);
+			if (a < 100) {
+				r = 255;
+				g = 0;
+				b = 255;
+			}
+		break;		
+	}
+}
+
+void grabRGBACompressed (FILE * fp, int bpc, unsigned char & r2, unsigned char & g2, unsigned char & b2, unsigned char & a2, palCol thePalette[]) {
+	static unsigned char r, g, b, a;
+	static bool oneCol;
+	unsigned short col;
+	
+	// Do we have to start a new packet?
+	if (countDown == 0) {
+		
+		// Read the packet description thingy
+		col = fgetc (fp);
+		
+		// Is it raw data?
+		if (col >= 128) {
+			oneCol = true;
+			countDown = col - 127;
+			grabRGBA (fp, bpc, r, g, b, a, thePalette);
+			//			fprintf (debugFile, "  %d raw colours...\n", countDown);
+		} else {
+			oneCol = false;
+			countDown = col + 1;
+			//			fprintf (debugFile, "  %d pixels the same colour...\n", countDown);
+		}
+	}
+	
+	countDown --;
+	
+	if (! oneCol) {
+		grabRGBA (fp, bpc, r2, g2, b2, a2, thePalette);
+	} else {
+		r2 = r;
+		g2 = g;
+		b2 = b;
+		a2 = a;
+	}
+}
+
+
+void grabRGBCompressed (FILE * fp, int bpc, unsigned char & r2, unsigned char & g2, unsigned char & b2, palCol thePalette[]) {
+	static unsigned char r, g, b;
+	static bool oneCol;
+	unsigned short col;
+	
+	// Do we have to start a new packet?
+	if (countDown == 0) {
+		
+		// Read the packet description thingy
+		col = fgetc (fp);
+		
+		// Is it raw data?
+		if (col >= 128) {
+			oneCol = true;
+			countDown = col - 127;
+			grabRGB (fp, bpc, r, g, b, thePalette);
+			//			fprintf (debugFile, "  %d raw colours...\n", countDown);
+		} else {
+			oneCol = false;
+			countDown = col + 1;
+			//			fprintf (debugFile, "  %d pixels the same colour...\n", countDown);
+		}
+	}
+	
+	countDown --;
+	
+	if (! oneCol) {
+		grabRGB (fp, bpc, r2, g2, b2, thePalette);
+	} else {
+		r2 = r;
+		g2 = g;
+		b2 = b;
+	}
+}
+
+void addDither (unsigned char & col, const unsigned char add)
+{
+	int tot = col;
+	tot += add;
+	col = (tot > 255) ? 255 : tot;
+}
+
+unsigned short readAColour (FILE * fp, int bpc, palCol thePalette[], int x, int y) {
+	unsigned char r,g,b;
+	grabRGB (fp, bpc, r, g, b, thePalette);
+
+	if (dither24bitImages)
+	{
+		addDither (r, ditherArray[x&3][y&3]);
+		addDither (g, ditherArray[x&3][y&3] / 2);
+		addDither (b, ditherArray[x&3][y&3]);
+	}
+
+	return makeColour (r, g, b);
+}
+
+unsigned short readCompressedColour (FILE * fp, int bpc, palCol thePalette[], int x, int y) {
+	unsigned char r,g,b;
+	grabRGBCompressed (fp, bpc, r, g, b, thePalette);
+	
+	if (dither24bitImages)
+	{
+		addDither (r, ditherArray[x&3][y&3]);
+		addDither (g, ditherArray[x&3][y&3] / 2);
+		addDither (b, ditherArray[x&3][y&3]);
+	}
+	
+	return makeColour (r, g, b);
+}
+
+const char * readTGAHeader (TGAHeader & h, FILE * fp, palCol thePalette[]) {
+
+	h.IDBlockSize = fgetc (fp);
+	h.gotMap = fgetc (fp);
+	unsigned char imageType = fgetc (fp);
+	h.firstPalColour = get2bytesReverse (fp);
+	h.numPalColours = get2bytesReverse (fp);
+	h.bitsPerPalColour = fgetc (fp);
+	h.xOrigin = get2bytesReverse (fp);
+	h.yOrigin = get2bytesReverse (fp);
+	h.width = get2bytesReverse (fp);
+	h.height = get2bytesReverse (fp);
+	h.pixelDepth = fgetc (fp);
+	h.imageDescriptor = fgetc (fp);
+	countDown = 0;
+	// Who cares about the ID block?
+	fseek (fp, h.IDBlockSize, 1);
+
+	switch (imageType) {
+		case 1:
+		case 2:
+		h.compressed = false;
+		break;
+		
+		case 9:
+		case 10:
+		h.compressed = true;
+		break;
+		
+		default:
+		return "Unsupported internal image format... are you sure this is a valid TGA image file?";
+	}
+
+	if (h.pixelDepth != 8 && h.pixelDepth != 16 && h.pixelDepth != 24 && h.pixelDepth != 32) {
+		return "Colour depth is not 8, 16, 24 or 32 bits... are you sure this is a valid TGA image file?";
+	}
+
+	if (h.gotMap) {
+		int c;
+		for (c = 0; c < h.numPalColours; c ++) {
+			grabRGB (fp, h.bitsPerPalColour, thePalette[c].r, thePalette[c].g, thePalette[c].b, thePalette);
+		}
+	}
+
+	return NULL;
+}
+
+void setDither (int dither)
+{
+	dither24bitImages = dither;
+}
+
+bool getDither ()
+{
+	return dither24bitImages;
+}
diff --git a/engines/sludge/CommonCode/tga.h b/engines/sludge/CommonCode/tga.h
new file mode 100644
index 0000000..e7f6b55
--- /dev/null
+++ b/engines/sludge/CommonCode/tga.h
@@ -0,0 +1,45 @@
+#include <stdio.h>
+
+struct TGAHeader {
+	unsigned char IDBlockSize;
+	unsigned char gotMap;
+	bool compressed;
+	unsigned short int firstPalColour;
+	unsigned short int numPalColours;
+	unsigned char bitsPerPalColour;
+	unsigned short xOrigin;
+	unsigned short yOrigin;
+	unsigned short width;
+	unsigned short height;
+	unsigned char pixelDepth;
+	unsigned char imageDescriptor;
+};
+
+struct palCol {
+	unsigned char r, g, b;
+};
+
+void grabRGBCompressed(FILE *fp, int bpc, unsigned char &r2, unsigned char &g2, unsigned char &b2, palCol thePalette[]);
+void grabRGB(FILE *fp, int bpc, unsigned char &r, unsigned char &g, unsigned char &b, palCol thePalette[]);
+void grabRGBACompressed(FILE *fp, int bpc, unsigned char &r2, unsigned char &g2, unsigned char &b2, unsigned char &a2, palCol thePalette[]);
+void grabRGBA(FILE *fp, int bpc, unsigned char &r, unsigned char &g, unsigned char &b, unsigned char &a, palCol thePalette[]);
+
+unsigned short int makeColour(unsigned char r, unsigned char g, unsigned char b);
+unsigned short readAColour(FILE *fp, int bpc, palCol thePalette[], int x, int y);
+unsigned short readCompressedColour(FILE *fp, int bpc, palCol thePalette[], int x, int y);
+const char *readTGAHeader(TGAHeader &h, FILE *fp, palCol thePalette[]);
+void setDither(int dither);
+bool getDither();
+
+inline unsigned short redValue(unsigned short c) {
+	return (c >> 11) << 3;
+}
+inline unsigned short greenValue(unsigned short c) {
+	return ((c >> 5) & 63) << 2;
+}
+inline unsigned short blueValue(unsigned short c) {
+	return (c & 31) << 3;
+}
+inline int brightness(unsigned short c) {
+	return ((int) redValue(c)) + ((int) greenValue(c)) + ((int) blueValue(c) >> 1);
+}
diff --git a/engines/sludge/CommonCode/utf8.cpp b/engines/sludge/CommonCode/utf8.cpp
new file mode 100644
index 0000000..24d9010
--- /dev/null
+++ b/engines/sludge/CommonCode/utf8.cpp
@@ -0,0 +1,541 @@
+/*
+  Basic UTF-8 manipulation routines
+  by Jeff Bezanson
+  placed in the public domain Fall 2005
+
+  This code is designed to provide the utilities you need to manipulate
+  UTF-8 as an internal string encoding. These functions do not perform the
+  error checking normally needed when handling UTF-8 data, so if you happen
+  to be from the Unicode Consortium you will want to flay me alive.
+  I do this because error checking can be performed at the boundaries (I/O),
+  with these routines reserved for higher performance on data known to be
+  valid.
+*/
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdarg.h>
+#ifdef WIN32
+#include <malloc.h>
+#else
+#include <alloca.h>
+#endif
+
+#include "utf8.h"
+
+static const uint32_t offsetsFromUTF8[6] = {
+    0x00000000UL, 0x00003080UL, 0x000E2080UL,
+    0x03C82080UL, 0xFA082080UL, 0x82082080UL
+};
+
+static const char trailingBytesForUTF8[256] = {
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
+};
+
+/* returns length of next utf-8 sequence */
+int u8_seqlen(char *s)
+{
+    return trailingBytesForUTF8[(unsigned int)(unsigned char)s[0]] + 1;
+}
+
+/* conversions without error checking
+   only works for valid UTF-8, i.e. no 5- or 6-byte sequences
+   srcsz = source size in bytes, or -1 if 0-terminated
+   sz = dest size in # of wide characters
+
+   returns # characters converted
+   dest will always be L'\0'-terminated, even if there isn't enough room
+   for all the characters.
+   if sz = srcsz+1 (i.e. 4*srcsz+4 bytes), there will always be enough space.
+*/
+int u8_toucs(uint32_t *dest, int sz, char *src, int srcsz)
+{
+    uint32_t ch;
+    char *src_end = src + srcsz;
+    int nb;
+    int i=0;
+
+    while (i < sz-1) {
+        nb = trailingBytesForUTF8[(unsigned char)*src];
+        if (srcsz == -1) {
+            if (*src == 0)
+                goto done_toucs;
+        }
+        else {
+            if (src + nb >= src_end)
+                goto done_toucs;
+        }
+        ch = 0;
+        switch (nb) {
+            /* these fall through deliberately */
+        case 3: ch += (unsigned char)*src++; ch <<= 6;
+        case 2: ch += (unsigned char)*src++; ch <<= 6;
+        case 1: ch += (unsigned char)*src++; ch <<= 6;
+        case 0: ch += (unsigned char)*src++;
+        }
+        ch -= offsetsFromUTF8[nb];
+        dest[i++] = ch;
+    }
+ done_toucs:
+    dest[i] = 0;
+    return i;
+}
+
+/* srcsz = number of source characters, or -1 if 0-terminated
+   sz = size of dest buffer in bytes
+
+   returns # characters converted
+   dest will only be '\0'-terminated if there is enough space. this is
+   for consistency; imagine there are 2 bytes of space left, but the next
+   character requires 3 bytes. in this case we could NUL-terminate, but in
+   general we can't when there's insufficient space. therefore this function
+   only NUL-terminates if all the characters fit, and there's space for
+   the NUL as well.
+   the destination string will never be bigger than the source string.
+*/
+int u8_toutf8(char *dest, int sz, uint32_t *src, int srcsz)
+{
+    uint32_t ch;
+    int i = 0;
+    char *dest_end = dest + sz;
+
+    while (srcsz<0 ? src[i]!=0 : i < srcsz) {
+        ch = src[i];
+        if (ch < 0x80) {
+            if (dest >= dest_end)
+                return i;
+            *dest++ = (char)ch;
+        }
+        else if (ch < 0x800) {
+            if (dest >= dest_end-1)
+                return i;
+            *dest++ = (ch>>6) | 0xC0;
+            *dest++ = (ch & 0x3F) | 0x80;
+        }
+        else if (ch < 0x10000) {
+            if (dest >= dest_end-2)
+                return i;
+            *dest++ = (ch>>12) | 0xE0;
+            *dest++ = ((ch>>6) & 0x3F) | 0x80;
+            *dest++ = (ch & 0x3F) | 0x80;
+        }
+        else if (ch < 0x110000) {
+            if (dest >= dest_end-3)
+                return i;
+            *dest++ = (ch>>18) | 0xF0;
+            *dest++ = ((ch>>12) & 0x3F) | 0x80;
+            *dest++ = ((ch>>6) & 0x3F) | 0x80;
+            *dest++ = (ch & 0x3F) | 0x80;
+        }
+        i++;
+    }
+    if (dest < dest_end)
+        *dest = '\0';
+    return i;
+}
+
+int u8_wc_toutf8(char *dest, uint32_t ch)
+{
+    if (ch < 0x80) {
+        dest[0] = (char)ch;
+        return 1;
+    }
+    if (ch < 0x800) {
+        dest[0] = (ch>>6) | 0xC0;
+        dest[1] = (ch & 0x3F) | 0x80;
+        return 2;
+    }
+    if (ch < 0x10000) {
+        dest[0] = (ch>>12) | 0xE0;
+        dest[1] = ((ch>>6) & 0x3F) | 0x80;
+        dest[2] = (ch & 0x3F) | 0x80;
+        return 3;
+    }
+    if (ch < 0x110000) {
+        dest[0] = (ch>>18) | 0xF0;
+        dest[1] = ((ch>>12) & 0x3F) | 0x80;
+        dest[2] = ((ch>>6) & 0x3F) | 0x80;
+        dest[3] = (ch & 0x3F) | 0x80;
+        return 4;
+    }
+    return 0;
+}
+
+/* charnum => byte offset */
+int u8_offset(char *str, int charnum)
+{
+    int offs=0;
+
+    while (charnum > 0 && str[offs]) {
+        (void)(isutf(str[++offs]) || isutf(str[++offs]) ||
+               isutf(str[++offs]) || ++offs);
+        charnum--;
+    }
+    return offs;
+}
+
+/* byte offset => charnum */
+int u8_charnum(char *s, int offset)
+{
+    int charnum = 0, offs=0;
+
+    while (offs < offset && s[offs]) {
+        (void)(isutf(s[++offs]) || isutf(s[++offs]) ||
+               isutf(s[++offs]) || ++offs);
+        charnum++;
+    }
+    return charnum;
+}
+
+/* number of characters */
+int u8_strlen(char *s)
+{
+    int count = 0;
+    int i = 0;
+
+    while (u8_nextchar(s, &i) != 0)
+        count++;
+
+    return count;
+}
+
+/* reads the next utf-8 sequence out of a string, updating an index */
+uint32_t u8_nextchar(const char *s, int *i)
+{
+    uint32_t ch = 0;
+    int sz = 0;
+
+    do {
+        ch <<= 6;
+        ch += (unsigned char)s[(*i)++];
+        sz++;
+    } while (s[*i] && !isutf(s[*i]));
+    ch -= offsetsFromUTF8[sz-1];
+
+    return ch;
+}
+
+void u8_inc(char *s, int *i)
+{
+    (void)(isutf(s[++(*i)]) || isutf(s[++(*i)]) ||
+           isutf(s[++(*i)]) || ++(*i));
+}
+
+void u8_dec(char *s, int *i)
+{
+    (void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) ||
+           isutf(s[--(*i)]) || --(*i));
+}
+
+int octal_digit(char c)
+{
+    return (c >= '0' && c <= '7');
+}
+
+int hex_digit(char c)
+{
+    return ((c >= '0' && c <= '9') ||
+            (c >= 'A' && c <= 'F') ||
+            (c >= 'a' && c <= 'f'));
+}
+
+/* assumes that src points to the character after a backslash
+   returns number of input characters processed */
+int u8_read_escape_sequence(char *str, uint32_t *dest)
+{
+    uint32_t ch;
+    char digs[9]="\0\0\0\0\0\0\0\0";
+    int dno=0, i=1;
+
+    ch = (uint32_t)str[0];    /* take literal character */
+    if (str[0] == 'n')
+        ch = L'\n';
+    else if (str[0] == 't')
+        ch = L'\t';
+    else if (str[0] == 'r')
+        ch = L'\r';
+    else if (str[0] == 'b')
+        ch = L'\b';
+    else if (str[0] == 'f')
+        ch = L'\f';
+    else if (str[0] == 'v')
+        ch = L'\v';
+    else if (str[0] == 'a')
+        ch = L'\a';
+    else if (octal_digit(str[0])) {
+        i = 0;
+        do {
+            digs[dno++] = str[i++];
+        } while (octal_digit(str[i]) && dno < 3);
+        ch = strtol(digs, NULL, 8);
+    }
+    else if (str[0] == 'x') {
+        while (hex_digit(str[i]) && dno < 2) {
+            digs[dno++] = str[i++];
+        }
+        if (dno > 0)
+            ch = strtol(digs, NULL, 16);
+    }
+    else if (str[0] == 'u') {
+        while (hex_digit(str[i]) && dno < 4) {
+            digs[dno++] = str[i++];
+        }
+        if (dno > 0)
+            ch = strtol(digs, NULL, 16);
+    }
+    else if (str[0] == 'U') {
+        while (hex_digit(str[i]) && dno < 8) {
+            digs[dno++] = str[i++];
+        }
+        if (dno > 0)
+            ch = strtol(digs, NULL, 16);
+    }
+    *dest = ch;
+
+    return i;
+}
+
+/* convert a string with literal \uxxxx or \Uxxxxxxxx characters to UTF-8
+   example: u8_unescape(mybuf, 256, "hello\\u220e")
+   note the double backslash is needed if called on a C string literal */
+int u8_unescape(char *buf, int sz, char *src)
+{
+    int c=0, amt;
+    uint32_t ch;
+    char temp[4];
+
+    while (*src && c < sz) {
+        if (*src == '\\') {
+            src++;
+            amt = u8_read_escape_sequence(src, &ch);
+        }
+        else {
+            ch = (uint32_t)*src;
+            amt = 1;
+        }
+        src += amt;
+        amt = u8_wc_toutf8(temp, ch);
+        if (amt > sz-c)
+            break;
+        memcpy(&buf[c], temp, amt);
+        c += amt;
+    }
+    if (c < sz)
+        buf[c] = '\0';
+    return c;
+}
+
+int u8_escape_wchar(char *buf, int sz, uint32_t ch)
+{
+    if (ch == L'\n')
+        return snprintf(buf, sz, "\\n");
+    else if (ch == L'\t')
+        return snprintf(buf, sz, "\\t");
+    else if (ch == L'\r')
+        return snprintf(buf, sz, "\\r");
+    else if (ch == L'\b')
+        return snprintf(buf, sz, "\\b");
+    else if (ch == L'\f')
+        return snprintf(buf, sz, "\\f");
+    else if (ch == L'\v')
+        return snprintf(buf, sz, "\\v");
+    else if (ch == L'\a')
+        return snprintf(buf, sz, "\\a");
+    else if (ch == L'\\')
+        return snprintf(buf, sz, "\\\\");
+    else if (ch < 32 || ch == 0x7f)
+        return snprintf(buf, sz, "\\x%hhX", (unsigned char)ch);
+    else if (ch > 0xFFFF)
+        return snprintf(buf, sz, "\\U%.8X", (uint32_t)ch);
+    else if (ch >= 0x80 && ch <= 0xFFFF)
+        return snprintf(buf, sz, "\\u%.4hX", (unsigned short)ch);
+
+    return snprintf(buf, sz, "%c", (char)ch);
+}
+
+int u8_escape(char *buf, int sz, char *src, int escape_quotes)
+{
+    int c=0, i=0, amt;
+
+    while (src[i] && c < sz) {
+        if (escape_quotes && src[i] == '"') {
+            amt = snprintf(buf, sz - c, "\\\"");
+            i++;
+        }
+        else {
+            amt = u8_escape_wchar(buf, sz - c, u8_nextchar(src, &i));
+        }
+        c += amt;
+        buf += amt;
+    }
+    if (c < sz)
+        *buf = '\0';
+    return c;
+}
+
+char *u8_strchr(char *s, uint32_t ch, int *charn)
+{
+    int i = 0, lasti=0;
+    uint32_t c;
+
+    *charn = 0;
+    while (s[i]) {
+        c = u8_nextchar(s, &i);
+        if (c == ch) {
+            return &s[lasti];
+        }
+        lasti = i;
+        (*charn)++;
+    }
+    return NULL;
+}
+
+char *u8_memchr(char *s, uint32_t ch, size_t sz, int *charn)
+{
+    int i = 0, lasti=0;
+    uint32_t c;
+    int csz;
+
+    *charn = 0;
+    while (i < sz) {
+        c = csz = 0;
+        do {
+            c <<= 6;
+            c += (unsigned char)s[i++];
+            csz++;
+        } while (i < sz && !isutf(s[i]));
+        c -= offsetsFromUTF8[csz-1];
+
+        if (c == ch) {
+            return &s[lasti];
+        }
+        lasti = i;
+        (*charn)++;
+    }
+    return NULL;
+}
+
+int u8_is_locale_utf8(char *locale)
+{
+    /* this code based on libutf8 */
+    const char* cp = locale;
+
+    for (; *cp != '\0' && *cp != '@' && *cp != '+' && *cp != ','; cp++) {
+        if (*cp == '.') {
+            const char* encoding = ++cp;
+            for (; *cp != '\0' && *cp != '@' && *cp != '+' && *cp != ','; cp++)
+                ;
+            if ((cp-encoding == 5 && !strncmp(encoding, "UTF-8", 5))
+                || (cp-encoding == 4 && !strncmp(encoding, "utf8", 4)))
+                return 1; /* it's UTF-8 */
+            break;
+        }
+    }
+    return 0;
+}
+
+int u8_vprintf(char *fmt, va_list ap)
+{
+    int cnt, sz=0;
+    char *buf;
+    uint32_t *wcs;
+
+    sz = 512;
+    buf = (char*)alloca(sz);
+ try_print:
+    cnt = vsnprintf(buf, sz, fmt, ap);
+    if (cnt >= sz) {
+        buf = (char*)alloca(cnt - sz + 1);
+        sz = cnt + 1;
+        goto try_print;
+    }
+    wcs = (uint32_t*)alloca((cnt+1) * sizeof(uint32_t));
+    cnt = u8_toucs(wcs, cnt+1, buf, cnt);
+    printf("%ls", (wchar_t*)wcs);
+    return cnt;
+}
+
+int u8_printf(char *fmt, ...)
+{
+    int cnt;
+    va_list args;
+
+    va_start(args, fmt);
+
+    cnt = u8_vprintf(fmt, args);
+
+    va_end(args);
+    return cnt;
+}
+
+
+// This function checks a string to see if it's valid UTF-8
+// It returns true if the string is valid.
+//
+// based on the valid_utf8 routine from the PCRE library by Philip Hazel
+
+int u8_isvalid(const char *str)
+{
+    const unsigned char *p;
+    unsigned char c;
+    int ab;
+	
+    for (p = (unsigned char*)str; *p; p++) {
+        c = *p;
+        if (c < 128)
+            continue;
+        if ((c & 0xc0) != 0xc0)
+            return 0;
+        ab = trailingBytesForUTF8[c];
+		
+        p++;
+        /* Check top bits in the second byte */
+        if ((*p & 0xc0) != 0x80)
+            return 0;
+		
+        /* Check for overlong sequences for each different length */
+        switch (ab) {
+				/* Check for xx00 000x */
+			case 1:
+				if ((c & 0x3e) == 0) return 0;
+				continue;   /* We know there aren't any more bytes to check */
+				
+				/* Check for 1110 0000, xx0x xxxx */
+			case 2:
+				if (c == 0xe0 && (*p & 0x20) == 0) return 0;
+				break;
+				
+				/* Check for 1111 0000, xx00 xxxx */
+			case 3:
+				if (c == 0xf0 && (*p & 0x30) == 0) return 0;
+				break;
+				
+				/* Check for 1111 1000, xx00 0xxx */
+			case 4:
+				if (c == 0xf8 && (*p & 0x38) == 0) return 0;
+				break;
+				
+				/* Check for leading 0xfe or 0xff,
+				 and then for 1111 1100, xx00 00xx */
+			case 5:
+				if (c == 0xfe || c == 0xff ||
+					(c == 0xfc && (*p & 0x3c) == 0)) return 0;
+				break;
+        }
+		
+        /* Check for valid bytes after the 2nd, if any; all must start 10 */
+        while (--ab > 0) {
+            if ((*(++p) & 0xc0) != 0x80) return 0;
+        }
+    }
+	
+    return 1;
+}
+
diff --git a/engines/sludge/CommonCode/utf8.h b/engines/sludge/CommonCode/utf8.h
new file mode 100644
index 0000000..85989ee
--- /dev/null
+++ b/engines/sludge/CommonCode/utf8.h
@@ -0,0 +1,75 @@
+#include <stdint.h>
+#include <stdarg.h>
+
+/* is c the start of a utf8 sequence? */
+#define isutf(c) (((c)&0xC0)!=0x80)
+
+/* convert UTF-8 data to wide character */
+int u8_toucs(uint32_t *dest, int sz, char *src, int srcsz);
+
+/* the opposite conversion */
+int u8_toutf8(char *dest, int sz, uint32_t *src, int srcsz);
+
+/* single character to UTF-8 */
+int u8_wc_toutf8(char *dest, uint32_t ch);
+
+/* character number to byte offset */
+int u8_offset(char *str, int charnum);
+
+/* byte offset to character number */
+int u8_charnum(char *s, int offset);
+
+/* return next character, updating an index variable */
+uint32_t u8_nextchar(const char *s, int *i);
+
+/* move to next character */
+void u8_inc(char *s, int *i);
+
+/* move to previous character */
+void u8_dec(char *s, int *i);
+
+/* returns length of next utf-8 sequence */
+int u8_seqlen(char *s);
+
+/* assuming src points to the character after a backslash, read an
+   escape sequence, storing the result in dest and returning the number of
+   input characters processed */
+int u8_read_escape_sequence(char *src, uint32_t *dest);
+
+/* given a wide character, convert it to an ASCII escape sequence stored in
+   buf, where buf is "sz" bytes. returns the number of characters output. */
+int u8_escape_wchar(char *buf, int sz, uint32_t ch);
+
+/* convert a string "src" containing escape sequences to UTF-8 */
+int u8_unescape(char *buf, int sz, char *src);
+
+/* convert UTF-8 "src" to ASCII with escape sequences.
+   if escape_quotes is nonzero, quote characters will be preceded by
+   backslashes as well. */
+int u8_escape(char *buf, int sz, char *src, int escape_quotes);
+
+/* utility predicates used by the above */
+int octal_digit(char c);
+int hex_digit(char c);
+
+/* return a pointer to the first occurrence of ch in s, or NULL if not
+   found. character index of found character returned in *charn. */
+char *u8_strchr(char *s, uint32_t ch, int *charn);
+
+/* same as the above, but searches a buffer of a given size instead of
+   a NUL-terminated string. */
+char *u8_memchr(char *s, uint32_t ch, size_t sz, int *charn);
+
+/* count the number of characters in a UTF-8 string */
+int u8_strlen(char *s);
+
+int u8_is_locale_utf8(char *locale);
+
+/* printf where the format string and arguments may be in UTF-8.
+   you can avoid this function and just use ordinary printf() if the current
+   locale is UTF-8. */
+int u8_vprintf(char *fmt, va_list ap);
+int u8_printf(char *fmt, ...);
+
+
+int u8_isvalid(const char *input);
diff --git a/engines/sludge/CommonCode/version.h b/engines/sludge/CommonCode/version.h
new file mode 100644
index 0000000..2b640a0
--- /dev/null
+++ b/engines/sludge/CommonCode/version.h
@@ -0,0 +1,13 @@
+#define MAJOR_VERSION 2
+#define MINOR_VERSION 2
+#define RELEASE_VERSION 1
+#define BUILD_VERSION 208
+#define TEXT_VERSION "2.2.1"
+#define WHOLE_VERSION (MAJOR_VERSION * 256 + MINOR_VERSION) // This version
+#define MINIM_VERSION (1             * 256 + 2)             // Earliest version of games the engine can run
+
+#define COPYRIGHT_TEXT "\251 Hungry Software and contributors 2000-2014"
+
+#define VERSION(a,b)    (a * 256 + b)
+
+extern int gameVersion;
diff --git a/engines/sludge/allfiles.h b/engines/sludge/allfiles.h
new file mode 100644
index 0000000..9478da5
--- /dev/null
+++ b/engines/sludge/allfiles.h
@@ -0,0 +1,32 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef SLUDGE_ALLFILES_H
+#define SLUDGE_ALLFILES_H
+
+#include "common/system.h"
+
+//#define debuggy2 int
+#define IN_THE_CENTRE 65535
+typedef unsigned char byte;
+
+#endif
diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
new file mode 100644
index 0000000..ed71770
--- /dev/null
+++ b/engines/sludge/backdrop.cpp
@@ -0,0 +1,1753 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#if 0
+#if defined __unix__ && !(defined __APPLE__)
+#include <png.h>
+#else
+#include <libpng/png.h>
+#endif
+
+#include <stdlib.h>
+#include <stdint.h>
+
+#if !defined(HAVE_GLES2)
+#include "GLee.h"
+#else
+#include <GLES2/gl2.h>
+#endif
+#endif
+
+#include "allfiles.h"
+#include "debug.h"
+#include "newfatal.h"
+#include "colours.h"
+#include "fileset.h"
+#include "cursors.h"
+#include "backdrop.h"
+#include "language.h"
+#include "moreio.h"
+#include "variable.h"
+#include "zbuffer.h"
+#include "graphics.h"
+#include "line.h"
+#include "people.h"
+#include "talk.h"
+#include "sludger.h"
+#include "statusba.h"
+
+#include "CommonCode/version.h"
+
+extern inputType input;
+
+
+bool freeze();
+void unfreeze(bool);    // Because FREEZE.H needs a load of other includes
+
+#if 0
+GLubyte *backdropTexture = NULL;
+GLuint backdropTextureName = 0;
+bool backdropExists = false;
+GLfloat backdropTexW = 1.0;
+GLfloat backdropTexH = 1.0;
+
+texture lightMap;
+
+GLuint snapshotTextureName = 0;
+#endif
+
+float snapTexW = 1.0;
+float snapTexH = 1.0;
+
+int lightMapMode = LIGHTMAPMODE_PIXEL;
+parallaxLayer *parallaxStuff = NULL;
+int cameraPX = 0, cameraPY = 0;
+
+unsigned int sceneWidth, sceneHeight;
+int lightMapNumber;
+unsigned int currentBlankColour = makeColour(0, 0, 0);
+
+extern int cameraX, cameraY;
+extern float cameraZoom;
+
+void nosnapshot() {
+#if 0
+	deleteTextures(1, &snapshotTextureName);
+	snapshotTextureName = 0;
+#endif
+}
+
+#if ALLOW_FILE
+void saveSnapshot(FILE *fp) {
+	if (snapshotTextureName) {
+		fputc(1, fp);               // 1 for snapshot follows
+		saveCoreHSI(fp, snapshotTextureName, winWidth, winHeight);
+	} else {
+		fputc(0, fp);
+	}
+}
+#endif
+
+bool snapshot() {
+
+	nosnapshot();
+	if (! freeze()) return false;
+#if 0
+	setPixelCoords(true);
+	glGenTextures(1, &snapshotTextureName);
+
+	int w = winWidth;
+	int h = winHeight;
+	if (! NPOT_textures) {
+		w = getNextPOT(winWidth);
+		h = getNextPOT(winHeight);
+		snapTexW = ((double)winWidth) / w;
+		snapTexH = ((double)winHeight) / h;
+	}
+
+	glBindTexture(GL_TEXTURE_2D, snapshotTextureName);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+
+	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0, snapshotTextureName);
+
+	// Render scene
+	glDepthMask(GL_TRUE);
+	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen
+	glDepthMask(GL_FALSE);
+
+	drawBackDrop();                 // Draw the room
+	drawZBuffer(cameraX, cameraY, false);
+
+	glEnable(GL_DEPTH_TEST);
+
+	drawPeople();                   // Then add any moving characters...
+
+	glDisable(GL_DEPTH_TEST);
+
+	viewSpeech();                   // ...and anything being said
+	drawStatusBar();
+	// Copy Our ViewPort To The Texture
+	copyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, viewportOffsetX, viewportOffsetY, winWidth, winHeight, snapshotTextureName);
+
+	setPixelCoords(false);
+#endif
+	unfreeze(false);
+	return true;
+}
+
+#if ALLOW_FILE
+bool restoreSnapshot(FILE *fp) {
+	unsigned int picWidth = get2bytes(fp);
+	unsigned int picHeight = get2bytes(fp);
+
+	if ((picWidth != winWidth) || (picHeight != winHeight))
+		return false;
+
+	unsigned int t1, t2, n;
+	unsigned short c;
+
+	GLubyte *target;
+	if (! NPOT_textures) {
+		picWidth = getNextPOT(picWidth);
+		picHeight = getNextPOT(picHeight);
+		snapTexW = ((double)winWidth) / picWidth;
+		snapTexH = ((double)winHeight) / picHeight;
+	}
+	GLubyte *snapshotTexture = new GLubyte [picHeight * picWidth * 4];
+	if (! snapshotTexture) return fatal("Out of memory while restoring snapshot.");
+
+	for (t2 = 0; t2 < winHeight; t2 ++) {
+		t1 = 0;
+		while (t1 < winWidth) {
+			c = (unsigned short) get2bytes(fp);
+			if (c & 32) {
+				n = fgetc(fp) + 1;
+				c -= 32;
+			} else {
+				n = 1;
+			}
+			while (n --) {
+				target = snapshotTexture + 4 * picWidth * t2 + t1 * 4;
+				target[0] = (GLubyte) redValue(c);
+				target[1] = (GLubyte) greenValue(c);
+				target[2] = (GLubyte) blueValue(c);
+				target[3] = (GLubyte) 255;
+				t1++;
+			}
+		}
+	}
+
+	if (! snapshotTextureName) glGenTextures(1, &snapshotTextureName);
+	glBindTexture(GL_TEXTURE_2D, snapshotTextureName);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+
+	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, snapshotTexture, snapshotTextureName);
+
+	delete snapshotTexture;
+	snapshotTexture = NULL;
+
+	return true;
+}
+#endif
+
+void killBackDrop() {
+#if 0
+	deleteTextures(1, &backdropTextureName);
+	backdropTextureName = 0;
+	backdropExists = false;
+#endif
+}
+
+void killLightMap() {
+#if 0
+	deleteTextures(1, &lightMap.name);
+	lightMap.name = 0;
+	if (lightMap.data) {
+		delete lightMap.data;
+		lightMap.data = NULL;
+	}
+	lightMapNumber = 0;
+#endif
+}
+
+void killParallax() {
+#if 0
+	while (parallaxStuff) {
+
+		parallaxLayer *k = parallaxStuff;
+		parallaxStuff = k -> next;
+
+		// Now kill the image
+		deleteTextures(1, &k -> textureName);
+		delete k -> texture;
+		delete k;
+		k = NULL;
+	}
+#endif
+}
+
+bool reserveBackdrop() {
+	cameraX = 0;
+	cameraY = 0;
+	input.mouseX = (int)((float)input.mouseX * cameraZoom);
+	input.mouseY = (int)((float)input.mouseY * cameraZoom);
+	cameraZoom = 1.0;
+	input.mouseX = (int)((float)input.mouseX / cameraZoom);
+	input.mouseY = (int)((float)input.mouseY / cameraZoom);
+	setPixelCoords(false);
+	int picWidth = sceneWidth;
+	int picHeight = sceneHeight;
+#if 0
+	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
+
+	if (backdropTexture) delete backdropTexture;
+	if (! NPOT_textures) {
+		picWidth = getNextPOT(sceneWidth);
+		picHeight = getNextPOT(sceneHeight);
+		backdropTexW = ((double)sceneWidth) / picWidth;
+		backdropTexH = ((double)sceneHeight) / picHeight;
+	}
+	backdropTexture = new GLubyte [picWidth * picHeight * 4];
+	if (! checkNew(backdropTexture)) return false;
+
+	if (! backdropTextureName) glGenTextures(1, &backdropTextureName);
+	glBindTexture(GL_TEXTURE_2D, backdropTextureName);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+	if (gameSettings.antiAlias < 0) {
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+	} else {
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+	}
+
+	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, backdropTexture, backdropTextureName);
+#endif
+	return true;
+}
+
+bool resizeBackdrop(int x, int y) {
+	killLightMap();
+	killBackDrop();
+	killParallax();
+	killZBuffer();
+	sceneWidth = x;
+	sceneHeight = y;
+	return reserveBackdrop();
+}
+
+void loadBackDrop(int fileNum, int x, int y) {
+	setResourceForFatal(fileNum);
+#if ALLOW_FILE
+	if (! openFileFromNum(fileNum)) {
+		fatal("Can't load overlay image");
+		return;
+	}
+
+	if (! loadHSI(bigDataFile, x, y, false)) {
+		char mess[200];
+		sprintf(mess, "Can't paste overlay image outside scene dimensions\n\nX = %i\nY = %i\nWidth = %i\nHeight = %i", x, y, sceneWidth, sceneHeight);
+		fatal(mess);
+	}
+
+	finishAccess();
+#endif
+	setResourceForFatal(-1);
+}
+
+void mixBackDrop(int fileNum, int x, int y) {
+#if ALLOW_FILE
+	setResourceForFatal(fileNum);
+	if (! openFileFromNum(fileNum)) {
+		fatal("Can't load overlay image");
+		return;
+	}
+
+	if (! mixHSI(bigDataFile, x, y)) {
+		fatal("Can't paste overlay image outside screen dimensions");
+	}
+
+	finishAccess();
+#endif
+	setResourceForFatal(-1);
+}
+
+void blankScreen(int x1, int y1, int x2, int y2) {
+
+	if (y1 < 0) y1 = 0;
+	if (x1 < 0) x1 = 0;
+	if (x2 > (int) sceneWidth) x2 = (int)sceneWidth;
+	if (y2 > (int) sceneHeight) y2 = (int)sceneHeight;
+
+	int picWidth = x2 - x1;
+	int picHeight = y2 - y1;
+#if 0
+	setPixelCoords(true);
+
+	int xoffset = 0;
+	while (xoffset < picWidth) {
+		int w = (picWidth - xoffset < viewportWidth) ? picWidth - xoffset : viewportWidth;
+
+		int yoffset = 0;
+		while (yoffset < picHeight) {
+			int h = (picHeight - yoffset < viewportHeight) ? picHeight - yoffset : viewportHeight;
+
+			// Render the scene
+
+
+
+			const GLfloat vertices[] = {
+				-10.325f, -1.325f, 0.0f,
+				w + 1.325f, -1.325f, 0.0f,
+				-10.325f, h + 1.325f, 0.0f,
+				w + 1.325f, h + 1.325f, 0.0f
+			};
+
+			glUseProgram(shader.color);
+
+			setPMVMatrix(shader.color);
+			setPrimaryColor(redValue(currentBlankColour) / 255.0f, greenValue(currentBlankColour) / 255.0f, blueValue(currentBlankColour) / 255.0f, 1.0f);
+			drawQuad(shader.color, vertices, 0);
+
+			glUseProgram(0);
+
+			// Copy Our ViewPort To The Texture
+			copyTexSubImage2D(GL_TEXTURE_2D, 0, x1 + xoffset, y1 + yoffset, viewportOffsetX, viewportOffsetY, w, h, backdropTextureName);
+
+			yoffset += viewportHeight;
+		}
+		xoffset += viewportWidth;
+	}
+
+	setPixelCoords(false);
+#endif
+}
+
+void hardScroll(int distance) {
+	if (abs(distance) >= sceneHeight) {
+		blankScreen(0, 0, sceneWidth, sceneHeight);
+		return;
+	}
+
+	if (! distance) return;
+#if 0
+	const GLfloat backdropTexCoords[] = {
+		0.0f, 0.0f,
+		backdropTexW, 0.0f,
+		0.0f, backdropTexH,
+		backdropTexW, backdropTexH
+	};
+
+	setPixelCoords(true);
+
+	unsigned int xoffset = 0;
+	while (xoffset < sceneWidth) {
+		int w = (sceneWidth - xoffset < viewportWidth) ? sceneWidth - xoffset : viewportWidth;
+
+		unsigned int yoffset = 0;
+		while (yoffset < sceneHeight) {
+			int h = (sceneHeight - yoffset < viewportHeight) ? sceneHeight - yoffset : viewportHeight;
+
+
+			glClear(GL_COLOR_BUFFER_BIT);   // Clear The Screen
+
+			// Render the backdrop
+			glBindTexture(GL_TEXTURE_2D, backdropTextureName);
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+
+			const GLfloat vertices[] = {
+				(GLfloat) - xoffset, (GLfloat) - distance - yoffset, 0.,
+				(GLfloat)sceneWidth - xoffset, (GLfloat) - distance - yoffset, 0.,
+				(GLfloat) - xoffset, (GLfloat)sceneHeight - distance - yoffset, 0.,
+				(GLfloat)sceneWidth - xoffset, (GLfloat)sceneHeight - distance - yoffset, 0.
+			};
+
+
+			glUseProgram(shader.texture);
+
+			setPMVMatrix(shader.texture);
+
+			drawQuad(shader.texture, vertices, 1, backdropTexCoords);
+
+			glUseProgram(0);
+
+			// Copy Our ViewPort To The Texture
+			copyTexSubImage2D(GL_TEXTURE_2D, 0, xoffset, yoffset, viewportOffsetX, viewportOffsetY, w, h, backdropTextureName);
+
+			yoffset += viewportHeight;
+		}
+		xoffset += viewportWidth;
+	}
+	setPixelCoords(false);
+#endif
+}
+
+void drawVerticalLine(unsigned int x, unsigned int y1, unsigned int y2) {
+	drawLine(x, y1, x, y2);
+}
+
+void drawHorizontalLine(unsigned int x1, unsigned int y, unsigned int x2) {
+	drawLine(x1, y, x2, y);
+}
+
+void darkScreen() {
+	setPixelCoords(true);
+
+	int xoffset = 0;
+	while (xoffset < sceneWidth) {
+		int w = (sceneWidth - xoffset < viewportWidth) ? sceneWidth - xoffset : viewportWidth;
+
+		int yoffset = 0;
+		while (yoffset < sceneHeight) {
+			int h = (sceneHeight - yoffset < viewportHeight) ? sceneHeight - yoffset : viewportHeight;
+
+			// Render the scene - first the old backdrop
+#if 0
+			//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+			glBindTexture(GL_TEXTURE_2D, backdropTextureName);
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+
+			const GLfloat vertices[] = {
+				(GLfloat) - xoffset, (GLfloat) - yoffset, 0.,
+				(GLfloat)sceneWidth - xoffset, (GLfloat) - yoffset, 0.,
+				(GLfloat) - xoffset, (GLfloat)sceneHeight - yoffset, 0.,
+				(GLfloat)sceneWidth - xoffset, (GLfloat)sceneHeight - yoffset, 0.
+			};
+
+			const GLfloat texCoords[] = {
+				0.0f, 0.0f,
+				backdropTexW, 0.0f,
+				0.0f, backdropTexH,
+				backdropTexW, backdropTexH
+			};
+
+
+			glUseProgram(shader.texture);
+
+			setPMVMatrix(shader.texture);
+
+			drawQuad(shader.texture, vertices, 1, texCoords);
+
+			// Then the darkness
+			glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE);
+
+			glEnable(GL_BLEND);
+
+			glUseProgram(shader.color);
+
+			setPMVMatrix(shader.color);
+			setPrimaryColor(0.0f, 0.0f, 0.0f, 0.5f);
+			drawQuad(shader.color, vertices, 0);
+
+			glUseProgram(0);
+
+			glDisable(GL_BLEND);
+			glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+
+			// Copy Our ViewPort To The Texture
+			copyTexSubImage2D(GL_TEXTURE_2D, 0, xoffset, yoffset, viewportOffsetX, viewportOffsetY, w, h, backdropTextureName);
+
+			yoffset += h;
+
+			glClear(GL_COLOR_BUFFER_BIT);
+#endif
+		}
+		xoffset += w;
+	}
+
+
+	setPixelCoords(false);
+}
+
+
+
+inline int sortOutPCamera(int cX, int fX, int sceneMax, int boxMax) {
+	return (fX == 65535) ?
+	       (sceneMax ? ((cX * boxMax) / sceneMax) : 0)
+	       :
+	       ((cX * fX) / 100);
+}
+
+
+void drawBackDrop() {
+#if 0
+	setPrimaryColor(1.0, 1.0, 1.0, 1.0);
+
+	//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
+	glEnable(GL_BLEND);
+
+	glUseProgram(shader.smartScaler);
+	GLuint uniform = glGetUniformLocation(shader.smartScaler, "useLightTexture");
+	if (uniform >= 0) glUniform1i(uniform, 0);
+
+	setPMVMatrix(shader.smartScaler);
+
+	if (gameSettings.antiAlias == 1) {
+		glUniform1i(glGetUniformLocation(shader.smartScaler, "antialias"), 1);
+	} else {
+		glUniform1i(glGetUniformLocation(shader.smartScaler, "antialias"), 0);
+	}
+
+	if (parallaxStuff) {
+		parallaxLayer *ps = parallaxStuff;
+
+		while (ps->next) ps = ps->next;
+
+		while (ps) {
+			ps -> cameraX = sortOutPCamera(cameraX, ps -> fractionX, (int)(sceneWidth - (float)winWidth / cameraZoom), (int)(ps -> width - (float)winWidth / cameraZoom));
+			ps -> cameraY = sortOutPCamera(cameraY, ps -> fractionY, (int)(sceneHeight - (float)winHeight / cameraZoom), (int)(ps -> height - (float)winHeight / cameraZoom));
+			glBindTexture(GL_TEXTURE_2D, ps->textureName);
+
+			float w = (ps->wrapS) ? sceneWidth : ps->width;
+			float h = (ps->wrapT) ? sceneHeight : ps->height;
+			float texw;
+			float texh;
+			if (! NPOT_textures) {
+				texw = (ps->wrapS) ? (float) sceneWidth / ps->width : (float) ps->width / getNextPOT(ps->width);
+				texh = (ps->wrapT) ? (float) sceneHeight / ps->height : (float) ps->height / getNextPOT(ps->height);
+			} else {
+				texw = (ps->wrapS) ? (float) sceneWidth / ps->width : 1.0;
+				texh = (ps->wrapT) ? (float) sceneHeight / ps->height : 1.0;
+			}
+
+			const GLfloat vertices[] = {
+				(GLfloat) - ps -> cameraX, (GLfloat) - ps -> cameraY, 0.1f,
+				w - ps -> cameraX, (GLfloat) - ps -> cameraY, 0.1f,
+				(GLfloat) - ps -> cameraX, h - ps -> cameraY, 0.1f,
+				w - ps -> cameraX, h - ps -> cameraY, 0.1f
+			};
+
+			const GLfloat texCoords[] = {
+				0.0f, 0.0f,
+				texw, 0.0f,
+				0.0f, texh,
+				texw, texh
+			};
+			drawQuad(shader.smartScaler, vertices, 1, texCoords);
+
+			ps = ps -> prev;
+		}
+	}
+
+	glBindTexture(GL_TEXTURE_2D, backdropTextureName);
+
+	const GLfloat backdropTexCoords[] = {
+		0.0f, 0.0f,
+		backdropTexW, 0.0f,
+		0.0f, backdropTexH,
+		backdropTexW, backdropTexH
+	};
+
+	const GLfloat vertices[] = {
+		(GLfloat) - cameraX, (GLfloat) - cameraY, 0.,
+		(GLfloat)sceneWidth - (GLfloat)cameraX, (GLfloat) - cameraY, 0.,
+		(GLfloat) - cameraX, (GLfloat)sceneHeight - (GLfloat)cameraY, 0.,
+		(GLfloat)sceneWidth - (GLfloat)cameraX, (GLfloat)sceneHeight - (GLfloat)cameraY, 0.
+	};
+
+	drawQuad(shader.smartScaler, vertices, 1, backdropTexCoords);
+
+	glDisable(GL_BLEND);
+
+	glUseProgram(0);
+#endif
+}
+
+bool loadLightMap(int v) {
+	int newPicWidth, newPicHeight;
+#if ALLOW_FILE
+	setResourceForFatal(v);
+	if (! openFileFromNum(v)) return fatal("Can't open light map.");
+	long file_pointer = ftell(bigDataFile);
+
+	png_structp png_ptr;
+	png_infop info_ptr, end_info;
+
+
+	int fileIsPNG = true;
+
+	// Is this a PNG file?
+
+	char tmp[10];
+	size_t bytes_read = fread(tmp, 1, 8, bigDataFile);
+	if (bytes_read != 8 && ferror(bigDataFile)) {
+		debugOut("Reading error in loadLightMap.\n");
+	}
+
+	if (png_sig_cmp((png_byte *) tmp, 0, 8)) {
+		// No, it's old-school HSI
+		fileIsPNG = false;
+		fseek(bigDataFile, file_pointer, SEEK_SET);
+
+		newPicWidth = lightMap.w = get2bytes(bigDataFile);
+		newPicHeight = lightMap.h = get2bytes(bigDataFile);
+	} else {
+		// Read the PNG header
+
+		png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+		if (!png_ptr) {
+			return false;
+		}
+
+		info_ptr = png_create_info_struct(png_ptr);
+		if (!info_ptr) {
+			png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
+			return false;
+		}
+
+		end_info = png_create_info_struct(png_ptr);
+		if (!end_info) {
+			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
+			return false;
+		}
+		png_init_io(png_ptr, bigDataFile);      // Tell libpng which file to read
+		png_set_sig_bytes(png_ptr, 8);  // 8 bytes already read
+
+		png_read_info(png_ptr, info_ptr);
+
+		png_uint_32 width, height;
+		int bit_depth, color_type, interlace_type, compression_type, filter_method;
+		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
+
+		newPicWidth = lightMap.w = width;
+		newPicHeight = lightMap.h = height;
+
+		if (bit_depth < 8) png_set_packing(png_ptr);
+		png_set_expand(png_ptr);
+		if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr);
+		if (bit_depth == 16) png_set_strip_16(png_ptr);
+
+		png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER);
+
+		png_read_update_info(png_ptr, info_ptr);
+		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
+
+		//int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
+
+	}
+
+	if (lightMapMode == LIGHTMAPMODE_HOTSPOT) {
+		if (lightMap.w != sceneWidth || lightMap.h != sceneHeight) {
+			return fatal("Light map width and height don't match scene width and height. That is required for lightmaps in HOTSPOT mode.");
+		}
+	}
+
+	if (! NPOT_textures) {
+		newPicWidth = getNextPOT(lightMap.w);
+		newPicHeight = getNextPOT(lightMap.h);
+		lightMap.texW = (double) lightMap.w / newPicWidth;
+		lightMap.texH = (double) lightMap.h / newPicHeight;
+	} else {
+		lightMap.texW = 1.0;
+		lightMap.texH = 1.0;
+	}
+
+	killLightMap();
+	lightMapNumber = v;
+#if 0
+	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
+#endif
+	if (lightMap.data) delete [] lightMap.data;
+
+	lightMap.data = new GLubyte [newPicWidth * newPicHeight * 4];
+	if (! lightMap.data) {
+		return fatal("Out of memory loading light map.");
+	}
+
+	int t1, t2, n;
+	unsigned short c;
+	GLubyte *target;
+
+	if (fileIsPNG) {
+		unsigned char *row_pointers[lightMap.h];
+		for (int i = 0; i < lightMap.h; i++)
+			row_pointers[i] = lightMap.data + 4 * i * newPicWidth;
+
+		png_read_image(png_ptr, (png_byte **) row_pointers);
+		png_read_end(png_ptr, NULL);
+		png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
+	} else {
+
+		for (t2 = 0; t2 < lightMap.h; t2 ++) {
+			t1 = 0;
+			while (t1 < lightMap.w) {
+				c = (unsigned short) get2bytes(bigDataFile);
+				if (c & 32) {
+					n = fgetc(bigDataFile) + 1;
+					c -= 32;
+				} else {
+					n = 1;
+				}
+				while (n --) {
+					target = lightMap.data + 4 * newPicWidth * t2 + t1 * 4;
+					target[0] = (GLubyte) redValue(c);
+					target[1] = (GLubyte) greenValue(c);
+					target[2] = (GLubyte) blueValue(c);
+					target[3] = (GLubyte) 255;
+					t1++;
+				}
+			}
+		}
+	}
+#if 0
+	if (! lightMap.name) glGenTextures(1, &lightMap.name);
+	glBindTexture(GL_TEXTURE_2D, lightMap.name);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+#endif
+	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, newPicWidth, newPicHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, lightMap.data, lightMap.name);
+
+	finishAccess();
+
+#endif
+	setResourceForFatal(-1);
+
+	return true;
+}
+
+void reloadParallaxTextures() {
+#if 0
+	parallaxLayer *nP = parallaxStuff;
+	if (! nP) return;
+
+	while (nP) {
+		//fprintf (stderr, "Reloading parallax. (%d, %d) ", nP->width, nP->height);
+		nP->textureName = 0;
+
+		glGenTextures(1, &nP->textureName);
+		glBindTexture(GL_TEXTURE_2D, nP->textureName);
+		if (nP -> wrapS)
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+		else
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+		if (nP -> wrapT)
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+		else
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+
+		if (gameSettings.antiAlias < 0) {
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+		} else {
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+		}
+
+		if (! NPOT_textures) {
+			texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, getNextPOT(nP->width), getNextPOT(nP->height), 0, GL_RGBA, GL_UNSIGNED_BYTE, nP->texture, nP->textureName);
+		} else {
+			texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, nP->width, nP->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nP->texture, nP->textureName);
+		}
+
+		nP = nP->next;
+	}
+#endif
+}
+
+bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY) {
+
+#if ALLOW_FILE
+	setResourceForFatal(v);
+	if (! openFileFromNum(v)) return fatal("Can't open parallax image");
+
+	parallaxLayer *nP = new parallaxLayer;
+	if (! checkNew(nP)) return false;
+
+	nP -> next = parallaxStuff;
+	parallaxStuff = nP;
+	if (nP -> next) {
+		nP -> next -> prev = nP;
+	}
+	nP -> prev = NULL;
+
+	int picWidth;
+	int picHeight;
+
+	long file_pointer = ftell(bigDataFile);
+
+	png_structp png_ptr;
+	png_infop info_ptr, end_info;
+
+
+	int fileIsPNG = true;
+
+	// Is this a PNG file?
+
+	char tmp[10];
+	size_t bytes_read = fread(tmp, 1, 8, bigDataFile);
+	if (bytes_read != 8 && ferror(bigDataFile)) {
+		debugOut("Reading error in loadParallax.\n");
+	}
+	if (png_sig_cmp((png_byte *) tmp, 0, 8)) {
+		// No, it's old-school HSI
+		fileIsPNG = false;
+		fseek(bigDataFile, file_pointer, SEEK_SET);
+
+		picWidth = nP -> width = get2bytes(bigDataFile);
+		picHeight = nP -> height = get2bytes(bigDataFile);
+	} else {
+		// Read the PNG header
+
+		png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+		if (!png_ptr) {
+			return false;
+		}
+
+		info_ptr = png_create_info_struct(png_ptr);
+		if (!info_ptr) {
+			png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
+			return false;
+		}
+
+		end_info = png_create_info_struct(png_ptr);
+		if (!end_info) {
+			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
+			return false;
+		}
+		png_init_io(png_ptr, bigDataFile);      // Tell libpng which file to read
+		png_set_sig_bytes(png_ptr, 8);  // 8 bytes already read
+
+		png_read_info(png_ptr, info_ptr);
+
+		png_uint_32 width, height;
+		int bit_depth, color_type, interlace_type, compression_type, filter_method;
+		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
+
+		picWidth = nP -> width = width;
+		picHeight = nP -> height = height;
+
+		if (bit_depth < 8) png_set_packing(png_ptr);
+		png_set_expand(png_ptr);
+		if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr);
+		if (bit_depth == 16) png_set_strip_16(png_ptr);
+
+		png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER);
+
+		png_read_update_info(png_ptr, info_ptr);
+		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
+
+		//int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
+
+	}
+
+	if (! NPOT_textures) {
+		picWidth = getNextPOT(picWidth);
+		picHeight = getNextPOT(picHeight);
+	}
+
+	nP -> fileNum = v;
+	nP -> fractionX = fracX;
+	nP -> fractionY = fracY;
+
+	if (fracX == 65535) {
+		nP -> wrapS = false;
+		if (nP -> width < winWidth) {
+			fatal("For AUTOFIT parallax backgrounds, the image must be at least as wide as the game window/screen.");
+			return false;
+		}
+	} else {
+		nP -> wrapS = true;
+	}
+
+	if (fracY == 65535) {
+		nP -> wrapT = false;
+		if (nP -> height < winHeight) {
+			fatal("For AUTOFIT parallax backgrounds, the image must be at least as tall as the game window/screen.");
+			return false;
+		}
+	} else {
+		nP -> wrapT = true;
+	}
+
+	nP -> texture = new GLubyte [picHeight * picWidth * 4];
+	if (! checkNew(nP -> texture)) return false;
+
+	if (fileIsPNG) {
+		unsigned char *row_pointers[nP -> height];
+		for (int i = 0; i < nP -> height; i++)
+			row_pointers[i] = nP -> texture + 4 * i * picWidth;
+
+		png_read_image(png_ptr, (png_byte **) row_pointers);
+		png_read_end(png_ptr, NULL);
+		png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
+	} else {
+
+		int t1, t2, n;
+		unsigned short c;
+		GLubyte *target;
+
+		for (t2 = 0; t2 < nP -> height; t2 ++) {
+			t1 = 0;
+			while (t1 < nP -> width) {
+				c = (unsigned short) get2bytes(bigDataFile);
+				if (c & 32) {
+					n = fgetc(bigDataFile) + 1;
+					c -= 32;
+				} else {
+					n = 1;
+				}
+				while (n--) {
+					target = nP -> texture + 4 * picWidth * t2 + t1 * 4;
+					if (c == 63519 || c == 2015) {
+						target[0] = (GLubyte) 0;
+						target[1] = (GLubyte) 0;
+						target[2] = (GLubyte) 0;
+						target[3] = (GLubyte) 0;
+					} else {
+						target[0] = (GLubyte) redValue(c);
+						target[1] = (GLubyte) greenValue(c);
+						target[2] = (GLubyte) blueValue(c);
+						target[3] = (GLubyte) 255;
+					}
+					t1 ++;
+				}
+			}
+		}
+	}
+
+	glGenTextures(1, &nP->textureName);
+	glBindTexture(GL_TEXTURE_2D, nP->textureName);
+	if (nP -> wrapS)
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+	else
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+	if (nP -> wrapT)
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+	else
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+
+	if (gameSettings.antiAlias < 0) {
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+	} else {
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+	}
+
+	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, nP->texture, nP->textureName);
+
+	finishAccess();
+#endif
+	setResourceForFatal(-1);
+	return true;
+}
+
+extern int viewportOffsetX, viewportOffsetY;
+
+#if ALLOW_FILE
+bool loadHSI(FILE *fp, int x, int y, bool reserve) {
+
+	int t1, t2, n;
+	unsigned short c;
+	GLubyte *target;
+	int32_t transCol = reserve ? -1 : 63519;
+	int picWidth;
+	int picHeight;
+	int realPicWidth, realPicHeight;
+	long file_pointer = ftell(fp);
+
+	png_structp png_ptr;
+	png_infop info_ptr, end_info;
+
+
+	int fileIsPNG = true;
+
+	// Is this a PNG file?
+
+	char tmp[10];
+	size_t bytes_read = fread(tmp, 1, 8, fp);
+	if (bytes_read != 8 && ferror(fp)) {
+		debugOut("Reading error in loadHSI.\n");
+	}
+	if (png_sig_cmp((png_byte *) tmp, 0, 8)) {
+		// No, it's old-school HSI
+		fileIsPNG = false;
+		fseek(fp, file_pointer, SEEK_SET);
+
+		picWidth = realPicWidth = get2bytes(fp);
+		picHeight = realPicHeight = get2bytes(fp);
+	} else {
+		// Read the PNG header
+
+		png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+		if (!png_ptr) {
+			return false;
+		}
+
+		info_ptr = png_create_info_struct(png_ptr);
+		if (!info_ptr) {
+			png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
+			return false;
+		}
+
+		end_info = png_create_info_struct(png_ptr);
+		if (!end_info) {
+			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
+			return false;
+		}
+		png_init_io(png_ptr, fp);       // Tell libpng which file to read
+		png_set_sig_bytes(png_ptr, 8);  // 8 bytes already read
+
+		png_read_info(png_ptr, info_ptr);
+
+		png_uint_32 width, height;
+		int bit_depth, color_type, interlace_type, compression_type, filter_method;
+		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
+
+		picWidth = realPicWidth = width;
+		picHeight = realPicHeight = height;
+
+		if (bit_depth < 8) png_set_packing(png_ptr);
+		png_set_expand(png_ptr);
+		if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr);
+		if (bit_depth == 16) png_set_strip_16(png_ptr);
+
+		png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER);
+
+		png_read_update_info(png_ptr, info_ptr);
+		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
+
+		//int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
+
+	}
+
+
+	GLfloat texCoordW = 1.0;
+	GLfloat texCoordH = 1.0;
+	if (! NPOT_textures) {
+		picWidth = getNextPOT(picWidth);
+		picHeight = getNextPOT(picHeight);
+		texCoordW = ((double)realPicWidth) / picWidth;
+		texCoordH = ((double)realPicHeight) / picHeight;
+	}
+
+	if (reserve) {
+		if (! resizeBackdrop(realPicWidth, realPicHeight)) return false;
+	}
+
+	if (x == IN_THE_CENTRE) x = (sceneWidth - realPicWidth) >> 1;
+	if (y == IN_THE_CENTRE) y = (sceneHeight - realPicHeight) >> 1;
+	if (x < 0 || x + realPicWidth > sceneWidth || y < 0 || y + realPicHeight > sceneHeight) return false;
+
+	if (fileIsPNG) {
+		unsigned char *row_pointers[realPicHeight];
+		for (int i = 0; i < realPicHeight; i++)
+			row_pointers[i] = backdropTexture + 4 * i * picWidth;
+
+		png_read_image(png_ptr, (png_byte **) row_pointers);
+		png_read_end(png_ptr, NULL);
+		png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
+	} else {
+		for (t2 = 0; t2 < realPicHeight; t2 ++) {
+			t1 = 0;
+			while (t1 < realPicWidth) {
+				c = (unsigned short) get2bytes(fp);
+				if (c & 32) {
+					n = fgetc(fp) + 1;
+					c -= 32;
+				} else {
+					n = 1;
+				}
+				while (n --) {
+					target = backdropTexture + 4 * picWidth * t2 + t1 * 4;
+					if (c == transCol || c == 2015) {
+						target[0] = (GLubyte) 0;
+						target[1] = (GLubyte) 0;
+						target[2] = (GLubyte) 0;
+						target[3] = (GLubyte) 0;
+					} else {
+						target[0] = (GLubyte) redValue(c);
+						target[1] = (GLubyte) greenValue(c);
+						target[2] = (GLubyte) blueValue(c);
+						target[3] = (GLubyte) 255;
+					}
+					t1++;
+				}
+			}
+		}
+	}
+
+	GLuint tmpTex;
+#if 0
+	glGenTextures(1, &tmpTex);
+	glBindTexture(GL_TEXTURE_2D, tmpTex);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+	if (gameSettings.antiAlias < 0) {
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+	} else {
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+	}
+#endif
+	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, backdropTexture, tmpTex);
+
+
+	//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+
+
+	float btx1;
+	float btx2;
+	float bty1;
+	float bty2;
+	if (! NPOT_textures) {
+		btx1 = backdropTexW * x / sceneWidth;
+		btx2 = backdropTexW * (x + realPicWidth) / sceneWidth;
+		bty1 = backdropTexH * y / sceneHeight;
+		bty2 = backdropTexH * (y + realPicHeight) / sceneHeight;
+	} else {
+		btx1 = (float) x / sceneWidth;
+		btx2 = (float)(x + realPicWidth) / sceneWidth;
+		bty1 = (float) y / sceneHeight;
+		bty2 = (float)(y + realPicHeight) / sceneHeight;
+	}
+
+	const GLfloat btexCoords[] = {
+		btx1, bty1,
+		btx2, bty1,
+		btx1, bty2,
+		btx2, bty2
+	};
+
+	setPixelCoords(true);
+
+	int xoffset = 0;
+	while (xoffset < realPicWidth) {
+		int w = (realPicWidth - xoffset < viewportWidth) ? realPicWidth - xoffset : viewportWidth;
+
+		int yoffset = 0;
+		while (yoffset < realPicHeight) {
+			int h = (realPicHeight - yoffset < viewportHeight) ? realPicHeight - yoffset : viewportHeight;
+#if 0
+			glClear(GL_COLOR_BUFFER_BIT);   // Clear The Screen
+#endif
+			const GLfloat vertices[] = {
+				(GLfloat) - xoffset, (GLfloat) - yoffset, 0.,
+				(GLfloat)realPicWidth - xoffset, (GLfloat) - yoffset, 0.,
+				(GLfloat) - xoffset, (GLfloat) - yoffset + realPicHeight, 0.,
+				(GLfloat)realPicWidth - xoffset, (GLfloat) - yoffset + realPicHeight, 0.
+			};
+
+			const GLfloat texCoords[] = {
+				0.0f, 0.0f,
+				texCoordW, 0.0f,
+				0.0f, texCoordH,
+				texCoordW, texCoordH
+			};
+
+			if (backdropExists) {
+#if 0
+				// Render the sprite to the backdrop
+				// (using mulitexturing, so the old backdrop is seen where alpha < 1.0)
+				glActiveTexture(GL_TEXTURE2);
+				glBindTexture(GL_TEXTURE_2D, backdropTextureName);
+				glActiveTexture(GL_TEXTURE0);
+
+				glUseProgram(shader.paste);
+				GLint uniform = glGetUniformLocation(shader.paste, "useLightTexture");
+				if (uniform >= 0) glUniform1i(uniform, 0); // No lighting
+#endif
+				setPMVMatrix(shader.paste);
+
+				setPrimaryColor(1.0, 1.0, 1.0, 1.0);
+#if 0
+				glBindTexture(GL_TEXTURE_2D, tmpTex);
+				//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
+#endif
+				drawQuad(shader.paste, vertices, 3, texCoords, NULL, btexCoords);
+#if 0
+				glUseProgram(0);
+#endif
+			} else {
+				// It's all new - nothing special to be done.
+
+#if 0
+				glUseProgram(shader.texture);
+#endif
+				setPMVMatrix(shader.texture);
+#if 0
+				glBindTexture(GL_TEXTURE_2D, tmpTex);
+#endif
+				setPrimaryColor(1.0, 0.0, 0.0, 0.0);
+
+				drawQuad(shader.texture, vertices, 1, texCoords);
+
+#if 0
+				glUseProgram(0);
+#endif
+			}
+
+			// Copy Our ViewPort To The Texture
+			copyTexSubImage2D(GL_TEXTURE_2D, 0, x + xoffset, y + yoffset, viewportOffsetX, viewportOffsetY, w, h, backdropTextureName);
+
+			yoffset += viewportHeight;
+		}
+
+		xoffset += viewportWidth;
+	}
+	deleteTextures(1, &tmpTex);
+
+	setPixelCoords(false);
+
+	backdropExists = true;
+	return true;
+}
+
+bool mixHSI(FILE *fp, int x, int y) {
+	int realPicWidth, realPicHeight;
+	int picWidth;
+	int picHeight;
+
+	long file_pointer = ftell(fp);
+
+	png_structp png_ptr;
+	png_infop info_ptr, end_info;
+
+
+	int fileIsPNG = true;
+
+	// Is this a PNG file?
+	char tmp[10];
+	size_t bytes_read = fread(tmp, 1, 8, fp);
+	if (bytes_read != 8 && ferror(fp)) {
+		debugOut("Reading error in mixHSI.\n");
+	}
+	if (png_sig_cmp((png_byte *) tmp, 0, 8)) {
+		// No, it's old-school HSI
+		fileIsPNG = false;
+		fseek(fp, file_pointer, SEEK_SET);
+
+		picWidth = realPicWidth = get2bytes(fp);
+		picHeight = realPicHeight = get2bytes(fp);
+	} else {
+		// Read the PNG header
+
+		png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+		if (!png_ptr) {
+			return false;
+		}
+
+		info_ptr = png_create_info_struct(png_ptr);
+		if (!info_ptr) {
+			png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
+			return false;
+		}
+
+		end_info = png_create_info_struct(png_ptr);
+		if (!end_info) {
+			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
+			return false;
+		}
+		png_init_io(png_ptr, fp);       // Tell libpng which file to read
+		png_set_sig_bytes(png_ptr, 8);  // 8 bytes already read
+
+		png_read_info(png_ptr, info_ptr);
+
+		png_uint_32 width, height;
+		int bit_depth, color_type, interlace_type, compression_type, filter_method;
+		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
+
+		picWidth = realPicWidth = width;
+		picHeight = realPicHeight = height;
+
+		if (bit_depth < 8) png_set_packing(png_ptr);
+		png_set_expand(png_ptr);
+		if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr);
+		if (bit_depth == 16) png_set_strip_16(png_ptr);
+
+		png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER);
+
+		png_read_update_info(png_ptr, info_ptr);
+		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
+
+		//int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
+
+	}
+
+	if (x == IN_THE_CENTRE) x = (sceneWidth - realPicWidth) >> 1;
+	if (y == IN_THE_CENTRE) y = (sceneHeight - realPicHeight) >> 1;
+	if (x < 0 || x + realPicWidth > sceneWidth || y < 0 || y + realPicHeight > sceneHeight) return false;
+
+	float btx1, tx1;
+	float btx2, tx2;
+	float bty1, ty1;
+	float bty2, ty2;
+
+	if (! NPOT_textures) {
+		tx1 = 0.0;
+		ty1 = 0.0;
+		tx2 = ((double)picWidth) / getNextPOT(picWidth);
+		ty2 = ((double)picHeight) / getNextPOT(picHeight);
+		picWidth = getNextPOT(picWidth);
+		picHeight = getNextPOT(picHeight);
+		btx1 = backdropTexW * x / sceneWidth;
+		btx2 = backdropTexW * (x + realPicWidth) / sceneWidth;
+		bty1 = backdropTexH * y / sceneHeight;
+		bty2 = backdropTexH * (y + realPicHeight) / sceneHeight;
+	} else {
+		tx1 = 0.0;
+		ty1 = 0.0;
+		tx2 = 1.0;
+		ty2 = 1.0;
+		btx1 = (float) x / sceneWidth;
+		btx2 = (float)(x + picWidth) / sceneWidth;
+		bty1 = (float) y / sceneHeight;
+		bty2 = (float)(y + picHeight) / sceneHeight;
+	}
+
+	const GLfloat texCoords[] = {
+		tx1, ty1,
+		tx2, ty1,
+		tx1, ty2,
+		tx2, ty2
+	};
+
+	const GLfloat btexCoords[] = {
+		btx1, bty1,
+		btx2, bty1,
+		btx1, bty2,
+		btx2, bty2
+	};
+
+	int t1, t2, n;
+	unsigned short c;
+	GLubyte *target;
+	int32_t transCol = 63519;
+
+
+	if (fileIsPNG) {
+		unsigned char *row_pointers[realPicHeight];
+		for (int i = 0; i < realPicHeight; i++)
+			row_pointers[i] = backdropTexture + 4 * i * picWidth;
+
+		png_read_image(png_ptr, (png_byte **) row_pointers);
+		png_read_end(png_ptr, NULL);
+		png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
+	} else {
+		for (t2 = 0; t2 < realPicHeight; t2 ++) {
+			t1 = 0;
+			while (t1 < realPicWidth) {
+				c = (unsigned short) get2bytes(fp);
+				if (c & 32) {
+					n = fgetc(fp) + 1;
+					c -= 32;
+				} else {
+					n = 1;
+				}
+				while (n --) {
+					target = backdropTexture + 4 * picWidth * t2 + t1 * 4;
+					if (c == transCol || c == 2015) {
+						target[0] = (GLubyte) 0;
+						target[1] = (GLubyte) 0;
+						target[2] = (GLubyte) 0;
+						target[3] = (GLubyte) 0;
+					} else {
+						target[0] = (GLubyte) redValue(c);
+						target[1] = (GLubyte) greenValue(c);
+						target[2] = (GLubyte) blueValue(c);
+						target[3] = (GLubyte) 255;
+					}
+					t1++;
+				}
+			}
+		}
+	}
+
+	GLuint tmpTex;
+#if 0
+	glGenTextures(1, &tmpTex);
+	glBindTexture(GL_TEXTURE_2D, tmpTex);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+	if (gameSettings.antiAlias < 0) {
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+	} else {
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+	}
+#endif
+	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, backdropTexture, tmpTex);
+
+
+	//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+
+	setPixelCoords(true);
+
+
+	int xoffset = 0;
+	while (xoffset < realPicWidth) {
+		int w = (realPicWidth - xoffset < viewportWidth) ? realPicWidth - xoffset : viewportWidth;
+
+		int yoffset = 0;
+		while (yoffset < realPicHeight) {
+			int h = (realPicHeight - yoffset < viewportHeight) ? realPicHeight - yoffset : viewportHeight;
+#if 0
+			glClear(GL_COLOR_BUFFER_BIT);   // Clear The Screen
+
+			// Render the sprite to the backdrop
+			// (using mulitexturing, so the backdrop is seen where alpha < 1.0)
+			glActiveTexture(GL_TEXTURE2);
+			glBindTexture(GL_TEXTURE_2D, backdropTextureName);
+			glActiveTexture(GL_TEXTURE0);
+
+			glUseProgram(shader.paste);
+			GLint uniform = glGetUniformLocation(shader.paste, "useLightTexture");
+			if (uniform >= 0) glUniform1i(uniform, 0); // No lighting
+#endif
+			setPMVMatrix(shader.paste);
+
+			setPrimaryColor(1.0, 1.0, 1.0, 0.5);
+#if 0
+			glBindTexture(GL_TEXTURE_2D, tmpTex);
+			//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
+#endif
+			const GLfloat vertices[] = {
+				(GLfloat) - xoffset, (GLfloat) - yoffset, 0.,
+				(GLfloat)realPicWidth - xoffset, (GLfloat) - yoffset, 0.,
+				(GLfloat) - xoffset, (GLfloat) - yoffset + realPicHeight, 0.,
+				(GLfloat)realPicWidth - xoffset, (GLfloat) - yoffset + realPicHeight, 0.
+			};
+
+			drawQuad(shader.paste, vertices, 3, texCoords, NULL, btexCoords);
+#if 0
+			// Copy Our ViewPort To The Texture
+			glUseProgram(0);
+#endif
+			copyTexSubImage2D(GL_TEXTURE_2D, 0, (int)((x < 0) ? xoffset : x + xoffset), (int)((y < 0) ? yoffset : y + yoffset), (int)((x < 0) ? viewportOffsetX - x : viewportOffsetX), (int)((y < 0) ? viewportOffsetY - y : viewportOffsetY), w, h, backdropTextureName);
+
+			yoffset += viewportHeight;
+		}
+
+		xoffset += viewportWidth;
+	}
+	deleteTextures(1, &tmpTex);
+	setPixelCoords(false);
+	return true;
+}
+
+void saveCorePNG(FILE *writer, GLuint texture, int w, int h) {
+	GLint tw, th;
+#if 0
+	glBindTexture(GL_TEXTURE_2D, texture);
+#endif
+	getTextureDimensions(texture, &tw, &th);
+
+	GLubyte *image = new GLubyte [tw * th * 4];
+	if (! checkNew(image)) return;
+#if 0
+	glPixelStorei(GL_PACK_ALIGNMENT, 1);
+//	glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
+#endif
+#ifdef HAVE_GLES2
+#if 0
+	GLuint old_fbo, new_fbo;
+	GLint old_vp[4];
+	glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint *)&old_fbo);
+	glGetIntegerv(GL_VIEWPORT, old_vp);
+	glGenFramebuffers(1, &new_fbo);
+	glBindFramebuffer(GL_FRAMEBUFFER, new_fbo);
+	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
+	glViewport(0, 0, tw, th);
+	glReadPixels(0, 0, tw, th, GL_RGBA, GL_UNSIGNED_BYTE, image);
+	glBindFramebuffer(GL_FRAMEBUFFER, old_fbo);
+	glViewport(old_vp[0], old_vp[1], old_vp[2], old_vp[3]);
+	glDeleteFramebuffers(1, &new_fbo);
+#endif
+#else
+	setPixelCoords(true);
+
+
+	//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+
+	const GLfloat texCoords[] = {
+		0.0f, 0.0f,
+		1.0f, 0.0f,
+		0.0f, 1.0f,
+		1.0f, 1.0f
+	};
+
+	int xoffset = 0;
+	while (xoffset < tw) {
+		int w = (tw - xoffset < viewportWidth) ? tw - xoffset : viewportWidth;
+
+		int yoffset = 0;
+		while (yoffset < th) {
+			int h = (th - yoffset < viewportHeight) ? th - yoffset : viewportHeight;
+#if 0
+			glClear(GL_COLOR_BUFFER_BIT);   // Clear The Screen
+#endif
+			const GLfloat vertices[] = {
+				(GLfloat) - xoffset, (GLfloat) - yoffset, 0.,
+				(GLfloat)tw - xoffset, (GLfloat) - yoffset, 0.,
+				(GLfloat) - xoffset, (GLfloat) - yoffset + th, 0.,
+				(GLfloat)tw - xoffset, (GLfloat) - yoffset + th, 0.
+			};
+
+#if 0
+			glUseProgram(shader.texture);
+#endif
+			setPMVMatrix(shader.texture);
+
+			drawQuad(shader.texture, vertices, 1, texCoords);
+#if 0
+			glUseProgram(0);
+
+			for (int i = 0; i < h; i++)   {
+				glReadPixels(viewportOffsetX, viewportOffsetY + i, w, 1, GL_RGBA, GL_UNSIGNED_BYTE, image + xoffset * 4 + (yoffset + i) * 4 * tw);
+			}
+#endif
+			yoffset += viewportHeight;
+		}
+
+		xoffset += viewportWidth;
+	}
+	setPixelCoords(false);
+#endif
+
+
+
+	png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+	if (!png_ptr) {
+		fatal("Error saving image!");
+		return;
+	}
+
+	png_infop info_ptr = png_create_info_struct(png_ptr);
+	if (!info_ptr) {
+		png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
+		fatal("Error saving image!");
+		return;
+	}
+
+	png_init_io(png_ptr, writer);
+
+	png_set_IHDR(png_ptr, info_ptr, w, h,
+	             8, PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
+
+	unsigned char *row_pointers[h];
+
+	for (int i = 0; i < h; i++) {
+		row_pointers[i] = image + 4 * i * tw;
+	}
+
+	png_set_rows(png_ptr, info_ptr, row_pointers);
+	png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
+
+	delete [] image;
+	image = NULL;
+}
+
+void saveCoreHSI(FILE *writer, GLuint texture, int w, int h) {
+
+	GLint tw, th;
+#if 0
+	glBindTexture(GL_TEXTURE_2D, texture);
+#endif
+	getTextureDimensions(texture, &tw, &th);
+
+	GLushort *image = new GLushort [tw * th];
+	if (! checkNew(image)) return;
+#if 0
+	glPixelStorei(GL_PACK_ALIGNMENT, 1);
+//	glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, image);
+#endif
+	setPixelCoords(true);
+
+	//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+
+	const GLfloat texCoords[] = {
+		0.0f, 0.0f,
+		1.0f, 0.0f,
+		0.0f, 1.0f,
+		1.0f, 1.0f
+	};
+
+	int xoffset = 0;
+	while (xoffset < tw) {
+		int w = (tw - xoffset < viewportWidth) ? tw - xoffset : viewportWidth;
+
+		int yoffset = 0;
+		while (yoffset < th) {
+			int h = (th - yoffset < viewportHeight) ? th - yoffset : viewportHeight;
+#if 0
+			glClear(GL_COLOR_BUFFER_BIT);   // Clear The Screen
+#endif
+			const GLfloat vertices[] = {
+				(GLfloat) - xoffset, (GLfloat) - yoffset, 0.,
+				(GLfloat)w - xoffset, (GLfloat) - yoffset, 0.,
+				(GLfloat) - xoffset, (GLfloat) - yoffset + h, 0.,
+				(GLfloat)w - xoffset, (GLfloat) - yoffset + h, 0.
+			};
+
+#if 0
+			glUseProgram(shader.texture);
+#endif
+			setPMVMatrix(shader.texture);
+			drawQuad(shader.texture, vertices, 1, texCoords);
+#if 0
+			glUseProgram(0);
+
+			for (int i = 0; i < h; i++)   {
+				glReadPixels(viewportOffsetX, viewportOffsetY + i, w, 1, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, image + xoffset + (yoffset + i)*tw);
+			}
+#endif
+			yoffset += viewportHeight;
+		}
+
+		xoffset += viewportWidth;
+	}
+	//glReadPixels(viewportOffsetX, viewportOffsetY, tw, th, GL_RGBA, GL_UNSIGNED_BYTE, data);
+
+	setPixelCoords(false);
+
+
+
+	int x, y, lookAhead;
+	unsigned short int *fromHere, * lookPointer;
+
+	put2bytes(w, writer);
+	put2bytes(h, writer);
+
+	for (y = 0; y < h; y ++) {
+		fromHere = image + (y * tw);
+		x = 0;
+		while (x < w) {
+			lookPointer = fromHere + 1;
+			for (lookAhead = x + 1; lookAhead < w; lookAhead ++) {
+				if (lookAhead - x == 256) break;
+				if (* fromHere != * lookPointer) break;
+				lookPointer ++;
+			}
+			if (lookAhead == x + 1) {
+				put2bytes((* fromHere) & 65503, writer);
+			} else {
+				put2bytes(* fromHere | 32, writer);
+				fputc(lookAhead - x - 1, writer);
+			}
+			fromHere = lookPointer;
+			x = lookAhead;
+		}
+	}
+	delete [] image;
+	image = NULL;
+}
+
+void saveHSI(FILE *writer) {
+	saveCorePNG(writer, backdropTextureName, sceneWidth, sceneHeight);
+}
+
+
+void saveParallaxRecursive(parallaxLayer *me, FILE *fp) {
+	if (me) {
+		saveParallaxRecursive(me -> next, fp);
+		fputc(1, fp);
+		put2bytes(me->fileNum, fp);
+		put2bytes(me ->fractionX, fp);
+		put2bytes(me->fractionY, fp);
+	}
+}
+#endif
+
+bool getRGBIntoStack(unsigned int x, unsigned int y, stackHandler *sH) {
+#if 0
+	if (x >= sceneWidth || y >= sceneHeight) {
+		return fatal("Co-ordinates are outside current scene!");
+	}
+
+	variable newValue;
+
+	newValue.varType = SVT_NULL;
+
+	saveTexture(backdropTextureName, backdropTexture);
+
+	GLubyte *target;
+	if (! NPOT_textures) {
+		target = backdropTexture + 4 * getNextPOT(sceneWidth) * y + x * 4;
+	} else {
+		target = backdropTexture + 4 * sceneWidth * y + x * 4;
+	}
+
+	setVariable(newValue, SVT_INT, target[2]);
+	if (! addVarToStackQuick(newValue, sH -> first)) return false;
+	sH -> last = sH -> first;
+
+	setVariable(newValue, SVT_INT, target[1]);
+	if (! addVarToStackQuick(newValue, sH -> first)) return false;
+
+	setVariable(newValue, SVT_INT, target[0]);
+	if (! addVarToStackQuick(newValue, sH -> first)) return false;
+#endif
+	return true;
+}
diff --git a/engines/sludge/backdrop.h b/engines/sludge/backdrop.h
new file mode 100644
index 0000000..97d3377
--- /dev/null
+++ b/engines/sludge/backdrop.h
@@ -0,0 +1,103 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef SLUDGE_BACKDROP_H
+#define SLUDGE_BACKDROP_H
+
+#if 0
+#if !defined(HAVE_GLES2)
+#include "GLee.h"
+#else
+#include <GLES2/gl2.h>
+#endif
+#endif
+
+#include "variable.h"
+#include "graphics.h"
+
+enum {
+	LIGHTMAPMODE_NONE       = -1,
+	LIGHTMAPMODE_HOTSPOT,
+	LIGHTMAPMODE_PIXEL,
+	LIGHTMAPMODE_NUM
+};
+
+extern unsigned int winWidth, winHeight, sceneWidth, sceneHeight;
+extern int lightMapMode;
+
+
+struct parallaxLayer {
+#if 0
+	GLubyte *texture;
+	GLuint textureName;
+#endif
+	int width, height, speedX, speedY;
+	bool wrapS, wrapT;
+	unsigned short fileNum, fractionX, fractionY;
+	int cameraX, cameraY;
+	parallaxLayer *next;
+	parallaxLayer *prev;
+};
+
+bool resizeBackdrop(int x, int y);
+void killBackDrop();
+void loadBackDrop(int fileNum, int x, int y);
+void mixBackDrop(int fileNum, int x, int y);
+void drawBackDrop();
+void blankScreen(int x1, int y1, int x2, int y2);
+void darkScreen();
+#if ALLOW_FILE
+void saveHSI(FILE *writer);
+void saveCoreHSI(FILE *writer, GLuint texture, int w, int h);
+bool loadHSI(FILE *fp, int, int, bool);
+bool mixHSI(FILE *fp, int x = 0, int y = 0);
+#endif
+void drawHorizontalLine(unsigned int, unsigned int, unsigned int);
+void drawVerticalLine(unsigned int, unsigned int, unsigned int);
+void hardScroll(int distance);
+bool getRGBIntoStack(unsigned int x, unsigned int y, stackHandler *sH);
+
+// Also the light map stuff
+
+void killLightMap();
+bool loadLightMap(int v);
+
+#if 0
+extern texture lightMap;
+#endif
+
+// And background parallax scrolling
+
+void killParallax();
+bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY);
+#if 0
+void saveParallaxRecursive(parallaxLayer *me, FILE *fp);
+#endif
+void reloadParallaxTextures();
+
+void nosnapshot();
+bool snapshot();
+#if ALLOW_FILE
+void saveSnapshot(FILE *fp);
+bool restoreSnapshot(FILE *fp);
+#endif
+#endif
diff --git a/engines/sludge/bg_effects.cpp b/engines/sludge/bg_effects.cpp
new file mode 100644
index 0000000..ad6438b
--- /dev/null
+++ b/engines/sludge/bg_effects.cpp
@@ -0,0 +1,375 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#include "allfiles.h"
+#include "backdrop.h"
+#include "colours.h"
+#include "debug.h"
+#include "graphics.h"
+#include "newfatal.h"
+#include "moreio.h"
+
+#if 0
+//extern unsigned short int * * backDropImage;
+extern GLuint backdropTextureName;
+#endif
+
+#if 0
+// Raised
+static int s_matrixEffectDivide = 2;
+static int s_matrixEffectWidth = 3;
+static int s_matrixEffectHeight = 3;
+static int s_matrixEffectData[9] = {0, 0, 0, 0, -1, 0, 0, 0, 2};
+static int s_matrixEffectBase = 0;
+#elif 0
+// Stay put
+static int s_matrixEffectDivide = 1;
+static int s_matrixEffectWidth = 3;
+static int s_matrixEffectHeight = 3;
+static int s_matrixEffectData[9] = {0, 0, 0, 0, 1, 0, 0, 0, 0};
+static int s_matrixEffectBase = 0;
+#elif 0
+// Brighten
+static int s_matrixEffectDivide = 9;
+static int s_matrixEffectWidth = 1;
+static int s_matrixEffectHeight = 1;
+static int s_matrixEffectData[9] = {10};
+static int s_matrixEffectBase = 15;
+#elif 0
+// Raised up/left
+static int s_matrixEffectDivide = 4;
+static int s_matrixEffectWidth = 3;
+static int s_matrixEffectHeight = 3;
+static int s_matrixEffectData[9] = { -2, -1, 0, -1, 1, 1, 0, 1, 2};
+static int s_matrixEffectBase = 16;
+#elif 0
+// Standard emboss
+static int s_matrixEffectDivide = 2;
+static int s_matrixEffectWidth = 3;
+static int s_matrixEffectHeight = 3;
+static int s_matrixEffectData[9] = { -1, 0, 0, 0, 0, 0, 0, 0, 1};
+static int s_matrixEffectBase = 128;
+#elif 0
+// Horizontal blur
+static int s_matrixEffectDivide = 11;
+static int s_matrixEffectWidth = 5;
+static int s_matrixEffectHeight = 1;
+static int s_matrixEffectData[9] = {1, 3, 3, 3, 1};
+static int s_matrixEffectBase = 0;
+#elif 0
+// Double vision
+static int s_matrixEffectDivide = 6;
+static int s_matrixEffectWidth = 13;
+static int s_matrixEffectHeight = 2;
+static int s_matrixEffectData[26] = {2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3};
+static int s_matrixEffectBase = 0;
+#elif 0
+// Negative
+static int s_matrixEffectDivide = 1;
+static int s_matrixEffectWidth = 1;
+static int s_matrixEffectHeight = 1;
+static int s_matrixEffectData[9] = { -1};
+static int s_matrixEffectBase = 255;
+#elif 0
+// Fog
+static int s_matrixEffectDivide = 4;
+static int s_matrixEffectWidth = 1;
+static int s_matrixEffectHeight = 1;
+static int s_matrixEffectData[9] = {3};
+static int s_matrixEffectBase = 45;
+#elif 0
+// Blur
+static int s_matrixEffectDivide = 14;
+static int s_matrixEffectWidth = 3;
+static int s_matrixEffectHeight = 3;
+static int s_matrixEffectData[9] = {1, 2, 1, 2, 2, 2, 1, 2, 1};
+static int s_matrixEffectBase = 0;
+#else
+static int s_matrixEffectDivide = 0;
+static int s_matrixEffectWidth = 0;
+static int s_matrixEffectHeight = 0;
+static int *s_matrixEffectData = NULL;
+static int s_matrixEffectBase = 0;
+#endif
+
+#if ALLOW_FILE
+void blur_saveSettings(FILE *fp) {
+	if (s_matrixEffectData) {
+		put4bytes(s_matrixEffectDivide, fp);
+		put4bytes(s_matrixEffectWidth, fp);
+		put4bytes(s_matrixEffectHeight, fp);
+		put4bytes(s_matrixEffectBase, fp);
+		fwrite(s_matrixEffectData, sizeof(int), s_matrixEffectWidth * s_matrixEffectHeight, fp);
+	} else {
+		put4bytes(0, fp);
+		put4bytes(0, fp);
+		put4bytes(0, fp);
+		put4bytes(0, fp);
+	}
+}
+#endif
+
+static int *blur_allocateMemoryForEffect() {
+	free(s_matrixEffectData);
+	s_matrixEffectData = NULL;
+
+	if (s_matrixEffectWidth && s_matrixEffectHeight) {
+		s_matrixEffectData = (int *) malloc(sizeof(int) * s_matrixEffectHeight * s_matrixEffectWidth);
+		checkNew(s_matrixEffectData);
+	}
+	return s_matrixEffectData;
+}
+
+#if ALLOW_FILE
+void blur_loadSettings(FILE *fp) {
+	s_matrixEffectDivide = get4bytes(fp);
+	s_matrixEffectWidth = get4bytes(fp);
+	s_matrixEffectHeight = get4bytes(fp);
+	s_matrixEffectBase = get4bytes(fp);
+
+	if (blur_allocateMemoryForEffect()) {
+		size_t bytes_read = fread(s_matrixEffectData, sizeof(int), s_matrixEffectWidth * s_matrixEffectHeight, fp);
+		if (bytes_read != sizeof(int) * s_matrixEffectWidth * s_matrixEffectHeight && ferror(fp)) {
+			debugOut("Reading error in blur_loadSettings.\n");
+		}
+	} else {
+		fseek(fp, sizeof(int) * s_matrixEffectWidth * s_matrixEffectHeight, SEEK_CUR);
+	}
+}
+#endif
+
+bool blur_createSettings(int numParams, variableStack *&stack) {
+	bool createNullThing = true;
+	const char *error = NULL;
+
+	if (numParams >= 3) {
+		// PARAMETERS: base, divide, stack (, stack (, stack...))
+
+		int height = numParams - 2;
+		int width = 0;
+
+		variableStack *justToCheckSizes = stack;
+		for (int a = 0; a < height; a ++) {
+			if (justToCheckSizes->thisVar.varType != SVT_STACK) {
+				error = "Third and subsequent parameters in setBackgroundEffect should be arrays";
+				break;
+			} else {
+				int w = stackSize(justToCheckSizes->thisVar.varData.theStack);
+				if (a) {
+					if (w != width) {
+						error = "Arrays in setBackgroundEffect must be the same size";
+						break;
+					}
+					if (w < width) {
+						width = w;
+					}
+				} else {
+					width = w;
+				}
+			}
+		}
+
+		if (width == 0 && ! error) {
+			error = "Empty arrays found in setBackgroundEffect parameters";
+		}
+
+		if (! error) {
+			s_matrixEffectWidth = width;
+			s_matrixEffectHeight = height;
+
+			if (blur_allocateMemoryForEffect()) {
+				for (int y = height - 1; y >= 0; y --) {
+					variableStack *eachNumber = stack->thisVar.varData.theStack->first;
+					if (! error) {
+						for (int x = 0; x < width; x ++) {
+							int arraySlot = x + (y * width);
+//							s_matrixEffectData[arraySlot] = (rand() % 4);
+							if (!getValueType(s_matrixEffectData[arraySlot], SVT_INT, eachNumber->thisVar)) {
+								error = "";
+								break;
+							}
+							eachNumber = eachNumber->next;
+						}
+						trimStack(stack);
+					}
+				}
+				if (! error && !getValueType(s_matrixEffectDivide, SVT_INT, stack -> thisVar))
+					error = "";
+				trimStack(stack);
+				if (! error && !getValueType(s_matrixEffectBase, SVT_INT, stack -> thisVar))
+					error = "";
+				trimStack(stack);
+				if (! error) {
+					if (s_matrixEffectDivide) {
+						createNullThing = false;
+					} else {
+						error = "Second parameter of setBackgroundEffect (the 'divide' value) should not be 0!";
+					}
+				}
+			} else {
+				error = "Couldn't allocate memory for effect";
+			}
+		}
+	} else {
+		if (numParams) {
+			error = "setBackgroundEffect should either have 0 parameters or more than 2";
+		}
+	}
+
+	if (createNullThing) {
+		s_matrixEffectDivide = 0;
+		s_matrixEffectWidth = 0;
+		s_matrixEffectHeight = 0;
+		s_matrixEffectBase = 0;
+		delete s_matrixEffectData;
+		s_matrixEffectData = NULL;
+	}
+
+	if (error && error[0]) {
+		fatal(error);
+	}
+
+	return ! createNullThing;
+}
+
+static inline int clampi(int i, int min, int max) {
+	return (i >= max) ? max : ((i <= min) ? min : i);
+}
+
+static inline void blur_createSourceLine(unsigned char *createLine, unsigned char *fromLine, int overlapOnLeft, int width) {
+	int miniX;
+	memcpy(createLine + overlapOnLeft * 4, fromLine, width * 4);
+
+	for (miniX = 0; miniX < overlapOnLeft; miniX ++) {
+		createLine[miniX * 4] = fromLine[0];
+		createLine[miniX * 4 + 1] = fromLine[1];
+		createLine[miniX * 4 + 2] = fromLine[2];
+	}
+
+	for (miniX = width + overlapOnLeft; miniX < width + s_matrixEffectWidth - 1; miniX ++) {
+		createLine[miniX * 4] = fromLine[width * 4 - 4];
+		createLine[miniX * 4 + 1] = fromLine[width * 4 - 3];
+		createLine[miniX * 4 + 2] = fromLine[width * 4 - 2];
+	}
+}
+
+bool blurScreen() {
+#if 0
+	if (s_matrixEffectWidth && s_matrixEffectHeight && s_matrixEffectDivide && s_matrixEffectData) {
+		unsigned char *thisLine;
+		int y, x;
+		bool ok = true;
+		int overlapOnLeft = s_matrixEffectWidth / 2;
+		int overlapAbove  = s_matrixEffectHeight / 2;
+
+		unsigned char **sourceLine = new unsigned char *[s_matrixEffectHeight];
+		if (! checkNew(sourceLine)) return false;
+
+		int picWidth = sceneWidth;
+		int picHeight = sceneHeight;
+
+		if (! NPOT_textures) {
+			picWidth = getNextPOT(sceneWidth);
+			picHeight = getNextPOT(sceneHeight);
+		}
+
+		// Retrieve the texture
+		saveTexture(backdropTextureName, backdropTexture);
+
+		for (y = 0; y < s_matrixEffectHeight; y ++) {
+			sourceLine[y] = new unsigned char[(s_matrixEffectWidth - 1 + picWidth) * 4];
+			ok &= (sourceLine[y] != NULL);
+		}
+
+		if (ok) {
+			for (y = 0; y < s_matrixEffectHeight; y ++) {
+				int miniY = clampi(y - overlapAbove - 1, 0, sceneHeight - 1);
+
+				blur_createSourceLine(sourceLine[y], backdropTexture + miniY * picWidth * 4, overlapOnLeft, picWidth);
+			}
+
+			for (y = 0; y < sceneHeight; y ++) {
+				thisLine = backdropTexture + y * picWidth * 4;
+
+				//-------------------------
+				// Scroll source lines
+				//-------------------------
+				unsigned char *tempLine = sourceLine[0];
+				for (int miniY = 0; miniY < s_matrixEffectHeight - 1; miniY ++) {
+					sourceLine[miniY] = sourceLine[miniY + 1];
+				}
+				sourceLine[s_matrixEffectHeight - 1] = tempLine;
+				{
+					int h = s_matrixEffectHeight - 1;
+					int miniY = clampi(y + (s_matrixEffectHeight - overlapAbove - 1), 0, sceneHeight - 1);
+
+					blur_createSourceLine(sourceLine[h], backdropTexture + miniY * picWidth * 4, overlapOnLeft, picWidth);
+				}
+				for (x = 0; x < sceneWidth; x ++) {
+					int totalRed = 0;
+					int totalGreen = 0;
+					int totalBlue = 0;
+					int *matrixElement = s_matrixEffectData;
+					for (int miniY = 0; miniY < s_matrixEffectHeight; ++ miniY) {
+						unsigned char *pixel = & sourceLine[miniY][x * 4];
+						for (int miniX = 0; miniX < s_matrixEffectWidth; ++ miniX) {
+
+							totalRed    += pixel[0]     * * matrixElement;
+							totalGreen  += pixel[1]     * * matrixElement;
+							totalBlue   += pixel[2]     * * matrixElement;
+							++ matrixElement;
+							pixel += 4;
+						}
+					}
+					totalRed = (totalRed + s_matrixEffectDivide / 2) / s_matrixEffectDivide + s_matrixEffectBase;
+					totalRed = (totalRed < 0) ? 0 : ((totalRed > 255) ? 255 : totalRed);
+
+					totalGreen = (totalGreen + s_matrixEffectDivide / 2) / s_matrixEffectDivide + s_matrixEffectBase;
+					totalGreen = (totalGreen < 0) ? 0 : ((totalGreen > 255) ? 255 : totalGreen);
+
+					totalBlue = (totalBlue + s_matrixEffectDivide / 2) / s_matrixEffectDivide + s_matrixEffectBase;
+					totalBlue = (totalBlue < 0) ? 0 : ((totalBlue > 255) ? 255 : totalBlue);
+
+					* thisLine = totalRed;
+					++ thisLine;
+					* thisLine = totalGreen;
+					++ thisLine;
+					* thisLine = totalBlue;
+					++ thisLine;
+//					* thisLine = totalAlpha;
+					++ thisLine;
+				}
+			}
+		}
+
+		for (y = 0; y < s_matrixEffectHeight; y ++) {
+			delete sourceLine[y];
+		}
+		delete sourceLine;
+		sourceLine = NULL;
+
+		texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, backdropTexture, backdropTextureName);
+		return true;
+	}
+#endif
+	return false;
+}
diff --git a/engines/sludge/bg_effects.h b/engines/sludge/bg_effects.h
new file mode 100644
index 0000000..067fa8d
--- /dev/null
+++ b/engines/sludge/bg_effects.h
@@ -0,0 +1,33 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef SLUDGE_BG_EFFECTS_H
+#define SLUDGE_BG_EFFECTS_H
+
+bool blurScreen();
+#if ALLOW_FILE
+void blur_saveSettings(FILE *fp);
+void blur_loadSettings(FILE *fp);
+#endif
+bool blur_createSettings(int numParams, variableStack *&stack);
+
+#endif
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
new file mode 100644
index 0000000..9ba633d
--- /dev/null
+++ b/engines/sludge/builtin.cpp
@@ -0,0 +1,2545 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#if 0
+#include <SDL/SDL.h>
+#endif
+
+#include "debug.h"
+#include "allfiles.h"
+#include "sludger.h"
+#include "builtin.h"
+#include "stringy.h"
+#include "newfatal.h"
+#include "cursors.h"
+#include "statusba.h"
+#include "loadsave.h"
+#include "backdrop.h"
+#include "bg_effects.h"
+#include "sprites.h"
+#include "fonttext.h"
+#include "sprbanks.h"
+#include "people.h"
+#include "sound.h"
+#include "objtypes.h"
+#include "floor.h"
+#include "zbuffer.h"
+#include "talk.h"
+#include "region.h"
+#include "language.h"
+#include "moreio.h"
+#include "movie.h"
+#include "savedata.h"
+#include "freeze.h"
+#include "colours.h"
+#include "language.h"
+#include "thumbnail.h"
+#include "graphics.h"
+#include "CommonCode/utf8.h"
+
+extern char *gamePath;
+
+int speechMode = 0;
+int cameraX, cameraY;
+float cameraZoom = 1.0;
+spritePalette pastePalette;
+
+char *launchMe = NULL;
+variable *launchResult = NULL;
+
+extern int lastFramesPerSecond, thumbWidth, thumbHeight;
+extern bool allowAnyFilename;
+extern bool captureAllKeys;
+extern short fontSpace;
+extern eventHandlers *currentEvents;
+extern variableStack *noStack;
+extern statusStuff *nowStatus;
+extern screenRegion *overRegion;
+extern HWND hMainWindow;
+extern unsigned int sceneWidth, sceneHeight;
+extern int numBIFNames, numUserFunc;
+extern char builtInFunctionNames[][25];
+
+extern char * *allUserFunc;
+extern char * *allBIFNames;
+extern inputType input;
+extern char *loadNow;
+
+#if 0
+extern GLuint backdropTextureName;
+#endif
+
+extern float speechSpeed;
+extern unsigned char brightnessLevel;
+extern unsigned char fadeMode;
+extern unsigned short saveEncoding;
+extern frozenStuffStruct *frozenStuff;
+extern unsigned int currentBlankColour;
+extern unsigned int languageID;
+extern unsigned char currentBurnR, currentBurnG, currentBurnB;
+
+int paramNum[] = { -1, 0, 1, 1, -1, -1, 1, 3, 4, 1, 0, 0, 8, -1,    // SAY -> MOVEMOUSE
+                   -1, 0, 0, -1, -1, 1, 1, 1, 1, 4, 1, 1, 2, 1,// FOCUS -> REMOVEREGION
+                   2, 2, 0, 0, 2,                              // ANIMATE -> SETSCALE
+                   -1, 2, 1, 0, 0, 0, 1, 0, 3,                 // new/push/pop stack, status stuff
+                   2, 0, 0, 3, 1, 0, 2,                        // delFromStack -> completeTimers
+                   -1, -1, -1, 2, 2, 0, 3, 1,                  // anim, costume, pO, setC, wait, sS, substring, stringLength
+                   0, 1, 1, 0, 2,                              // dark, save, load, quit, rename
+                   1, 3, 3, 1, 2, 1, 1, 3, 1, 0, 0, 2, 1,      // stackSize, pasteString, startMusic, defvol, vol, stopmus, stopsound, setfont, alignStatus, show x 2, pos'Status, setFloor
+                   -1, -1, 1, 1, 2, 1, 1, 1, -1, -1, -1, 1, 1, // force, jump, peekstart, peekend, enqueue, getSavedGames, inFont, loopSound, removeChar, stopCharacter
+                   1, 0, 3, 3, 1, 2, 1, 2, 2,                  // launch, howFrozen, pastecol, litcol, checksaved, float, cancelfunc, walkspeed, delAll
+                   2, 3, 1, 2, 2, 0, 0, 1, 2, 3, 1, -1,        // extras, mixoverlay, pastebloke, getMScreenX/Y, setSound(Default/-)Volume, looppoints, speechMode, setLightMap
+                   -1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1,           // think, getCharacterDirection, is(char/region/moving), deleteGame, renameGame, hardScroll, stringWidth, speechSpeed, normalCharacter
+                   2, 1, 2, 1, 3, 1, 1, 2, 1,                  // fetchEvent, setBrightness, spin, fontSpace, burnString, captureAll, cacheSound, setSpinSpeed, transitionMode
+                   1, 0, 0, 1, 0, 2, 1, 1, 1,                  // movie(Start/Abort/Playing), updateDisplay, getSoundCache, savedata, loaddata, savemode, freeSound
+                   3, 0, 3, 3, 2, 1, 1,                        // setParallax, clearParallax, setBlankColour, setBurnColour, getPixelColour, makeFastArray, getCharacterScale
+                   0, 2, 0,                                    // getLanguage, launchWith, getFramesPerSecond
+                   3, 2, 2, 0, 0, 1,                           // readThumbnail, setThumbnailSize, hasFlag, snapshot, clearSnapshot, anyFilename
+                   2, 1,                                       // regGet, fatal
+                   4, 3, -1, 0,                                // chr AA, max AA, setBackgroundEffect, doBackgroundEffect
+                   2,                                          // setCharacterAngleOffset
+                   2, 5,                                       // setCharacterTransparency, setCharacterColourise
+                   1,                                          // zoomCamera
+                   1, 0, 0                                     // playMovie, stopMovie, pauseMovie
+                 };
+
+bool failSecurityCheck(char *fn) {
+	if (fn == NULL) return true;
+
+	int a = 0;
+
+	while (fn[a]) {
+		switch (fn[a]) {
+		case ':':
+		case '\\':
+		case '/':
+		case '*':
+		case '?':
+		case '"':
+		case '<':
+		case '>':
+		case '|':
+			fatal("Filenames may not contain the following characters: \n\n\\  /  :  \"  <  >  |  ?  *\n\nConsequently, the following filename is not allowed:", fn);
+			return true;
+		}
+		a ++;
+	}
+	return false;
+}
+
+loadedFunction *saverFunc;
+
+typedef builtReturn(* builtInSludgeFunc)(int numParams, loadedFunction *fun);
+struct builtInFunctionData {
+	builtInSludgeFunc func;
+};
+
+#define builtIn(a)          static builtReturn builtIn_ ## a (int numParams, loadedFunction * fun)
+#define UNUSEDALL           (void) (0 && sizeof(numParams) && sizeof (fun));
+
+static builtReturn sayCore(int numParams, loadedFunction *fun, bool sayIt) {
+	int fileNum = -1;
+	char *newText;
+	int objT, p;
+	killSpeechTimers();
+
+	switch (numParams) {
+	case 3:
+		if (!getValueType(fileNum, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
+		trimStack(fun -> stack);
+	// No break; here
+
+	case 2:
+		newText = getTextFromAnyVar(fun -> stack -> thisVar);
+		if (!newText) return BR_ERROR;
+		trimStack(fun -> stack);
+		if (!getValueType(objT, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+		trimStack(fun -> stack);
+		p = wrapSpeech(newText, objT, fileNum, sayIt);
+		fun -> timeLeft = p;
+		//debugOut ("BUILTIN: sayCore: %s (%i)\n", newText, p);
+		fun -> isSpeech = true;
+		delete newText;
+		newText = NULL;
+		return BR_KEEP_AND_PAUSE;
+	}
+
+	fatal("Function should have either 2 or 3 parameters");
+	return BR_ERROR;
+}
+
+#pragma mark -
+#pragma mark Built in functions
+
+builtIn(say) {
+	UNUSEDALL
+	return sayCore(numParams, fun, true);
+}
+
+builtIn(think) {
+	UNUSEDALL
+	return sayCore(numParams, fun, false);
+}
+
+builtIn(freeze) {
+	UNUSEDALL
+	freeze();
+	freezeSubs();
+	fun -> freezerLevel = 0;
+	return BR_CONTINUE;
+}
+
+builtIn(unfreeze) {
+	UNUSEDALL
+	unfreeze();
+	unfreezeSubs();
+	return BR_CONTINUE;
+}
+
+builtIn(howFrozen) {
+	UNUSEDALL
+	setVariable(fun -> reg, SVT_INT, howFrozen());
+	return BR_CONTINUE;
+}
+
+builtIn(setCursor) {
+	UNUSEDALL
+	personaAnimation *aa = getAnimationFromVar(fun -> stack -> thisVar);
+	pickAnimCursor(aa);
+	trimStack(fun -> stack);
+	return BR_CONTINUE;
+}
+
+builtIn(getMouseX) {
+	UNUSEDALL
+	setVariable(fun -> reg, SVT_INT, input.mouseX + cameraX);
+	return BR_CONTINUE;
+}
+
+builtIn(getMouseY) {
+	UNUSEDALL
+	setVariable(fun -> reg, SVT_INT, input.mouseY + cameraY);
+	return BR_CONTINUE;
+}
+
+builtIn(getMouseScreenX) {
+	UNUSEDALL
+	setVariable(fun -> reg, SVT_INT, input.mouseX * cameraZoom);
+	return BR_CONTINUE;
+}
+
+builtIn(getMouseScreenY) {
+	UNUSEDALL
+	setVariable(fun -> reg, SVT_INT, input.mouseY * cameraZoom);
+	return BR_CONTINUE;
+}
+
+builtIn(getStatusText) {
+	UNUSEDALL
+	makeTextVar(fun -> reg, statusBarText());
+	return BR_CONTINUE;
+}
+
+builtIn(getMatchingFiles) {
+	UNUSEDALL
+	char *newText = getTextFromAnyVar(fun -> stack -> thisVar);
+	if (!newText) return BR_ERROR;
+	trimStack(fun -> stack);
+	unlinkVar(fun -> reg);
+
+	// Return value
+	fun -> reg.varType = SVT_STACK;
+	fun -> reg.varData.theStack = new stackHandler;
+	if (!checkNew(fun -> reg.varData.theStack)) return BR_ERROR;
+	fun -> reg.varData.theStack -> first = NULL;
+	fun -> reg.varData.theStack -> last = NULL;
+	fun -> reg.varData.theStack -> timesUsed = 1;
+	if (!getSavedGamesStack(fun -> reg.varData.theStack, newText)) return BR_ERROR;
+	delete newText;
+	newText = NULL;
+	return BR_CONTINUE;
+}
+
+builtIn(saveGame) {
+	UNUSEDALL
+
+	if (frozenStuff) {
+		fatal("Can't save game state while the engine is frozen");
+	}
+
+	loadNow = getTextFromAnyVar(fun -> stack -> thisVar);
+	trimStack(fun -> stack);
+
+	char *aaaaa = encodeFilename(loadNow);
+	delete[] loadNow;
+	if (failSecurityCheck(aaaaa)) return BR_ERROR;      // Won't fail if encoded, how cool is that? OK, not very.
+
+	loadNow = joinStrings(":", aaaaa);
+	delete[] aaaaa;
+
+	setVariable(fun -> reg, SVT_INT, 0);
+	saverFunc = fun;
+	return BR_KEEP_AND_PAUSE;
+}
+
+builtIn(fileExists) {
+	UNUSEDALL
+	loadNow = getTextFromAnyVar(fun -> stack -> thisVar);
+	trimStack(fun -> stack);
+	char *aaaaa = encodeFilename(loadNow);
+	delete loadNow;
+	if (failSecurityCheck(aaaaa)) return BR_ERROR;
+#if ALLOW_FILE
+	FILE *fp = fopen(aaaaa, "rb");
+	if (!fp) {
+		char currentDir[1000];
+		if (!getcwd(currentDir, 998)) {
+			debugOut("Can't get current directory.\n");
+		}
+
+		if (chdir(gamePath)) {
+			debugOut("Error: Failed changing to directory %s\n", gamePath);
+		}
+		fp = fopen(aaaaa, "rb");
+		if (chdir(currentDir)) {
+			debugOut("Error: Failed changing to directory %s\n", currentDir);
+		}
+	}
+	// Return value
+	setVariable(fun -> reg, SVT_INT, (fp != NULL));
+	if (fp) fclose(fp);
+	delete[] aaaaa;
+	loadNow = NULL;
+#endif
+	return BR_CONTINUE;
+}
+
+builtIn(loadGame) {
+	UNUSEDALL
+	char *aaaaa = getTextFromAnyVar(fun -> stack -> thisVar);
+	trimStack(fun -> stack);
+	loadNow = encodeFilename(aaaaa);
+	delete aaaaa;
+
+	if (frozenStuff) {
+		fatal("Can't load a saved game while the engine is frozen");
+	}
+#if ALLOW_FILE
+	if (failSecurityCheck(loadNow)) return BR_ERROR;
+	FILE *fp = fopen(loadNow, "rb");
+	if (fp) {
+		fclose(fp);
+		return BR_KEEP_AND_PAUSE;
+	}
+	delete loadNow;
+	loadNow = NULL;
+#endif
+	return BR_CONTINUE;
+}
+
+//--------------------------------------
+#pragma mark -
+#pragma mark Background image - Painting
+
+builtIn(blankScreen) {
+	UNUSEDALL
+	blankScreen(0, 0, sceneWidth, sceneHeight);
+	return BR_CONTINUE;
+}
+
+builtIn(blankArea) {
+	UNUSEDALL
+	int x1, y1, x2, y2;
+	if (!getValueType(y2, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(x2, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(y1, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(x1, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	blankScreen(x1, y1, x2, y2);
+	return BR_CONTINUE;
+}
+
+builtIn(darkBackground) {
+	UNUSEDALL
+	darkScreen();
+	return BR_CONTINUE;
+}
+
+builtIn(addOverlay) {
+	UNUSEDALL
+	int fileNumber, xPos, yPos;
+	if (!getValueType(yPos, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(xPos, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	loadBackDrop(fileNumber, xPos, yPos);
+	return BR_CONTINUE;
+}
+
+builtIn(mixOverlay) {
+	UNUSEDALL
+	int fileNumber, xPos, yPos;
+	if (!getValueType(yPos, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(xPos, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	mixBackDrop(fileNumber, xPos, yPos);
+	return BR_CONTINUE;
+}
+
+builtIn(pasteImage) {
+	UNUSEDALL
+	int x, y;
+	if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	personaAnimation *pp = getAnimationFromVar(fun -> stack -> thisVar);
+	trimStack(fun -> stack);
+	if (pp == NULL) return BR_CONTINUE;
+
+	pasteCursor(x, y, pp);
+	return BR_CONTINUE;
+}
+
+#pragma mark -
+#pragma mark Background Image - Scrolling
+
+builtIn(setSceneDimensions) {
+	UNUSEDALL
+	int x, y;
+	if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (resizeBackdrop(x, y)) {
+		blankScreen(0, 0, x, y);
+		return BR_CONTINUE;
+	}
+	fatal("Out of memory creating new backdrop.");
+	return BR_ERROR;
+}
+
+builtIn(aimCamera) {
+	UNUSEDALL
+	if (!getValueType(cameraY, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(cameraX, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	cameraX -= (float)(winWidth >> 1) / cameraZoom;
+	cameraY -= (float)(winHeight >> 1) / cameraZoom;
+
+	if (cameraX < 0) cameraX = 0;
+	else if (cameraX > sceneWidth - (float)winWidth / cameraZoom) cameraX = sceneWidth - (float)winWidth / cameraZoom;
+	if (cameraY < 0) cameraY = 0;
+	else if (cameraY > sceneHeight - (float)winHeight / cameraZoom) cameraY = sceneHeight - (float)winHeight / cameraZoom;
+	return BR_CONTINUE;
+}
+
+
+builtIn(zoomCamera) {
+	UNUSEDALL
+	int z;
+	if (!getValueType(z, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	input.mouseX = input.mouseX * cameraZoom;
+	input.mouseY = input.mouseY * cameraZoom;
+
+
+	cameraZoom = (float) z * 0.01;
+	if ((float) winWidth / cameraZoom > sceneWidth) cameraZoom = (float)winWidth / sceneWidth;
+	if ((float) winHeight / cameraZoom > sceneHeight) cameraZoom = (float)winHeight / sceneHeight;
+	setPixelCoords(false);
+
+	input.mouseX = input.mouseX / cameraZoom;
+	input.mouseY = input.mouseY / cameraZoom;
+
+	return BR_CONTINUE;
+}
+
+#pragma mark -
+#pragma mark Variables
+
+
+builtIn(pickOne) {
+	UNUSEDALL
+	if (!numParams) {
+		fatal("Built-in function should have at least 1 parameter");
+		return BR_ERROR;
+	}
+
+	int i;
+#if 0
+	i = rand() % numParams;
+#endif
+
+	// Return value
+	while (numParams --) {
+		if (i == numParams) copyVariable(fun -> stack -> thisVar, fun -> reg);
+		trimStack(fun -> stack);
+	}
+	return BR_CONTINUE;
+}
+
+builtIn(substring) {
+	UNUSEDALL
+	char *wholeString;
+	char *newString;
+	int start, length;
+
+	//debugOut ("BUILTIN: substring\n");
+
+	if (!getValueType(length, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(start, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	wholeString = getTextFromAnyVar(fun -> stack -> thisVar);
+	trimStack(fun -> stack);
+
+	if (u8_strlen(wholeString) < start + length) {
+		length = u8_strlen(wholeString) - start;
+		if (u8_strlen(wholeString) < start) {
+			start = 0;
+		}
+	}
+	if (length < 0) {
+		length = 0;
+	}
+
+	int startoffset = u8_offset(wholeString, start);
+	int endoffset = u8_offset(wholeString, start + length);
+
+	newString = new char[endoffset - startoffset + 1];
+	if (!checkNew(newString)) {
+		return BR_ERROR;
+	}
+
+	memcpy(newString, wholeString + startoffset, endoffset - startoffset);
+	newString[endoffset - startoffset] = 0;
+
+	makeTextVar(fun -> reg, newString);
+	delete newString;
+	return BR_CONTINUE;
+}
+
+builtIn(stringLength) {
+	UNUSEDALL
+	char *newText = getTextFromAnyVar(fun -> stack -> thisVar);
+	trimStack(fun -> stack);
+	setVariable(fun -> reg, SVT_INT, stringLength(newText));
+	delete[] newText;
+	return BR_CONTINUE;
+}
+
+builtIn(newStack) {
+	UNUSEDALL
+	unlinkVar(fun -> reg);
+
+	// Return value
+	fun -> reg.varType = SVT_STACK;
+	fun -> reg.varData.theStack = new stackHandler;
+	if (!checkNew(fun -> reg.varData.theStack)) return BR_ERROR;
+	fun -> reg.varData.theStack -> first = NULL;
+	fun -> reg.varData.theStack -> last = NULL;
+	fun -> reg.varData.theStack -> timesUsed = 1;
+	while (numParams --) {
+		if (!addVarToStack(fun -> stack -> thisVar, fun -> reg.varData.theStack -> first)) return BR_ERROR;
+		if (fun -> reg.varData.theStack -> last == NULL) {
+			fun -> reg.varData.theStack -> last = fun -> reg.varData.theStack -> first;
+		}
+		trimStack(fun -> stack);
+	}
+	return BR_CONTINUE;
+}
+
+// wait is exactly the same function, but limited to 2 parameters
+#define builtIn_wait builtIn_newStack
+
+builtIn(stackSize) {
+	UNUSEDALL
+	switch (fun -> stack -> thisVar.varType) {
+	case SVT_STACK:
+		// Return value
+		setVariable(fun -> reg, SVT_INT, stackSize(fun -> stack -> thisVar.varData.theStack));
+		trimStack(fun -> stack);
+		return BR_CONTINUE;
+
+	case SVT_FASTARRAY:
+		// Return value
+		setVariable(fun -> reg, SVT_INT, fun -> stack -> thisVar.varData.fastArray -> size);
+		trimStack(fun -> stack);
+		return BR_CONTINUE;
+
+	default:
+		break;
+	}
+	fatal("Parameter isn't a stack or a fast array.");
+	return BR_ERROR;
+}
+
+builtIn(copyStack) {
+	UNUSEDALL
+	if (fun -> stack -> thisVar.varType != SVT_STACK) {
+		fatal("Parameter isn't a stack.");
+		return BR_ERROR;
+	}
+	// Return value
+	if (!copyStack(fun -> stack -> thisVar, fun -> reg)) return BR_ERROR;
+	trimStack(fun -> stack);
+	return BR_CONTINUE;
+}
+
+builtIn(pushToStack) {
+	UNUSEDALL
+	if (fun -> stack -> next -> thisVar.varType != SVT_STACK) {
+		fatal("Parameter isn't a stack");
+		return BR_ERROR;
+	}
+
+	if (!addVarToStack(fun -> stack -> thisVar, fun -> stack -> next -> thisVar.varData.theStack -> first))
+		return BR_ERROR;
+
+	if (fun -> stack -> next -> thisVar.varData.theStack -> first -> next == NULL)
+		fun -> stack -> next -> thisVar.varData.theStack -> last = fun -> stack -> next -> thisVar.varData.theStack -> first;
+
+	trimStack(fun -> stack);
+	trimStack(fun -> stack);
+	return BR_CONTINUE;
+}
+
+builtIn(enqueue) {
+	UNUSEDALL
+	if (fun -> stack -> next -> thisVar.varType != SVT_STACK) {
+		fatal("Parameter isn't a stack");
+		return BR_ERROR;
+	}
+
+	if (fun -> stack -> next -> thisVar.varData.theStack -> first == NULL) {
+		if (!addVarToStack(fun -> stack -> thisVar, fun -> stack -> next -> thisVar.varData.theStack -> first))
+			return BR_ERROR;
+
+		fun -> stack -> next -> thisVar.varData.theStack -> last = fun -> stack -> next -> thisVar.varData.theStack -> first;
+	} else {
+		if (!addVarToStack(fun -> stack -> thisVar,
+		                    fun -> stack -> next -> thisVar.varData.theStack -> last -> next))
+			return BR_ERROR;
+		fun -> stack -> next -> thisVar.varData.theStack -> last = fun -> stack -> next -> thisVar.varData.theStack -> last -> next;
+	}
+
+	trimStack(fun -> stack);
+	trimStack(fun -> stack);
+	return BR_CONTINUE;
+}
+
+builtIn(deleteFromStack) {
+	UNUSEDALL
+	if (fun -> stack -> next -> thisVar.varType != SVT_STACK) {
+		fatal("Parameter isn't a stack.");
+		return BR_ERROR;
+	}
+
+	// Return value
+	setVariable(fun -> reg, SVT_INT,
+	            deleteVarFromStack(fun -> stack -> thisVar,
+	                               fun -> stack -> next -> thisVar.varData.theStack -> first, false));
+
+	// Horrible hacking because 'last' value might now be wrong!
+	fun->stack->next->thisVar.varData.theStack->last = stackFindLast(fun->stack->next->thisVar.varData.theStack->first);
+
+	trimStack(fun -> stack);
+	trimStack(fun -> stack);
+	return BR_CONTINUE;
+}
+
+builtIn(deleteAllFromStack) {
+	UNUSEDALL
+	if (fun -> stack -> next -> thisVar.varType != SVT_STACK) {
+		fatal("Parameter isn't a stack.");
+		return BR_ERROR;
+	}
+
+	// Return value
+	setVariable(fun -> reg, SVT_INT,
+	            deleteVarFromStack(fun -> stack -> thisVar,
+	                               fun -> stack -> next -> thisVar.varData.theStack -> first, true));
+
+	// Horrible hacking because 'last' value might now be wrong!
+	fun->stack->next->thisVar.varData.theStack->last = stackFindLast(fun->stack->next->thisVar.varData.theStack->first);
+
+	trimStack(fun -> stack);
+	trimStack(fun -> stack);
+	return BR_CONTINUE;
+}
+
+builtIn(popFromStack) {
+	UNUSEDALL
+	if (fun -> stack -> thisVar.varType != SVT_STACK) {
+		fatal("Parameter isn't a stack.");
+		return BR_ERROR;
+	}
+	if (fun -> stack -> thisVar.varData.theStack -> first == NULL) {
+		fatal("The stack's empty.");
+		return BR_ERROR;
+	}
+
+	// Return value
+	copyVariable(fun -> stack -> thisVar.varData.theStack -> first -> thisVar, fun -> reg);
+	trimStack(fun -> stack -> thisVar.varData.theStack -> first);
+	trimStack(fun -> stack);
+	return BR_CONTINUE;
+}
+
+builtIn(peekStart) {
+	UNUSEDALL
+	if (fun -> stack -> thisVar.varType != SVT_STACK) {
+		fatal("Parameter isn't a stack.");
+		return BR_ERROR;
+	}
+	if (fun -> stack -> thisVar.varData.theStack -> first == NULL) {
+		fatal("The stack's empty.");
+		return BR_ERROR;
+	}
+
+	// Return value
+	copyVariable(fun -> stack -> thisVar.varData.theStack -> first -> thisVar, fun -> reg);
+	trimStack(fun -> stack);
+	return BR_CONTINUE;
+}
+
+builtIn(peekEnd) {
+	UNUSEDALL
+	if (fun -> stack -> thisVar.varType != SVT_STACK) {
+		fatal("Parameter isn't a stack.");
+		return BR_ERROR;
+	}
+	if (fun -> stack -> thisVar.varData.theStack -> first == NULL) {
+		fatal("The stack's empty.");
+		return BR_ERROR;
+	}
+
+	// Return value
+	copyVariable(fun -> stack -> thisVar.varData.theStack -> last -> thisVar, fun -> reg);
+	trimStack(fun -> stack);
+	return BR_CONTINUE;
+}
+
+builtIn(random) {
+	UNUSEDALL
+	int num;
+
+	if (!getValueType(num, SVT_INT, fun -> stack -> thisVar))
+		return BR_ERROR;
+
+	trimStack(fun -> stack);
+	if (num <= 0) num = 1;
+	setVariable(fun -> reg, SVT_INT, 0 /*rand() % num*/); //TODO:false value
+	return BR_CONTINUE;
+}
+
+static bool getRGBParams(int &red, int &green, int &blue, loadedFunction *fun) {
+	if (!getValueType(blue, SVT_INT, fun -> stack -> thisVar)) return false;
+	trimStack(fun -> stack);
+	if (!getValueType(green, SVT_INT, fun -> stack -> thisVar)) return false;
+	trimStack(fun -> stack);
+	if (!getValueType(red, SVT_INT, fun -> stack -> thisVar)) return false;
+	trimStack(fun -> stack);
+	return true;
+}
+
+builtIn(setStatusColour) {
+	UNUSEDALL
+	int red, green, blue;
+
+	if (!getRGBParams(red, green, blue, fun))
+		return BR_ERROR;
+
+	statusBarColour((byte) red, (byte) green, (byte) blue);
+	return BR_CONTINUE;
+}
+
+builtIn(setLitStatusColour) {
+	UNUSEDALL
+	int red, green, blue;
+
+	if (!getRGBParams(red, green, blue, fun))
+		return BR_ERROR;
+
+	statusBarLitColour((byte) red, (byte) green, (byte) blue);
+	return BR_CONTINUE;
+}
+
+builtIn(setPasteColour) {
+	UNUSEDALL
+	int red, green, blue;
+
+	if (!getRGBParams(red, green, blue, fun))
+		return BR_ERROR;
+
+	setFontColour(pastePalette, (byte) red, (byte) green, (byte) blue);
+	return BR_CONTINUE;
+}
+
+builtIn(setBlankColour) {
+	UNUSEDALL
+	int red, green, blue;
+
+	if (!getRGBParams(red, green, blue, fun))
+		return BR_ERROR;
+
+	currentBlankColour = makeColour(red & 255, green & 255, blue & 255);
+	setVariable(fun -> reg, SVT_INT, 1);
+	return BR_CONTINUE;
+}
+
+builtIn(setBurnColour) {
+	UNUSEDALL
+	int red, green, blue;
+
+	if (!getRGBParams(red, green, blue, fun))
+		return BR_ERROR;
+
+	currentBurnR = red;
+	currentBurnG = green;
+	currentBurnB = blue;
+	setVariable(fun -> reg, SVT_INT, 1);
+	return BR_CONTINUE;
+}
+
+
+builtIn(setFont) {
+	UNUSEDALL
+	int fileNumber, newHeight;
+	if (!getValueType(newHeight, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	//              newDebug ("  Height:", newHeight);
+	trimStack(fun -> stack);
+	char *newText = getTextFromAnyVar(fun -> stack -> thisVar);
+	if (!newText) return BR_ERROR;
+	//              newDebug ("  Character supported:", newText);
+	trimStack(fun -> stack);
+	if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
+	//              newDebug ("  File:", fileNumber);
+	trimStack(fun -> stack);
+	if (!loadFont(fileNumber, newText, newHeight)) return BR_ERROR;
+	//              newDebug ("  Done!");
+	delete newText;
+
+	return BR_CONTINUE;
+}
+
+builtIn(inFont) {
+	UNUSEDALL
+	char *newText = getTextFromAnyVar(fun -> stack -> thisVar);
+	if (!newText) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	// Return value
+
+	setVariable(fun -> reg, SVT_INT, isInFont(newText));
+	return BR_CONTINUE;
+}
+
+builtIn(pasteString) {
+	UNUSEDALL
+	char *newText = getTextFromAnyVar(fun -> stack -> thisVar);
+	trimStack(fun -> stack);
+	int y, x;
+	if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (x == IN_THE_CENTRE) x = (winWidth - stringWidth(newText)) >> 1;
+	fixFont(pastePalette);
+	pasteStringToBackdrop(newText, x, y, pastePalette);
+	delete[] newText;
+	return BR_CONTINUE;
+}
+
+builtIn(anim) {
+	UNUSEDALL
+	if (numParams < 2) {
+		fatal("Built-in function anim() must have at least 2 parameters.");
+		return BR_ERROR;
+	}
+
+	// First store the frame numbers and take 'em off the stack
+	personaAnimation *ba = createPersonaAnim(numParams - 1, fun -> stack);
+
+	// Only remaining paramter is the file number
+	int fileNumber;
+	if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	// Load the required sprite bank
+	loadedSpriteBank *sprBanky = loadBankForAnim(fileNumber);
+	if (!sprBanky) return BR_ERROR;    // File not found, fatal done already
+	setBankFile(ba, sprBanky);
+
+	// Return value
+	newAnimationVariable(fun -> reg, ba);
+
+	return BR_CONTINUE;
+}
+
+builtIn(costume) {
+	UNUSEDALL
+	persona *newPersona = new persona;
+	if (!checkNew(newPersona)) return BR_ERROR;
+	newPersona -> numDirections = numParams / 3;
+	if (numParams == 0 || newPersona -> numDirections * 3 != numParams) {
+		fatal("Illegal number of parameters (should be greater than 0 and divisible by 3)");
+		return BR_ERROR;
+	}
+	int iii;
+	newPersona -> animation = new personaAnimation * [numParams];
+	if (!checkNew(newPersona -> animation)) return BR_ERROR;
+	for (iii = numParams - 1; iii >= 0; iii --) {
+		newPersona -> animation[iii] = getAnimationFromVar(fun -> stack -> thisVar);
+		trimStack(fun -> stack);
+	}
+
+	// Return value
+	newCostumeVariable(fun -> reg, newPersona);
+	return BR_CONTINUE;
+}
+
+builtIn(launch) {
+	UNUSEDALL
+	char *newTextA = getTextFromAnyVar(fun -> stack -> thisVar);
+	if (!newTextA) return BR_ERROR;
+
+	char *newText = encodeFilename(newTextA);
+
+	trimStack(fun -> stack);
+	if (newTextA[0] == 'h' &&
+	        newTextA[1] == 't' &&
+	        newTextA[2] == 't' &&
+	        newTextA[3] == 'p' &&
+	        (newTextA[4] == ':' || (newTextA[4] == 's' && newTextA[5] == ':'))) {
+
+		// IT'S A WEBSITE!
+		launchMe = copyString(newTextA);
+	} else {
+		char *gameDir;
+#ifdef _WIN32
+		gameDir = joinStrings(gamePath, "\\");
+#else
+		gameDir = joinStrings(gamePath, "/");
+#endif
+		launchMe = joinStrings(gameDir, newText);
+		delete newText;
+		if (!launchMe) return BR_ERROR;
+	}
+	delete newTextA;
+	setGraphicsWindow(false);
+	setVariable(fun -> reg, SVT_INT, 1);
+	launchResult = &fun->reg;
+
+	return BR_KEEP_AND_PAUSE;
+}
+
+builtIn(pause) {
+	UNUSEDALL
+	int theTime;
+	if (!getValueType(theTime, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (theTime > 0) {
+		fun -> timeLeft = theTime - 1;
+		fun -> isSpeech = false;
+		return BR_KEEP_AND_PAUSE;
+	}
+	return BR_CONTINUE;
+}
+
+builtIn(completeTimers) {
+	UNUSEDALL
+	completeTimers();
+	return BR_CONTINUE;
+}
+
+builtIn(callEvent) {
+	UNUSEDALL
+	int obj1, obj2;
+	if (!getValueType(obj2, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(obj1, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	int fNum = getCombinationFunction(obj1, obj2);
+
+	// Return value
+	if (fNum) {
+		setVariable(fun -> reg, SVT_FUNC, fNum);
+		return BR_CALLAFUNC;
+	}
+	setVariable(fun -> reg, SVT_INT, 0);
+	return BR_CONTINUE;
+}
+
+#if 0
+SDL_Event quit_event;
+#endif
+
+bool reallyWantToQuit = false;
+
+builtIn(quitGame) {
+	UNUSEDALL
+	reallyWantToQuit = true;
+#if 0
+	quit_event.type = SDL_QUIT;
+	SDL_PushEvent(&quit_event);
+#endif
+	return BR_CONTINUE;
+}
+
+
+#pragma mark -
+#pragma mark Movie functions
+
+// The old movie functions are deprecated and does nothing.
+builtIn(_rem_movieStart) {
+	UNUSEDALL
+	trimStack(fun -> stack);
+	return BR_CONTINUE;
+}
+
+builtIn(_rem_movieAbort) {
+	UNUSEDALL
+	setVariable(fun -> reg, SVT_INT, 0);
+	return BR_CONTINUE;
+}
+
+builtIn(_rem_moviePlaying) {
+	UNUSEDALL
+	setVariable(fun -> reg, SVT_INT, 0);
+	return BR_CONTINUE;
+}
+
+builtIn(playMovie) {
+	UNUSEDALL
+	int fileNumber, r;
+
+	if (movieIsPlaying) return BR_PAUSE;
+
+	if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	r = playMovie(fileNumber);
+
+	setVariable(fun -> reg, SVT_INT, r);
+
+	if (r && (!fun->next)) {
+		restartFunction(fun);
+		return BR_ALREADY_GONE;
+	}
+	return BR_CONTINUE;
+}
+
+builtIn(stopMovie) {
+	UNUSEDALL
+	int r;
+
+	r = stopMovie();
+
+	setVariable(fun -> reg, SVT_INT, 0);
+	return BR_CONTINUE;
+}
+
+builtIn(pauseMovie) {
+	UNUSEDALL
+	int r;
+
+	r = pauseMovie();
+
+	setVariable(fun -> reg, SVT_INT, 0);
+	return BR_CONTINUE;
+}
+
+
+#pragma mark -
+#pragma mark Audio functions
+
+builtIn(startMusic) {
+	UNUSEDALL
+	int fromTrack, musChan, fileNumber;
+	if (!getValueType(fromTrack, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(musChan, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!playMOD(fileNumber, musChan, fromTrack)) return BR_CONTINUE;  //BR_ERROR;
+	return BR_CONTINUE;
+}
+
+builtIn(stopMusic) {
+	UNUSEDALL
+	int v;
+	if (!getValueType(v, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	stopMOD(v);
+	return BR_CONTINUE;
+}
+
+builtIn(setMusicVolume) {
+	UNUSEDALL
+	int musChan, v;
+	if (!getValueType(v, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(musChan, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	setMusicVolume(musChan, v);
+	return BR_CONTINUE;
+}
+
+builtIn(setDefaultMusicVolume) {
+	UNUSEDALL
+	int v;
+	if (!getValueType(v, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	setDefaultMusicVolume(v);
+	return BR_CONTINUE;
+}
+
+builtIn(playSound) {
+	UNUSEDALL
+	int fileNumber;
+	if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!startSound(fileNumber, false)) return BR_CONTINUE;    // Was BR_ERROR
+	return BR_CONTINUE;
+}
+builtIn(loopSound) {
+	UNUSEDALL
+	int fileNumber;
+
+	if (numParams < 1) {
+		fatal("Built-in function loopSound() must have at least 1 parameter.");
+		return BR_ERROR;
+	} else if (numParams < 2) {
+
+		if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
+		trimStack(fun -> stack);
+		if (!startSound(fileNumber, true)) return BR_CONTINUE;     // Was BR_ERROR
+		return BR_CONTINUE;
+	} else {
+		// We have more than one sound to play!
+
+		int doLoop = 2;
+		soundList *s = NULL;
+		soundList *old = NULL;
+
+		// Should we loop?
+		if (fun->stack->thisVar.varType != SVT_FILE) {
+			getValueType(doLoop, SVT_INT, fun -> stack -> thisVar);
+			trimStack(fun -> stack);
+			numParams--;
+		}
+		while (numParams) {
+			if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) {
+				fatal("Illegal parameter given built-in function loopSound().");
+				return BR_ERROR;
+			}
+			s = new soundList;
+			if (!checkNew(s)) return BR_ERROR;
+
+			s-> next = old;
+			s-> prev = NULL;
+			s-> sound = fileNumber;
+			old = s;
+
+			trimStack(fun->stack);
+			numParams--;
+		}
+		while (s->next) s = s-> next;
+		if (doLoop > 1) {
+			s->next = old;
+			old->prev = s;
+		} else if (doLoop) {
+			s->next = s;
+		}
+		old->vol = -1;
+		playSoundList(old);
+		return BR_CONTINUE;
+	}
+}
+
+builtIn(stopSound) {
+	UNUSEDALL
+	int v;
+	if (!getValueType(v, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	huntKillSound(v);
+	return BR_CONTINUE;
+}
+
+builtIn(setDefaultSoundVolume) {
+	UNUSEDALL
+	int v;
+	if (!getValueType(v, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	setDefaultSoundVolume(v);
+	return BR_CONTINUE;
+}
+
+builtIn(setSoundVolume) {
+	UNUSEDALL
+	int musChan, v;
+	if (!getValueType(v, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(musChan, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	setSoundVolume(musChan, v);
+	return BR_CONTINUE;
+}
+
+
+builtIn(setSoundLoopPoints) {
+	UNUSEDALL
+	int musChan, theEnd, theStart;
+	if (!getValueType(theEnd, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(theStart, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(musChan, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	setSoundLoop(musChan, theStart, theEnd);
+	return BR_CONTINUE;
+}
+
+#pragma mark -
+#pragma mark Extra room bits
+
+builtIn(setFloor) {
+	UNUSEDALL
+	if (fun -> stack -> thisVar.varType == SVT_FILE) {
+		int v;
+		getValueType(v, SVT_FILE, fun -> stack -> thisVar);
+		trimStack(fun -> stack);
+		if (!setFloor(v)) return BR_ERROR;
+	} else {
+		trimStack(fun -> stack);
+		setFloorNull();
+	}
+	return BR_CONTINUE;
+}
+
+builtIn(showFloor) {
+	UNUSEDALL
+	drawFloor();
+	return BR_CONTINUE;
+}
+
+builtIn(setZBuffer) {
+	UNUSEDALL
+	if (fun -> stack -> thisVar.varType == SVT_FILE) {
+		int v;
+		getValueType(v, SVT_FILE, fun -> stack -> thisVar);
+		trimStack(fun -> stack);
+		if (!setZBuffer(v)) return BR_ERROR;
+	} else {
+		trimStack(fun -> stack);
+		killZBuffer();
+	}
+	return BR_CONTINUE;
+}
+
+builtIn(setLightMap) {
+	UNUSEDALL
+	switch (numParams) {
+	case 2:
+		if (!getValueType(lightMapMode, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+		trimStack(fun -> stack);
+		lightMapMode %= LIGHTMAPMODE_NUM;
+	// No break;
+
+	case 1:
+		if (fun -> stack -> thisVar.varType == SVT_FILE) {
+			int v;
+			getValueType(v, SVT_FILE, fun -> stack -> thisVar);
+			trimStack(fun -> stack);
+			if (!loadLightMap(v)) return BR_ERROR;
+			setVariable(fun -> reg, SVT_INT, 1);
+		} else {
+			trimStack(fun -> stack);
+			killLightMap();
+			setVariable(fun -> reg, SVT_INT, 0);
+		}
+		break;
+
+	default:
+		fatal("Function should have either 2 or 3 parameters");
+		return BR_ERROR;
+	}
+	return BR_CONTINUE;
+}
+
+
+#pragma mark -
+#pragma mark Objects
+
+builtIn(setSpeechMode) {
+	UNUSEDALL
+	if (!getValueType(speechMode, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (speechMode < 0 || speechMode > 2) {
+		fatal("Valid parameters are be SPEECHANDTEXT, SPEECHONLY or TEXTONLY");
+		return BR_ERROR;
+	}
+	return BR_CONTINUE;
+}
+
+builtIn(somethingSpeaking) {
+	UNUSEDALL
+	int i = isThereAnySpeechGoingOn();
+	if (i == -1) {
+		setVariable(fun -> reg, SVT_INT, 0);
+	} else {
+		setVariable(fun -> reg, SVT_OBJTYPE, i);
+	}
+	return BR_CONTINUE;
+}
+
+builtIn(skipSpeech) {
+	UNUSEDALL
+	killSpeechTimers();
+	return BR_CONTINUE;
+}
+
+builtIn(getOverObject) {
+	UNUSEDALL
+	if (overRegion)
+		// Return value
+		setVariable(fun -> reg, SVT_OBJTYPE, overRegion -> thisType -> objectNum);
+	else
+		// Return value
+		setVariable(fun -> reg, SVT_INT, 0);
+	return BR_CONTINUE;
+}
+
+builtIn(rename) {
+	UNUSEDALL
+	char *newText = getTextFromAnyVar(fun -> stack -> thisVar);
+	int objT;
+	if (!newText) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(objT, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	objectType *o = findObjectType(objT);
+	delete o -> screenName;
+	o -> screenName = newText;
+	return BR_CONTINUE;
+}
+
+builtIn(getObjectX) {
+	UNUSEDALL
+	int objectNumber;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	onScreenPerson *pers = findPerson(objectNumber);
+	if (pers) {
+		setVariable(fun -> reg, SVT_INT, pers -> x);
+	} else {
+		screenRegion *la = getRegionForObject(objectNumber);
+		if (la) {
+			setVariable(fun -> reg, SVT_INT, la -> sX);
+		} else {
+			setVariable(fun -> reg, SVT_INT, 0);
+		}
+	}
+	return BR_CONTINUE;
+}
+
+builtIn(getObjectY) {
+	UNUSEDALL
+	int objectNumber;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	onScreenPerson *pers = findPerson(objectNumber);
+	if (pers) {
+		setVariable(fun -> reg, SVT_INT, pers -> y);
+	} else {
+		screenRegion *la = getRegionForObject(objectNumber);
+		if (la) {
+			setVariable(fun -> reg, SVT_INT, la -> sY);
+		} else {
+			setVariable(fun -> reg, SVT_INT, 0);
+		}
+	}
+	return BR_CONTINUE;
+}
+
+
+builtIn(addScreenRegion) {
+	UNUSEDALL
+	int sX, sY, x1, y1, x2, y2, di, objectNumber;
+	if (!getValueType(di, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(sY, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(sX, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(y2, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(x2, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(y1, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(x1, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (addScreenRegion(x1, y1, x2, y2, sX, sY, di, objectNumber)) return BR_CONTINUE;
+	return BR_ERROR;
+
+}
+
+builtIn(removeScreenRegion) {
+	UNUSEDALL
+	int objectNumber;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	removeScreenRegion(objectNumber);
+	return BR_CONTINUE;
+}
+
+builtIn(showBoxes) {
+	UNUSEDALL
+	showBoxes();
+	return BR_CONTINUE;
+}
+
+builtIn(removeAllScreenRegions) {
+	UNUSEDALL
+	killAllRegions();
+	return BR_CONTINUE;
+}
+
+builtIn(addCharacter) {
+	UNUSEDALL
+	persona *p;
+	int x, y, objectNumber;
+
+	p = getCostumeFromVar(fun -> stack -> thisVar);
+	if (p == NULL) return BR_ERROR;
+
+	trimStack(fun -> stack);
+	if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (addPerson(x, y, objectNumber, p)) return BR_CONTINUE;
+	return BR_ERROR;
+}
+
+builtIn(hideCharacter) {
+	UNUSEDALL
+	int objectNumber;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	setShown(false, objectNumber);
+	return BR_CONTINUE;
+}
+
+builtIn(showCharacter) {
+	UNUSEDALL
+	int objectNumber;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	setShown(true, objectNumber);
+	return BR_CONTINUE;
+}
+
+builtIn(removeAllCharacters) {
+	UNUSEDALL
+	killSpeechTimers();
+	killMostPeople();
+	return BR_CONTINUE;
+}
+
+builtIn(setCharacterDrawMode) {
+	UNUSEDALL
+	int obj, di;
+	if (!getValueType(di, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	setDrawMode(di, obj);
+	return BR_CONTINUE;
+}
+builtIn(setCharacterTransparency) {
+	UNUSEDALL
+	int obj, x;
+	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	setPersonTransparency(obj, x);
+	return BR_CONTINUE;
+}
+builtIn(setCharacterColourise) {
+	UNUSEDALL
+	int obj, r, g, b, mix;
+	if (!getValueType(mix, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(b, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(g, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(r, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	setPersonColourise(obj, r, g, b, mix);
+	return BR_CONTINUE;
+}
+
+builtIn(setScale) {
+	UNUSEDALL
+	int val1, val2;
+	if (!getValueType(val2, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(val1, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	setScale((short int) val1, (short int) val2);
+	return BR_CONTINUE;
+}
+
+builtIn(stopCharacter) {
+	UNUSEDALL
+	int obj;
+	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	// Return value
+	setVariable(fun -> reg, SVT_INT, stopPerson(obj));
+	return BR_CONTINUE;
+}
+
+builtIn(pasteCharacter) {
+	UNUSEDALL
+	int obj;
+	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	onScreenPerson *thisPerson = findPerson(obj);
+	if (thisPerson) {
+		personaAnimation *myAnim;
+		myAnim = thisPerson -> myAnim;
+		if (myAnim != thisPerson -> lastUsedAnim) {
+			thisPerson -> lastUsedAnim = myAnim;
+			thisPerson -> frameNum = 0;
+			thisPerson -> frameTick = myAnim -> frames[0].howMany;
+		}
+
+		int fNum = myAnim -> frames[thisPerson -> frameNum].frameNum;
+		fixScaleSprite(thisPerson -> x, thisPerson -> y, myAnim -> theSprites -> bank.sprites[abs(fNum)], myAnim -> theSprites -> bank.myPalette, thisPerson, 0, 0, fNum < 0);
+		setVariable(fun -> reg, SVT_INT, 1);
+	} else {
+		setVariable(fun -> reg, SVT_INT, 0);
+	}
+	return BR_CONTINUE;
+}
+
+builtIn(animate) {
+	UNUSEDALL
+	int obj;
+	personaAnimation *pp = getAnimationFromVar(fun -> stack -> thisVar);
+	if (pp == NULL) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	animatePerson(obj, pp);
+	setVariable(fun -> reg, SVT_INT, timeForAnim(pp));
+	return BR_CONTINUE;
+}
+
+builtIn(setCostume) {
+	UNUSEDALL
+	int obj;
+	persona *pp = getCostumeFromVar(fun -> stack -> thisVar);
+	if (pp == NULL) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	animatePerson(obj, pp);
+	return BR_CONTINUE;
+}
+
+builtIn(floatCharacter) {
+	UNUSEDALL
+	int obj, di;
+	if (!getValueType(di, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	setVariable(fun -> reg, SVT_INT, floatCharacter(di, obj));
+	return BR_CONTINUE;
+}
+
+builtIn(setCharacterWalkSpeed) {
+	UNUSEDALL
+	int obj, di;
+	if (!getValueType(di, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	setVariable(fun -> reg, SVT_INT, setCharacterWalkSpeed(di, obj));
+	return BR_CONTINUE;
+}
+
+builtIn(turnCharacter) {
+	UNUSEDALL
+	int obj, di;
+	if (!getValueType(di, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	setVariable(fun -> reg, SVT_INT, turnPersonToFace(obj, di));
+	return BR_CONTINUE;
+}
+
+builtIn(setCharacterExtra) {
+	UNUSEDALL
+	int obj, di;
+	if (!getValueType(di, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	setVariable(fun -> reg, SVT_INT, setPersonExtra(obj, di));
+	return BR_CONTINUE;
+}
+
+builtIn(removeCharacter) {
+	UNUSEDALL
+	int objectNumber;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	removeOneCharacter(objectNumber);
+	return BR_CONTINUE;
+}
+
+static builtReturn moveChr(int numParams, loadedFunction *fun, bool force, bool immediate) {
+	switch (numParams) {
+	case 3: {
+		int x, y, objectNumber;
+
+		if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+		trimStack(fun -> stack);
+		if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+		trimStack(fun -> stack);
+		if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+		trimStack(fun -> stack);
+
+		if (force) {
+			if (forceWalkingPerson(x, y, objectNumber, fun, -1)) return BR_PAUSE;
+		} else if (immediate) {
+			jumpPerson(x, y, objectNumber);
+		} else {
+			if (makeWalkingPerson(x, y, objectNumber, fun, -1)) return BR_PAUSE;
+		}
+		return BR_CONTINUE;
+	}
+
+	case 2: {
+		int toObj, objectNumber;
+		screenRegion *reggie;
+
+		if (!getValueType(toObj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+		trimStack(fun -> stack);
+		if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+		trimStack(fun -> stack);
+		reggie = getRegionForObject(toObj);
+		if (reggie == NULL) return BR_CONTINUE;
+
+		if (force) {
+			if (forceWalkingPerson(reggie -> sX, reggie -> sY, objectNumber, fun, reggie -> di)) return BR_PAUSE;
+		} else if (immediate) {
+			jumpPerson(reggie -> sX, reggie -> sY, objectNumber);
+		} else {
+			if (makeWalkingPerson(reggie -> sX, reggie -> sY, objectNumber, fun, reggie -> di)) return BR_PAUSE;
+		}
+		return BR_CONTINUE;
+	}
+
+	default:
+		fatal("Built-in function must have either 2 or 3 parameters.");
+		return BR_ERROR;
+	}
+}
+
+builtIn(moveCharacter) {
+	UNUSEDALL
+	return moveChr(numParams, fun, false, false);
+}
+
+builtIn(forceCharacter) {
+	UNUSEDALL
+	return moveChr(numParams, fun, true, false);
+}
+
+builtIn(jumpCharacter) {
+	UNUSEDALL
+	return moveChr(numParams, fun, false, true);
+}
+
+builtIn(clearStatus) {
+	UNUSEDALL
+	clearStatusBar();
+	return BR_CONTINUE;
+}
+
+builtIn(removeLastStatus) {
+	UNUSEDALL
+	killLastStatus();
+	return BR_CONTINUE;
+}
+
+builtIn(addStatus) {
+	UNUSEDALL
+	addStatusBar();
+	return BR_CONTINUE;
+}
+
+builtIn(statusText) {
+	UNUSEDALL
+	char *newText = getTextFromAnyVar(fun -> stack -> thisVar);
+	if (!newText) return BR_ERROR;
+	trimStack(fun -> stack);
+	setStatusBar(newText);
+	delete newText;
+	return BR_CONTINUE;
+}
+
+builtIn(lightStatus) {
+	UNUSEDALL
+	int val;
+	if (!getValueType(val, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	setLitStatus(val);
+	return BR_CONTINUE;
+}
+
+builtIn(positionStatus) {
+	UNUSEDALL
+	int x, y;
+	if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	positionStatus(x, y);
+	return BR_CONTINUE;
+}
+
+builtIn(alignStatus) {
+	UNUSEDALL
+	int val;
+	if (!getValueType(val, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	nowStatus -> alignStatus = (short) val;
+	return BR_CONTINUE;
+}
+
+static bool getFuncNumForCallback(int numParams, loadedFunction *fun, int &functionNum) {
+	switch (numParams) {
+	case 0:
+		functionNum = 0;
+		break;
+
+	case 1:
+		if (!getValueType(functionNum, SVT_FUNC, fun -> stack -> thisVar)) return false;
+		trimStack(fun -> stack);
+		break;
+
+	default:
+		fatal("Too many parameters.");
+		return false;
+	}
+	return true;
+}
+
+builtIn(onLeftMouse) {
+	UNUSEDALL
+	int functionNum;
+	if (getFuncNumForCallback(numParams, fun, functionNum)) {
+		currentEvents -> leftMouseFunction = functionNum;
+		return BR_CONTINUE;
+	}
+	return BR_ERROR;
+}
+
+builtIn(onLeftMouseUp) {
+	UNUSEDALL
+	int functionNum;
+	if (getFuncNumForCallback(numParams, fun, functionNum)) {
+		currentEvents -> leftMouseUpFunction = functionNum;
+		return BR_CONTINUE;
+	}
+	return BR_ERROR;
+}
+
+builtIn(onRightMouse) {
+	UNUSEDALL
+	int functionNum;
+	if (getFuncNumForCallback(numParams, fun, functionNum)) {
+		currentEvents -> rightMouseFunction = functionNum;
+		return BR_CONTINUE;
+	}
+	return BR_ERROR;
+}
+
+builtIn(onRightMouseUp) {
+	UNUSEDALL
+	int functionNum;
+	if (getFuncNumForCallback(numParams, fun, functionNum)) {
+		currentEvents -> rightMouseUpFunction = functionNum;
+		return BR_CONTINUE;
+	}
+	return BR_ERROR;
+}
+
+builtIn(onFocusChange) {
+	UNUSEDALL
+	int functionNum;
+	if (getFuncNumForCallback(numParams, fun, functionNum)) {
+		currentEvents -> focusFunction = functionNum;
+		return BR_CONTINUE;
+	}
+	return BR_ERROR;
+}
+
+builtIn(onMoveMouse) {
+	UNUSEDALL
+	int functionNum;
+	if (getFuncNumForCallback(numParams, fun, functionNum)) {
+		currentEvents -> moveMouseFunction = functionNum;
+		return BR_CONTINUE;
+	}
+	return BR_ERROR;
+}
+
+builtIn(onKeyboard) {
+	UNUSEDALL
+	int functionNum;
+	if (getFuncNumForCallback(numParams, fun, functionNum)) {
+		currentEvents -> spaceFunction = functionNum;
+		return BR_CONTINUE;
+	}
+	return BR_ERROR;
+}
+
+builtIn(spawnSub) {
+	UNUSEDALL
+	int functionNum;
+	if (getFuncNumForCallback(numParams, fun, functionNum)) {
+		if (!startNewFunctionNum(functionNum, 0, NULL, noStack)) return BR_ERROR;
+		return BR_CONTINUE;
+	}
+	return BR_ERROR;
+}
+
+builtIn(cancelSub) {
+	UNUSEDALL
+	int functionNum;
+	if (getFuncNumForCallback(numParams, fun, functionNum)) {
+		bool killedMyself;
+		cancelAFunction(functionNum, fun, killedMyself);
+		if (killedMyself) {
+			abortFunction(fun);
+			return BR_ALREADY_GONE;
+		}
+		return BR_CONTINUE;
+	}
+	return BR_ERROR;
+}
+
+builtIn(stringWidth) {
+	UNUSEDALL
+	char *theText = getTextFromAnyVar(fun -> stack -> thisVar);
+	if (!theText) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	// Return value
+	setVariable(fun -> reg, SVT_INT, stringWidth(theText));
+	delete theText;
+	return BR_CONTINUE;
+}
+
+builtIn(hardScroll) {
+	UNUSEDALL
+	int v;
+	if (!getValueType(v, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	hardScroll(v);
+	return BR_CONTINUE;
+}
+
+
+builtIn(isScreenRegion) {
+	UNUSEDALL
+	int objectNumber;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	setVariable(fun -> reg, SVT_INT, getRegionForObject(objectNumber) != NULL);
+	return BR_CONTINUE;
+}
+
+builtIn(setSpeechSpeed) {
+	UNUSEDALL
+	int number;
+	if (!getValueType(number, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	speechSpeed = number * 0.01;
+	setVariable(fun -> reg, SVT_INT, 1);
+	return BR_CONTINUE;
+}
+
+builtIn(setFontSpacing) {
+	UNUSEDALL
+	int fontSpaceI;
+	if (!getValueType(fontSpaceI, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	fontSpace = fontSpaceI;
+	trimStack(fun -> stack);
+	setVariable(fun -> reg, SVT_INT, 1);
+	return BR_CONTINUE;
+}
+
+builtIn(transitionLevel) {
+	UNUSEDALL
+	int number;
+	if (!getValueType(number, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	if (number < 0)
+		brightnessLevel = 0;
+	else if (number > 255)
+		brightnessLevel = 255;
+	else
+		brightnessLevel = number;
+
+	setVariable(fun -> reg, SVT_INT, 1);
+	return BR_CONTINUE;
+}
+
+builtIn(captureAllKeys) {
+	UNUSEDALL
+	captureAllKeys = getBoolean(fun -> stack -> thisVar);
+	trimStack(fun -> stack);
+	setVariable(fun -> reg, SVT_INT, captureAllKeys);
+	return BR_CONTINUE;
+}
+
+
+builtIn(spinCharacter) {
+	UNUSEDALL
+	int number, objectNumber;
+	if (!getValueType(number, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	onScreenPerson *thisPerson = findPerson(objectNumber);
+	if (thisPerson) {
+		thisPerson -> wantAngle = number;
+		thisPerson -> spinning = true;
+		thisPerson -> continueAfterWalking = fun;
+		setVariable(fun -> reg, SVT_INT, 1);
+		return BR_PAUSE;
+	} else {
+		setVariable(fun -> reg, SVT_INT, 0);
+		return BR_CONTINUE;
+	}
+}
+
+builtIn(getCharacterDirection) {
+	UNUSEDALL
+	int objectNumber;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	onScreenPerson *thisPerson = findPerson(objectNumber);
+	if (thisPerson) {
+		setVariable(fun -> reg, SVT_INT, thisPerson -> direction);
+	} else {
+		setVariable(fun -> reg, SVT_INT, 0);
+	}
+	return BR_CONTINUE;
+}
+
+builtIn(isCharacter) {
+	UNUSEDALL
+	int objectNumber;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	onScreenPerson *thisPerson = findPerson(objectNumber);
+	setVariable(fun -> reg, SVT_INT, thisPerson != NULL);
+	return BR_CONTINUE;
+}
+
+builtIn(normalCharacter) {
+	UNUSEDALL
+	int objectNumber;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	onScreenPerson *thisPerson = findPerson(objectNumber);
+	if (thisPerson) {
+		thisPerson -> myAnim = thisPerson -> myPersona -> animation[thisPerson -> direction];
+		setVariable(fun -> reg, SVT_INT, 1);
+	} else {
+		setVariable(fun -> reg, SVT_INT, 0);
+	}
+	return BR_CONTINUE;
+}
+
+builtIn(isMoving) {
+	UNUSEDALL
+	int objectNumber;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	onScreenPerson *thisPerson = findPerson(objectNumber);
+	if (thisPerson) {
+		setVariable(fun -> reg, SVT_INT, thisPerson -> walking);
+	} else {
+		setVariable(fun -> reg, SVT_INT, 0);
+	}
+	return BR_CONTINUE;
+}
+
+builtIn(fetchEvent) {
+	UNUSEDALL
+	int obj1, obj2;
+	if (!getValueType(obj2, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(obj1, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	int fNum = getCombinationFunction(obj1, obj2);
+
+	// Return value
+	if (fNum) {
+		setVariable(fun -> reg, SVT_FUNC, fNum);
+	} else {
+		setVariable(fun -> reg, SVT_INT, 0);
+	}
+	return BR_CONTINUE;
+}
+
+builtIn(deleteFile) {
+	UNUSEDALL
+
+	char *namNormal = getTextFromAnyVar(fun -> stack -> thisVar);
+	trimStack(fun -> stack);
+	char *nam = encodeFilename(namNormal);
+	delete namNormal;
+	if (failSecurityCheck(nam)) return BR_ERROR;
+	setVariable(fun -> reg, SVT_INT, remove(nam));
+	delete nam;
+
+	return BR_CONTINUE;
+}
+
+builtIn(renameFile) {
+	UNUSEDALL
+	char *temp;
+
+	temp = getTextFromAnyVar(fun -> stack -> thisVar);
+	char *newnam = encodeFilename(temp);
+	trimStack(fun -> stack);
+	if (failSecurityCheck(newnam)) return BR_ERROR;
+	delete temp;
+
+	temp = getTextFromAnyVar(fun -> stack -> thisVar);
+	char *nam = encodeFilename(temp);
+	trimStack(fun -> stack);
+	if (failSecurityCheck(nam)) return BR_ERROR;
+	delete temp;
+
+	setVariable(fun -> reg, SVT_INT, rename(nam, newnam));
+	delete nam;
+	delete newnam;
+
+
+	return BR_CONTINUE;
+}
+
+builtIn(cacheSound) {
+	UNUSEDALL
+	int fileNumber;
+	if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (cacheSound(fileNumber) == -1) return BR_ERROR;
+	return BR_CONTINUE;
+}
+
+builtIn(burnString) {
+	UNUSEDALL
+	char *newText = getTextFromAnyVar(fun -> stack -> thisVar);
+	trimStack(fun -> stack);
+	int y, x;
+	if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (x == IN_THE_CENTRE) x = (winWidth - stringWidth(newText)) >> 1;
+	fixFont(pastePalette);
+	burnStringToBackdrop(newText, x, y, pastePalette);
+	delete[] newText;
+	return BR_CONTINUE;
+}
+
+builtIn(setCharacterSpinSpeed) {
+	UNUSEDALL
+	int speed, who;
+	if (!getValueType(speed, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(who, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	onScreenPerson *thisPerson = findPerson(who);
+
+	if (thisPerson) {
+		thisPerson -> spinSpeed = speed;
+		setVariable(fun -> reg, SVT_INT, 1);
+	} else {
+		setVariable(fun -> reg, SVT_INT, 0);
+	}
+	return BR_CONTINUE;
+}
+
+builtIn(setCharacterAngleOffset) {
+	UNUSEDALL
+	int angle, who;
+	if (!getValueType(angle, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(who, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	onScreenPerson *thisPerson = findPerson(who);
+
+	if (thisPerson) {
+		thisPerson -> angleOffset = angle;
+		setVariable(fun -> reg, SVT_INT, 1);
+	} else {
+		setVariable(fun -> reg, SVT_INT, 0);
+	}
+	return BR_CONTINUE;
+}
+
+
+builtIn(transitionMode) {
+	UNUSEDALL
+	int n;
+	if (!getValueType(n, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	fadeMode = n;
+	trimStack(fun -> stack);
+	setVariable(fun -> reg, SVT_INT, 1);
+	return BR_CONTINUE;
+}
+
+
+// Removed function - does nothing
+builtIn(_rem_updateDisplay) {
+	UNUSEDALL
+	trimStack(fun -> stack);
+	setVariable(fun -> reg, SVT_INT, true);
+	return BR_CONTINUE;
+}
+
+builtIn(getSoundCache) {
+	UNUSEDALL
+	fun -> reg.varType = SVT_STACK;
+	fun -> reg.varData.theStack = new stackHandler;
+	if (!checkNew(fun -> reg.varData.theStack)) return BR_ERROR;
+	fun -> reg.varData.theStack -> first = NULL;
+	fun -> reg.varData.theStack -> last = NULL;
+	fun -> reg.varData.theStack -> timesUsed = 1;
+	if (!getSoundCacheStack(fun -> reg.varData.theStack)) return BR_ERROR;
+	return BR_CONTINUE;
+}
+
+builtIn(saveCustomData) {
+	UNUSEDALL
+	// saveCustomData (thisStack, fileName);
+	char *fileNameB = getTextFromAnyVar(fun -> stack -> thisVar);
+	if (!checkNew(fileNameB)) return BR_ERROR;
+
+	char *fileName = encodeFilename(fileNameB);
+	delete fileNameB;
+
+	if (failSecurityCheck(fileName)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	if (fun -> stack -> thisVar.varType != SVT_STACK) {
+		fatal("First parameter isn't a stack");
+		return BR_ERROR;
+	}
+	if (!stackToFile(fileName, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	delete fileName;
+	return BR_CONTINUE;
+}
+
+builtIn(loadCustomData) {
+	UNUSEDALL
+
+	char *newTextA = getTextFromAnyVar(fun -> stack -> thisVar);
+	if (!checkNew(newTextA)) return BR_ERROR;
+
+	char *newText = encodeFilename(newTextA);
+	delete newTextA;
+
+	if (failSecurityCheck(newText)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	unlinkVar(fun -> reg);
+	fun -> reg.varType = SVT_STACK;
+	fun -> reg.varData.theStack = new stackHandler;
+	if (!checkNew(fun -> reg.varData.theStack)) return BR_ERROR;
+	fun -> reg.varData.theStack -> first = NULL;
+	fun -> reg.varData.theStack -> last = NULL;
+	fun -> reg.varData.theStack -> timesUsed = 1;
+	if (!fileToStack(newText, fun -> reg.varData.theStack)) return BR_ERROR;
+	delete newText;
+	return BR_CONTINUE;
+}
+
+builtIn(setCustomEncoding) {
+	UNUSEDALL
+	int n;
+	if (!getValueType(n, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	saveEncoding = n;
+	trimStack(fun -> stack);
+	setVariable(fun -> reg, SVT_INT, 1);
+	return BR_CONTINUE;
+}
+
+builtIn(freeSound) {
+	UNUSEDALL
+	int v;
+	if (!getValueType(v, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	huntKillFreeSound(v);
+	return BR_CONTINUE;
+}
+
+builtIn(parallaxAdd) {
+	UNUSEDALL
+	if (frozenStuff) {
+		fatal("Can't set background parallax image while frozen");
+		return BR_ERROR;
+	} else {
+		int wrapX, wrapY, v;
+		if (!getValueType(wrapY, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+		trimStack(fun -> stack);
+		if (!getValueType(wrapX, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+		trimStack(fun -> stack);
+		if (!getValueType(v, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
+		trimStack(fun -> stack);
+
+		if (!loadParallax(v, wrapX, wrapY)) return BR_ERROR;
+		setVariable(fun -> reg, SVT_INT, 1);
+	}
+	return BR_CONTINUE;
+}
+
+builtIn(parallaxClear) {
+	UNUSEDALL
+	killParallax();
+	setVariable(fun -> reg, SVT_INT, 1);
+	return BR_CONTINUE;
+}
+
+builtIn(getPixelColour) {
+	UNUSEDALL
+	int x, y;
+	if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	unlinkVar(fun -> reg);
+	fun -> reg.varType = SVT_STACK;
+	fun -> reg.varData.theStack = new stackHandler;
+	if (!checkNew(fun -> reg.varData.theStack)) return BR_ERROR;
+	fun -> reg.varData.theStack -> first = NULL;
+	fun -> reg.varData.theStack -> last = NULL;
+	fun -> reg.varData.theStack -> timesUsed = 1;
+	if (!getRGBIntoStack(x, y, fun -> reg.varData.theStack)) return BR_ERROR;
+
+	return BR_CONTINUE;
+}
+
+builtIn(makeFastArray) {
+	UNUSEDALL
+	switch (fun -> stack -> thisVar.varType) {
+	case SVT_STACK: {
+		bool success = makeFastArrayFromStack(fun -> reg, fun -> stack -> thisVar.varData.theStack);
+		trimStack(fun -> stack);
+		return success ? BR_CONTINUE : BR_ERROR;
+	}
+	break;
+
+	case SVT_INT: {
+		int i = fun -> stack -> thisVar.varData.intValue;
+		trimStack(fun -> stack);
+		return makeFastArraySize(fun -> reg, i) ? BR_CONTINUE : BR_ERROR;
+	}
+	break;
+
+	default:
+		break;
+	}
+	fatal("Parameter must be a number or a stack.");
+	return BR_ERROR;
+}
+
+builtIn(getCharacterScale) {
+	UNUSEDALL
+	int objectNumber;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	onScreenPerson *pers = findPerson(objectNumber);
+	if (pers) {
+		setVariable(fun -> reg, SVT_INT, pers -> scale * 100);
+	} else {
+		setVariable(fun -> reg, SVT_INT, 0);
+	}
+	return BR_CONTINUE;
+}
+
+builtIn(getLanguageID) {
+	UNUSEDALL
+	setVariable(fun -> reg, SVT_INT, gameSettings.languageID);
+	return BR_CONTINUE;
+}
+
+// Removed function
+builtIn(_rem_launchWith) {
+	UNUSEDALL
+
+	trimStack(fun -> stack);
+	trimStack(fun -> stack);
+	setVariable(fun -> reg, SVT_INT, false);
+
+	return BR_CONTINUE;
+
+}
+
+builtIn(getFramesPerSecond) {
+	UNUSEDALL
+	setVariable(fun -> reg, SVT_INT, lastFramesPerSecond);
+	return BR_CONTINUE;
+}
+
+builtIn(showThumbnail) {
+	UNUSEDALL
+	int x, y;
+	if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+
+	// Encode the name!Encode the name!
+	char *aaaaa = getTextFromAnyVar(fun -> stack -> thisVar);
+	//              deb ("Got name:", aaaaa;)
+	trimStack(fun -> stack);
+	//              deb ("About to encode", aaaaa);
+	char *file = encodeFilename(aaaaa);
+	//              deb ("Made new name", file);
+	//              deb ("aaaaa is still ", aaaaa);
+	delete[] aaaaa;
+	//              deb ("Deleted", "aaaaa");
+	showThumbnail(file, x, y);
+	delete[] file;
+	return BR_CONTINUE;
+}
+
+builtIn(setThumbnailSize) {
+	UNUSEDALL
+	if (!getValueType(thumbHeight, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(thumbWidth, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (thumbWidth < 0 || thumbHeight < 0 || thumbWidth > winWidth || thumbHeight > winHeight) {
+		char buff[50];
+		sprintf(buff, "%d x %d", thumbWidth, thumbHeight);
+		fatal("Invalid thumbnail size", buff);
+		return BR_ERROR;
+	}
+	return BR_CONTINUE;
+}
+
+builtIn(hasFlag) {
+	UNUSEDALL
+	int objNum, flagIndex;
+	if (!getValueType(flagIndex, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	if (!getValueType(objNum, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun -> stack);
+	objectType *objT = findObjectType(objNum);
+	if (!objT) return BR_ERROR;
+	setVariable(fun -> reg, SVT_INT, objT->flags & (1 << flagIndex));
+	return BR_CONTINUE;
+}
+
+builtIn(snapshotGrab) {
+	UNUSEDALL
+	return snapshot() ? BR_CONTINUE : BR_ERROR;
+}
+
+builtIn(snapshotClear) {
+	UNUSEDALL
+	nosnapshot();
+	return BR_CONTINUE;
+}
+
+builtIn(bodgeFilenames) {
+	UNUSEDALL
+	bool lastValue = allowAnyFilename;
+	allowAnyFilename = getBoolean(fun -> stack -> thisVar);
+	trimStack(fun -> stack);
+	setVariable(fun -> reg, SVT_INT, lastValue);
+	return BR_CONTINUE;
+}
+
+// Deprecated - does nothing.
+builtIn(_rem_registryGetString) {
+	UNUSEDALL
+	trimStack(fun -> stack);
+	trimStack(fun -> stack);
+	setVariable(fun -> reg, SVT_INT, 0);
+
+	return BR_CONTINUE;
+}
+
+builtIn(quitWithFatalError) {
+	UNUSEDALL
+	char *mess = getTextFromAnyVar(fun -> stack -> thisVar);
+	trimStack(fun -> stack);
+	fatal(mess);
+	return BR_ERROR;
+}
+
+builtIn(_rem_setCharacterAA) {
+	UNUSEDALL
+
+	trimStack(fun -> stack);
+	trimStack(fun -> stack);
+	trimStack(fun -> stack);
+	trimStack(fun -> stack);
+
+	return BR_CONTINUE;
+}
+
+builtIn(_rem_setMaximumAA) {
+	UNUSEDALL
+
+	trimStack(fun -> stack);
+	trimStack(fun -> stack);
+	trimStack(fun -> stack);
+
+	return BR_CONTINUE;
+
+}
+
+builtIn(setBackgroundEffect) {
+	UNUSEDALL
+	bool done = blur_createSettings(numParams, fun->stack);
+	setVariable(fun -> reg, SVT_INT, done ? 1 : 0);
+	return BR_CONTINUE;
+}
+
+builtIn(doBackgroundEffect) {
+	UNUSEDALL
+	bool done = blurScreen();
+	setVariable(fun -> reg, SVT_INT, done ? 1 : 0);
+	return BR_CONTINUE;
+}
+
+#pragma mark -
+#pragma mark Other functions
+
+//-------------------------------------
+
+#define FUNC(special,name)      {builtIn_ ## name},
+static builtInFunctionData builtInFunctionArray[] = {
+#include "CommonCode/functionlist.h"
+};
+#undef FUNC
+
+#define FUNC(special,name)      {#name},
+char builtInFunctionNames[][25] = {
+#include "CommonCode/functionlist.h"
+};
+#undef FUNC
+
+#define NUM_FUNCS           (sizeof (builtInFunctionArray) / sizeof (builtInFunctionArray[0]))
+
+
+
+builtReturn callBuiltIn(int whichFunc, int numParams, loadedFunction *fun) {
+	// fprintf (stderr, "Calling function %d: %s\n", whichFunc, builtInFunctionNames[whichFunc]);    fflush (stderr);
+	if (numBIFNames) {
+
+		//      deb ("IN:", (fun -> originalNumber < numUserFunc) ? allUserFunc[fun -> originalNumber] : "Unknown user function");
+		//      deb ("GO:", (whichFunc < numBIFNames) ? allBIFNames[whichFunc] : "Unknown built-in function");
+
+		setFatalInfo(
+		    (fun -> originalNumber < numUserFunc) ? allUserFunc[fun -> originalNumber] : "Unknown user function",
+		    (whichFunc < numBIFNames) ? allBIFNames[whichFunc] : "Unknown built-in function");
+	}
+
+	if (whichFunc < NUM_FUNCS) {
+		if (paramNum[whichFunc] != -1) {
+			if (paramNum[whichFunc] != numParams) {
+				char buff[100];
+				sprintf(buff, "Built in function must have %i parameter%s",
+				        paramNum[whichFunc],
+				        (paramNum[whichFunc] == 1) ? "" : "s");
+
+				fatal(copyString(buff));
+				return BR_ERROR;
+			}
+		}
+
+		if (builtInFunctionArray[whichFunc].func) {
+			//fprintf (stderr, "Calling %i: %s\n", whichFunc, builtInFunctionNames[whichFunc]);
+			return builtInFunctionArray[whichFunc].func(numParams, fun);
+		}
+	}
+
+	fatal("Unknown / unimplemented built-in function.");
+	return BR_ERROR;
+}
+
diff --git a/engines/sludge/builtin.h b/engines/sludge/builtin.h
new file mode 100644
index 0000000..8f5ac59
--- /dev/null
+++ b/engines/sludge/builtin.h
@@ -0,0 +1,31 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef SLUDGE_BUILTIN_H
+#define SLUDGE_BUILTIN_H
+
+enum builtReturn {BR_KEEP_AND_PAUSE, BR_ERROR, BR_CONTINUE, BR_PAUSE, BR_CALLAFUNC, BR_ALREADY_GONE};
+
+bool failSecurityCheck(char *fn);
+builtReturn callBuiltIn(int whichFunc, int numParams, loadedFunction *fun);
+
+#endif
diff --git a/engines/sludge/color.frag b/engines/sludge/color.frag
new file mode 100644
index 0000000..1f3e45a
--- /dev/null
+++ b/engines/sludge/color.frag
@@ -0,0 +1,7 @@
+varying vec4 color;
+
+void main(void)
+{
+	gl_FragColor = color;
+}
+
diff --git a/engines/sludge/color.vert b/engines/sludge/color.vert
new file mode 100644
index 0000000..819d377
--- /dev/null
+++ b/engines/sludge/color.vert
@@ -0,0 +1,13 @@
+attribute vec4 myVertex;
+
+uniform mat4 myPMVMatrix;
+uniform vec4 myColor;
+
+varying vec4 color;
+
+void main(void)
+{
+	gl_Position = myPMVMatrix * myVertex;
+	color = myColor;
+}
+
diff --git a/engines/sludge/colours.h b/engines/sludge/colours.h
new file mode 100644
index 0000000..503823f
--- /dev/null
+++ b/engines/sludge/colours.h
@@ -0,0 +1,47 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef SLUDGE_COLOURS_H
+#define SLUDGE_COLOURS_H
+
+// Simple colour conversion routines to deal with 16-bit graphics
+//unsigned short int makeColour (byte r, byte g, byte b);
+
+inline unsigned short redValue(unsigned short c) {
+	return (c >> 11) << 3;
+}
+inline unsigned short greenValue(unsigned short c) {
+	return ((c >> 5) & 63) << 2;
+}
+inline unsigned short blueValue(unsigned short c) {
+	return (c & 31) << 3;
+}
+
+inline unsigned short makeGrey(unsigned short int r) {
+	return ((r >> 3) << 11) | ((r >> 2) << 5) | (r >> 3);
+}
+
+inline unsigned short makeColour(unsigned short int r, unsigned short int g, unsigned short int b) {
+	return ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3);
+}
+
+#endif
diff --git a/engines/sludge/csludge.h b/engines/sludge/csludge.h
new file mode 100644
index 0000000..3c73a9d1
--- /dev/null
+++ b/engines/sludge/csludge.h
@@ -0,0 +1,43 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef SLUDGE_CSLUDGE_H
+#define SLUDGE_CSLUDGE_H
+
+enum sludgeCommand {SLU_UNKNOWN,
+                    SLU_RETURN, SLU_BRANCH, SLU_BR_ZERO, SLU_SET_GLOBAL,
+                    SLU_SET_LOCAL, SLU_LOAD_GLOBAL, SLU_LOAD_LOCAL,
+                    SLU_PLUS, SLU_MINUS, SLU_MULT, SLU_DIVIDE,
+                    SLU_AND, SLU_OR, SLU_EQUALS, SLU_NOT_EQ, SLU_MODULUS,
+                    SLU_LOAD_VALUE, SLU_LOAD_BUILT, SLU_LOAD_FUNC, SLU_CALLIT,
+                    SLU_LOAD_STRING, SLU_LOAD_FILE, /*SLU_LOAD_SCENE,*/ SLU_LOAD_OBJTYPE,
+                    SLU_NOT, SLU_LOAD_NULL, SLU_STACK_PUSH, SLU_LESSTHAN, SLU_MORETHAN, SLU_NEGATIVE,
+                    SLU_UNREG, SLU_LESS_EQUAL, SLU_MORE_EQUAL,
+                    SLU_INCREMENT_LOCAL,
+                    SLU_DECREMENT_LOCAL,
+                    SLU_INCREMENT_GLOBAL,
+                    SLU_DECREMENT_GLOBAL, SLU_INDEXSET, SLU_INDEXGET,
+                    SLU_INCREMENT_INDEX, SLU_DECREMENT_INDEX, SLU_QUICK_PUSH,
+                    numSludgeCommands
+                   };
+
+#endif
diff --git a/engines/sludge/cursors.cpp b/engines/sludge/cursors.cpp
new file mode 100644
index 0000000..6ad3a35
--- /dev/null
+++ b/engines/sludge/cursors.cpp
@@ -0,0 +1,86 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#if 0
+#if !defined(HAVE_GLES2)
+#include "GLee.h"
+#else
+#include <GLES2/gl2.h>
+#endif
+#endif
+
+#include "allfiles.h"
+#include "cursors.h"
+#include "colours.h"
+#include "sprites.h"
+#include "sprbanks.h"
+#include "people.h"
+#include "sludger.h"
+
+personaAnimation *mouseCursorAnim;
+int mouseCursorFrameNum = 0;
+int mouseCursorCountUp = 0;
+
+extern inputType input;
+
+void pickAnimCursor(personaAnimation *pp) {
+	deleteAnim(mouseCursorAnim);
+	mouseCursorAnim = pp;
+	mouseCursorFrameNum = 0;
+	mouseCursorCountUp = 0;
+}
+
+void displayCursor() {
+#if 0
+	if (mouseCursorAnim && mouseCursorAnim -> numFrames) {
+
+		int spriteNum = mouseCursorAnim -> frames[mouseCursorFrameNum].frameNum;
+		int flipMe = 0;
+
+		if (spriteNum < 0) {
+			spriteNum = -spriteNum;
+			flipMe = 1;
+			if (spriteNum >= mouseCursorAnim -> theSprites -> bank.total) spriteNum = 0;
+		} else {
+			if (spriteNum >= mouseCursorAnim -> theSprites -> bank.total) flipMe = 2;
+		}
+
+		if (flipMe != 2) {
+			(flipMe ? flipFontSprite : fontSprite)(input.mouseX, input.mouseY,
+			                                       mouseCursorAnim -> theSprites -> bank.sprites[spriteNum],
+			                                       mouseCursorAnim -> theSprites -> bank.myPalette /* ( spritePalette&) NULL*/);
+		}
+
+		if (++ mouseCursorCountUp >= mouseCursorAnim -> frames[mouseCursorFrameNum].howMany) {
+			mouseCursorCountUp = 0;
+			mouseCursorFrameNum ++;
+			mouseCursorFrameNum %= mouseCursorAnim -> numFrames;
+		}
+	}
+#endif
+}
+
+void pasteCursor(int x, int y, personaAnimation *c) {
+	if (c -> numFrames) pasteSpriteToBackDrop(x, y,
+		        c -> theSprites -> bank.sprites[c -> frames[0].frameNum],
+		        c -> theSprites -> bank.myPalette);
+}
diff --git a/engines/sludge/cursors.h b/engines/sludge/cursors.h
new file mode 100644
index 0000000..9c803fc
--- /dev/null
+++ b/engines/sludge/cursors.h
@@ -0,0 +1,30 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef SLUDGE_CURSORS_H
+#define SLUDGE_CURSORS_H
+
+void pickAnimCursor(struct personaAnimation *pp);
+void displayCursor();
+void pasteCursor(int x, int y, struct personaAnimation *c);
+
+#endif
diff --git a/engines/sludge/debug.cpp b/engines/sludge/debug.cpp
new file mode 100644
index 0000000..222f411
--- /dev/null
+++ b/engines/sludge/debug.cpp
@@ -0,0 +1,52 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#if 0
+#include <stdarg.h>
+#endif
+
+#include "allfiles.h"
+#include "debug.h"
+#include "language.h"
+
+void debugOut(const char *a, ...) {
+	if (! gameSettings.debugMode) return;
+
+	va_list argptr;
+	va_start(argptr, a);
+
+#if ALLOW_FILE
+#if defined __unix__ && !(defined __APPLE__)
+	vfprintf(stderr, a, argptr);
+#else
+	FILE *fp = fopen("debuggy.txt", "at");
+	if (fp) {
+		vfprintf(fp, a, argptr);
+		fclose(fp);
+	}
+#endif
+#endif
+}
+
+void debugHeader() {
+	debugOut("*** Engine compiled " __DATE__ " at " __TIME__ ".\n");
+}
diff --git a/engines/sludge/debug.h b/engines/sludge/debug.h
new file mode 100644
index 0000000..94b6c34
--- /dev/null
+++ b/engines/sludge/debug.h
@@ -0,0 +1,29 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef SLUDGE_DEDBUG_H
+#define SLUDGE_DEGBUG_H
+
+void debugOut(const char *a, ...);
+void debugHeader();
+
+#endif
diff --git a/engines/sludge/eglport/eglport.cpp b/engines/sludge/eglport/eglport.cpp
new file mode 100755
index 0000000..8414383
--- /dev/null
+++ b/engines/sludge/eglport/eglport.cpp
@@ -0,0 +1,712 @@
+/**
+ *
+ *  EGLPORT.C
+ *  Copyright (C) 2011-2013 Scott R. Smith
+ *
+ *  Permission is hereby granted, free of charge, to any person obtaining a copy
+ *  of this software and associated documentation files (the "Software"), to deal
+ *  in the Software without restriction, including without limitation the rights
+ *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ *  copies of the Software, and to permit persons to whom the Software is
+ *  furnished to do so, subject to the following conditions:
+ *
+ *  The above copyright notice and this permission notice shall be included in
+ *  all copies or substantial portions of the Software.
+ *
+ *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ *  THE SOFTWARE.
+ *
+ */
+
+#include "eglport.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+
+//#define USE_EGL_SDL 1
+//#define USE_GLES1	1
+
+#if defined(USE_EGL_SDL)
+#include "SDL.h"
+#include "SDL_syswm.h"
+SDL_SysWMinfo sysWmInfo;      /** Holds our X Display/Window information */
+#endif /* USE_EGL_SDL */
+
+#if defined(PANDORA) /* Pandora VSync Support */
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <linux/fb.h>
+
+#ifndef FBIO_WAITFORVSYNC
+#define FBIO_WAITFORVSYNC _IOW('F', 0x20, __u32)
+#endif
+int fbdev = -1;
+
+#elif defined(RPI)
+#include "bcm_host.h"
+#endif /* PANDORA */
+
+enum EGL_RENDER_T {
+    RENDER_RAW=0,           /** Sets render mode to raw or framebuffer mode. */
+    RENDER_SDL,             /** Sets render mode to X11/SDL mode. */
+    RENDER_TOTAL
+};
+
+enum EGL_SETTINGS_T {
+    CFG_MODE=0,             /** Render mode for EGL 0=RAW 1=SDL. */
+    CFG_VSYNC,              /** Controls system vsync if available. */
+    CFG_FSAA,               /** Number of samples for full screen AA. 0 is off, 2/4 samples. */
+    CFG_FPS,                /** Calculate and report frame per second. */
+    CFG_RED_SIZE,           /** Number of bits of Red in the color buffer. */
+    CFG_GREEN_SIZE,         /** Number of bits of Green in the color buffer. */
+    CFG_BLUE_SIZE,          /** Number of bits of Blue in the color buffer. */
+    CFG_ALPHA_SIZE,         /** Number of bits of Alpha in the color buffer. */
+    CFG_DEPTH_SIZE,         /** Number of bits of Z in the depth buffer. */
+    CFG_BUFFER_SIZE,        /** The total color component bits in the color buffer. */
+    CFG_STENCIL_SIZE,       /** Number of bits of Stencil in the stencil buffer. */
+    CFG_TOTAL               /** Total number of settings. */
+};
+
+NativeDisplayType   nativeDisplay = 0;      /** Reference to the systems native display */
+NativeWindowType    nativeWindow  = 0;      /** Reference to the systems native window */
+EGLint              eglSettings[CFG_TOTAL]; /** Stores setting values. */
+EGLDisplay          eglDisplay    = NULL;   /** Reference to the EGL display */
+EGLConfig           eglConfig     = NULL;   /** Reference to the EGL config */
+EGLContext          eglContext    = NULL;   /** Reference to the EGL context */
+EGLSurface          eglSurface    = NULL;   /** Reference to the EGL surface */
+
+#define     totalConfigsIn 5                /** Total number of configurations to request */
+EGLint      totalConfigsFound = 0;          /** Total number of configurations matching attributes */
+EGLConfig   eglConfigs[totalConfigsIn];     /** Structure containing references to matching configurations */
+
+uint32_t    fpsCount    = 0;                /** Total number of frames counted */
+uint32_t    fpsTime     = 0;                /** Start time of frame count measurment */
+
+int8_t	eglColorbits 	= 0;
+int8_t	eglDepthbits	= 0;
+int8_t	eglStencilbits	= 0;
+
+
+/** Private API */
+void        OpenCfg                 ( const char* file );
+int8_t      ConfigureEGL            ( EGLConfig config );
+int8_t      FindEGLConfigs          ( void );
+int8_t      CheckEGLErrors          ( const char* file, uint16_t line );
+
+int8_t      GetNativeDisplay        ( void );
+int8_t      GetNativeWindow         ( uint16_t width, uint16_t height );
+void        FreeNativeDisplay       ( void );
+void        FreeNativeWindow        ( void );
+
+void        Platform_Open           ( void );
+void        Platform_Close          ( void );
+void        Platform_VSync          ( void );
+uint32_t    Platform_GetTicks       ( void );
+
+void EGL_Init( void )
+{
+  //nothing...
+  return;
+}
+/** @brief Release all EGL and system resources
+ */
+void EGL_Close( void )
+{
+    /* Release EGL resources */
+    if (eglDisplay != NULL)
+    {
+        peglMakeCurrent( eglDisplay, NULL, NULL, EGL_NO_CONTEXT );
+        if (eglContext != NULL) {
+            peglDestroyContext( eglDisplay, eglContext );
+        }
+        if (eglSurface != NULL) {
+            peglDestroySurface( eglDisplay, eglSurface );
+        }
+        peglTerminate( eglDisplay );
+    }
+
+    eglSurface = NULL;
+    eglContext = NULL;
+    eglDisplay = NULL;
+	
+	eglColorbits = 0;
+	eglDepthbits = 0;
+	eglStencilbits = 0;
+
+    /* Release platform resources */
+    FreeNativeWindow();
+    FreeNativeDisplay();
+    Platform_Close();
+
+    CheckEGLErrors( __FILE__, __LINE__ );
+
+    printf( "EGLport: Closed\n" );
+}
+
+/** @brief Swap the surface buffer onto the display
+ */
+void EGL_SwapBuffers( void )
+{
+    if (eglSettings[CFG_VSYNC] != 0) {
+        Platform_VSync();
+    }
+
+    peglSwapBuffers( eglDisplay, eglSurface );
+
+    if (eglSettings[CFG_FPS] != 0) {
+        fpsCount++;
+
+        if (fpsTime - Platform_GetTicks() >= 1000)
+        {
+            printf( "EGLport: %d fps\n", fpsCount );
+            fpsTime = Platform_GetTicks();
+            fpsCount = 0;
+        }
+    }
+}
+
+/** @brief Obtain the system display and initialize EGL
+ * @param width : desired pixel width of the window (not used by all platforms)
+ * @param height : desired pixel height of the window (not used by all platforms)
+ * @return : 0 if the function passed, else 1
+ */
+int8_t EGL_Open( /*uint16_t width, uint16_t height*/ )
+{
+    EGLint eglMajorVer, eglMinorVer;
+    EGLBoolean result;
+    uint32_t configIndex = 0;
+    const char* output;
+
+    static const EGLint contextAttribs[] =
+    {
+#if defined(USE_GLES2)
+          EGL_CONTEXT_CLIENT_VERSION,     2,
+#endif
+          EGL_NONE
+    };
+
+#if defined(DEBUG)
+    printf( "EGLport Warning: DEBUG is enabled which may effect performance\n" );
+#endif
+
+    /* Check that system is not open */
+    if (eglDisplay != NULL || eglContext != NULL || eglSurface != NULL)
+    {
+        printf( "EGLport ERROR: EGL system is already open!\n" );
+        return 1;
+    }
+
+    /* Check for the cfg file to alternative settings */
+    OpenCfg( "eglport.cfg" );
+
+    /* Setup any platform specific bits */
+    Platform_Open();
+
+    printf( "EGLport: Opening EGL display\n" );
+    if (GetNativeDisplay() != 0)
+    {
+        printf( "EGLport ERROR: Unable to obtain native display!\n" );
+        return 1;
+    }
+
+    eglDisplay = peglGetDisplay( nativeDisplay );
+    if (eglDisplay == EGL_NO_DISPLAY)
+    {
+        CheckEGLErrors( __FILE__, __LINE__ );
+        printf( "EGLport ERROR: Unable to create EGL display.\n" );
+        return 1;
+    }
+
+    printf( "EGLport: Initializing\n" );
+    result = peglInitialize( eglDisplay, &eglMajorVer, &eglMinorVer );
+    if (result != EGL_TRUE )
+    {
+        CheckEGLErrors( __FILE__, __LINE__ );
+        printf( "EGLport ERROR: Unable to initialize EGL display.\n" );
+        return 1;
+    }
+
+    /* Get EGL Library Information */
+    printf( "EGL Implementation Version: Major %d Minor %d\n", eglMajorVer, eglMinorVer );
+    output = peglQueryString( eglDisplay, EGL_VENDOR );
+    printf( "EGL_VENDOR: %s\n", output );
+    output = peglQueryString( eglDisplay, EGL_VERSION );
+    printf( "EGL_VERSION: %s\n", output );
+    output = peglQueryString( eglDisplay, EGL_EXTENSIONS );
+    printf( "EGL_EXTENSIONS: %s\n", output );
+
+    if (FindEGLConfigs() != 0)
+    {
+        printf( "EGLport ERROR: Unable to configure EGL. See previous error.\n" );
+        return 1;
+    }
+
+    printf( "EGLport: Using Config %d\n", configIndex );
+#if defined(EGL_VERSION_1_2)
+    /* Bind GLES and create the context */
+    printf( "EGLport: Binding API\n" );
+    result = peglBindAPI( EGL_OPENGL_ES_API );
+    if ( result == EGL_FALSE )
+    {
+        CheckEGLErrors( __FILE__, __LINE__ );
+        printf( "EGLport ERROR: Could not bind EGL API.\n" );
+        return 1;
+    }
+#endif /* EGL_VERSION_1_2 */
+
+    printf( "EGLport: Creating Context\n" );
+    eglContext = peglCreateContext( eglDisplay, eglConfigs[configIndex], NULL, contextAttribs );
+    if (eglContext == EGL_NO_CONTEXT)
+    {
+        CheckEGLErrors( __FILE__, __LINE__ );
+        printf( "EGLport ERROR: Unable to create GLES context!\n");
+        return 1;
+    }
+
+    printf( "EGLport: Creating window surface\n" );
+    if (GetNativeWindow( 800, 480/*width, height*/ ) != 0)
+    {
+        printf( "EGLport ERROR: Unable to obtain native window!\n" );
+        return 1;
+    }
+
+    eglSurface = peglCreateWindowSurface( eglDisplay, eglConfigs[configIndex], nativeWindow, 0 );
+    if (eglSurface == EGL_NO_SURFACE)
+    {
+        CheckEGLErrors( __FILE__, __LINE__ );
+        printf( "EGLport ERROR: Unable to create EGL surface!\n" );
+        return 1;
+    }
+
+    printf( "EGLport: Making Current\n" );
+    result = peglMakeCurrent( eglDisplay,  eglSurface,  eglSurface, eglContext );
+    if (result != EGL_TRUE)
+    {
+        CheckEGLErrors( __FILE__, __LINE__ );
+        printf( "EGLport ERROR: Unable to make GLES context current\n" );
+        return 1;
+    }
+
+	{
+	  EGLint color, depth, stencil;
+	  eglGetConfigAttrib(eglDisplay, eglConfigs[configIndex], EGL_BUFFER_SIZE, &color);
+	  eglGetConfigAttrib(eglDisplay, eglConfigs[configIndex], EGL_DEPTH_SIZE, &depth);
+	  eglGetConfigAttrib(eglDisplay, eglConfigs[configIndex], EGL_STENCIL_SIZE, &stencil);
+	  eglColorbits = (color==16)?5:8; //quick hack
+	  eglDepthbits = depth;
+	  eglStencilbits = stencil;
+	}
+
+    printf( "EGLport: Setting swap interval\n" );
+    peglSwapInterval( eglDisplay, (eglSettings[CFG_VSYNC] > 0) ? 1 : 0 );
+
+    printf( "EGLport: Complete\n" );
+
+    CheckEGLErrors( __FILE__, __LINE__ );
+	
+    return 0;
+}
+
+/** @brief Read settings that configure how to use EGL
+ * @param file : name of the config file
+ */
+void OpenCfg ( const char* file )
+{
+    #define MAX_STRING 20
+    #define MAX_SIZE 100
+    uint8_t i;
+    FILE* fp = NULL;
+    char* location = NULL;
+    char eglStrings[CFG_TOTAL][MAX_STRING];
+    char buffer[MAX_SIZE];
+
+    strncpy( eglStrings[CFG_MODE], "egl_mode=", MAX_STRING );
+    strncpy( eglStrings[CFG_VSYNC], "use_vsync=", MAX_STRING );
+    strncpy( eglStrings[CFG_FSAA], "use_fsaa=", MAX_STRING );
+    strncpy( eglStrings[CFG_RED_SIZE], "size_red=", MAX_STRING );
+    strncpy( eglStrings[CFG_GREEN_SIZE], "size_green=", MAX_STRING );
+    strncpy( eglStrings[CFG_BLUE_SIZE], "size_blue=", MAX_STRING );
+    strncpy( eglStrings[CFG_ALPHA_SIZE], "size_alpha=", MAX_STRING );
+    strncpy( eglStrings[CFG_DEPTH_SIZE], "size_depth=", MAX_STRING );
+    strncpy( eglStrings[CFG_BUFFER_SIZE], "size_buffer=", MAX_STRING );
+    strncpy( eglStrings[CFG_STENCIL_SIZE], "size_stencil=", MAX_STRING );
+
+    /* Set defaults */
+#if defined(USE_EGL_SDL) && !defined(PANDORA)
+    eglSettings[CFG_MODE]           = RENDER_SDL;
+#else
+    eglSettings[CFG_MODE]           = RENDER_RAW;
+#endif
+    eglSettings[CFG_VSYNC]          = 0;
+    eglSettings[CFG_FSAA]           = 0;
+    eglSettings[CFG_FPS]            = 0;
+    eglSettings[CFG_RED_SIZE]       = 5;
+    eglSettings[CFG_GREEN_SIZE]     = 6;
+    eglSettings[CFG_BLUE_SIZE]      = 5;
+    eglSettings[CFG_ALPHA_SIZE]     = 0;
+    eglSettings[CFG_DEPTH_SIZE]     = 16;
+    eglSettings[CFG_BUFFER_SIZE]    = 16;
+    eglSettings[CFG_STENCIL_SIZE]   = 0;
+
+    /* Parse INI file */
+    fp = fopen( file, "r");
+    if (fp != NULL)
+    {
+        while (fgets( buffer, MAX_SIZE, fp ) != NULL)
+        {
+            for (i=0; i<CFG_TOTAL; i++)
+            {
+                location = strstr( buffer, eglStrings[i] );
+                if (location != NULL)
+                {
+                    eglSettings[i] = atol( location+strlen( eglStrings[i] ) );
+                    printf( "EGLport: %s set to %d.\n", eglStrings[i], eglSettings[i] );
+                    break;
+                }
+            }
+        }
+
+        fclose( fp );
+    }
+    else
+    {
+        printf( "EGL NOTICE: Unable to read ini settings from file '%s'. Using defaults\n", file );
+    }
+}
+
+/** @brief Find a EGL configuration tht matches the defined attributes
+ * @return : 0 if the function passed, else 1
+ */
+int8_t FindEGLConfigs( void )
+{
+    EGLBoolean result;
+    int attrib = 0;
+    EGLint ConfigAttribs[23];
+
+    ConfigAttribs[attrib++] = EGL_RED_SIZE;                         /* 1 */
+    ConfigAttribs[attrib++] = eglSettings[CFG_RED_SIZE];            /* 2 */
+    ConfigAttribs[attrib++] = EGL_GREEN_SIZE;                       /* 3 */
+    ConfigAttribs[attrib++] = eglSettings[CFG_GREEN_SIZE];          /* 4 */
+    ConfigAttribs[attrib++] = EGL_BLUE_SIZE;                        /* 5 */
+    ConfigAttribs[attrib++] = eglSettings[CFG_BLUE_SIZE];           /* 6 */
+    ConfigAttribs[attrib++] = EGL_ALPHA_SIZE;                       /* 7 */
+    ConfigAttribs[attrib++] = eglSettings[CFG_ALPHA_SIZE];          /* 8 */
+    ConfigAttribs[attrib++] = EGL_DEPTH_SIZE;                       /* 9 */
+    ConfigAttribs[attrib++] = eglSettings[CFG_DEPTH_SIZE];          /* 10 */
+    ConfigAttribs[attrib++] = EGL_BUFFER_SIZE;                      /* 11 */
+    ConfigAttribs[attrib++] = eglSettings[CFG_BUFFER_SIZE];         /* 12 */
+    ConfigAttribs[attrib++] = EGL_STENCIL_SIZE;                     /* 13 */
+    ConfigAttribs[attrib++] = eglSettings[CFG_STENCIL_SIZE];        /* 14 */
+    ConfigAttribs[attrib++] = EGL_SURFACE_TYPE;                     /* 15 */
+    ConfigAttribs[attrib++] = EGL_WINDOW_BIT;                       /* 16 */
+#if defined(EGL_VERSION_1_2)
+    ConfigAttribs[attrib++] = EGL_RENDERABLE_TYPE;                  /* 17 */
+#if defined(USE_GLES1)
+    ConfigAttribs[attrib++] = EGL_OPENGL_ES_BIT;
+#elif defined(USE_GLES2)
+    ConfigAttribs[attrib++] = EGL_OPENGL_ES2_BIT;                   /* 18 */
+#endif /* USE_GLES1 */
+#endif /* EGL_VERSION_1_2 */
+    ConfigAttribs[attrib++] = EGL_SAMPLE_BUFFERS;                   /* 19 */
+    ConfigAttribs[attrib++] = (eglSettings[CFG_FSAA] > 0) ? 1 : 0;  /* 20 */
+    ConfigAttribs[attrib++] = EGL_SAMPLES;                          /* 21 */
+    ConfigAttribs[attrib++] = eglSettings[CFG_FSAA];                /* 22 */
+    ConfigAttribs[attrib++] = EGL_NONE;                             /* 23 */
+
+    result = peglChooseConfig( eglDisplay, ConfigAttribs, eglConfigs, totalConfigsIn, &totalConfigsFound );
+    if (result != EGL_TRUE || totalConfigsFound == 0)
+    {
+        CheckEGLErrors( __FILE__, __LINE__ );
+        printf( "EGLport ERROR: Unable to query for available configs, found %d.\n", totalConfigsFound );
+        return 1;
+    }
+    printf( "EGLport: Found %d available configs\n", totalConfigsFound );
+
+    return 0;
+}
+
+/** @brief Error checking function
+ * @param file : string reference that contains the source file that the check is occuring in
+ * @param line : numeric reference that contains the line number that the check is occuring in
+ * @return : 0 if the function passed, else 1
+ */
+int8_t CheckEGLErrors( const char* file, uint16_t line )
+{
+    EGLenum error;
+    const char* errortext;
+    const char* description;
+
+    error = eglGetError();
+
+    if (error != EGL_SUCCESS && error != 0)
+    {
+        switch (error)
+        {
+            case EGL_NOT_INITIALIZED:
+                errortext   = "EGL_NOT_INITIALIZED.";
+                description = "EGL is not or could not be initialized, for the specified display.";
+                break;
+            case EGL_BAD_ACCESS:
+                errortext   = "EGL_BAD_ACCESS EGL";
+                description = "cannot access a requested resource (for example, a context is bound in another thread).";
+                break;
+            case EGL_BAD_ALLOC:
+                errortext   = "EGL_BAD_ALLOC EGL";
+                description = "failed to allocate resources for the requested operation.";
+                break;
+            case EGL_BAD_ATTRIBUTE:
+                errortext   = "EGL_BAD_ATTRIBUTE";
+                description = "An unrecognized attribute or attribute value was passed in anattribute list.";
+                break;
+            case EGL_BAD_CONFIG:
+                errortext   = "EGL_BAD_CONFIG";
+                description = "An EGLConfig argument does not name a valid EGLConfig.";
+                break;
+            case EGL_BAD_CONTEXT:
+                errortext   = "EGL_BAD_CONTEXT";
+                description = "An EGLContext argument does not name a valid EGLContext.";
+                break;
+            case EGL_BAD_CURRENT_SURFACE:
+                errortext   = "EGL_BAD_CURRENT_SURFACE";
+                description = "The current surface of the calling thread is a window, pbuffer,or pixmap that is no longer valid.";
+                break;
+            case EGL_BAD_DISPLAY:
+                errortext   = "EGL_BAD_DISPLAY";
+                description = "An EGLDisplay argument does not name a valid EGLDisplay.";
+                break;
+            case EGL_BAD_MATCH:
+                errortext   = "EGL_BAD_MATCH";
+                description = "Arguments are inconsistent; for example, an otherwise valid context requires buffers (e.g. depth or stencil) not allocated by an otherwise valid surface.";
+                break;
+            case EGL_BAD_NATIVE_PIXMAP:
+                errortext   = "EGL_BAD_NATIVE_PIXMAP";
+                description = "An EGLNativePixmapType argument does not refer to a validnative pixmap.";
+                break;
+            case EGL_BAD_NATIVE_WINDOW:
+                errortext   = "EGL_BAD_NATIVE_WINDOW";
+                description = "An EGLNativeWindowType argument does not refer to a validnative window.";
+                break;
+            case EGL_BAD_PARAMETER:
+                errortext   = "EGL_BAD_PARAMETER";
+                description = "One or more argument values are invalid.";
+                break;
+            case EGL_BAD_SURFACE:
+                errortext   = "EGL_BAD_SURFACE";
+                description = "An EGLSurface argument does not name a valid surface (window,pbuffer, or pixmap) configured for rendering";
+                break;
+            case EGL_CONTEXT_LOST:
+                errortext   = "EGL_CONTEXT_LOST";
+                description = "A power management event has occurred. The application mustdestroy all contexts and reinitialise client API state and objects to continue rendering.";
+                break;
+            default:
+                errortext   = "Unknown EGL Error";
+                description = "";
+                break;
+        }
+
+        printf( "EGLport ERROR: EGL Error detected in file %s at line %d: %s (0x%X)\n  Description: %s\n", file, line, errortext, error, description );
+        return 1;
+    }
+
+    return 0;
+}
+
+/** @brief Obtain a reference to the system's native display
+ * @param window : pointer to save the display reference
+ * @return : 0 if the function passed, else 1
+ */
+int8_t GetNativeDisplay( void )
+{
+    if (eglSettings[CFG_MODE] == RENDER_RAW)        /* RAW FB mode */
+    {
+        printf( "EGLport: Using EGL_DEFAULT_DISPLAY\n" );
+        nativeDisplay = EGL_DEFAULT_DISPLAY;
+    }
+    else if (eglSettings[CFG_MODE] == RENDER_SDL)   /* SDL/X11 mode */
+    {
+#if defined(USE_EGL_SDL)
+        printf( "EGLport: Opening SDL/X11 display\n" );
+        SDL_VERSION(&sysWmInfo.version);
+        SDL_GetWMInfo(&sysWmInfo);
+        nativeDisplay = (EGLNativeDisplayType)sysWmInfo.info.x11.display;
+
+        if (nativeDisplay == 0)
+        {
+            printf( "EGLport ERROR: unable to get display!\n" );
+            return 1;
+        }
+#else
+        printf( "EGLport ERROR: SDL mode was not enabled in this compile!\n" );
+#endif
+    }
+
+    return 0;
+}
+
+/** @brief Obtain a reference to the system's native window
+ * @param width : desired pixel width of the window (not used by all platforms)
+ * @param height : desired pixel height of the window (not used by all platforms)
+ * @return : 0 if the function passed, else 1
+ */
+int8_t GetNativeWindow( uint16_t width, uint16_t height )
+{
+    nativeWindow = 0;
+
+#if defined(WIZ) || defined(CAANOO)
+
+    nativeWindow = (NativeWindowType)malloc(16*1024);
+
+    if(nativeWindow == NULL) {
+        printf( "EGLport ERROR: Memory for window Failed\n" );
+        return 1;
+    }
+
+#elif defined(RPI)
+
+    EGLBoolean result;
+    uint32_t screen_width, screen_height;
+    static EGL_DISPMANX_WINDOW_T nativewindow;
+    DISPMANX_ELEMENT_HANDLE_T dispman_element;
+    DISPMANX_DISPLAY_HANDLE_T dispman_display;
+    DISPMANX_UPDATE_HANDLE_T dispman_update;
+    VC_RECT_T dst_rect;
+    VC_RECT_T src_rect;
+
+    /* create an EGL window surface */
+    result = graphics_get_display_size(0 /* LCD */, &screen_width, &screen_height);
+    if(result < 0) {
+        printf( "EGLport ERROR: RPi graphicget_display_size failed\n" );
+        return 1;
+    }
+
+    dst_rect.x = 0;
+    dst_rect.y = 0;
+    dst_rect.width = screen_width;
+    dst_rect.height = screen_height;
+
+    src_rect.x = 0;
+    src_rect.y = 0;
+    src_rect.width = width << 16;
+    src_rect.height = height << 16;
+
+    dispman_display = vc_dispmanx_display_open( 0 /* LCD */);
+    dispman_update  = vc_dispmanx_update_start( 0 );
+    dispman_element = vc_dispmanx_element_add ( dispman_update, dispman_display,
+      0 /*layer*/, &dst_rect, 0 /*src*/,
+      &src_rect, DISPMANX_PROTECTION_NONE,  (VC_DISPMANX_ALPHA_T*)0 /*alpha*/,  (DISPMANX_CLAMP_T*)0 /*clamp*/,  (DISPMANX_TRANSFORM_T)0 /*transform*/);
+
+    nativewindow.element = dispman_element;
+    nativewindow.width = screen_width;
+    nativewindow.height = screen_height;
+    vc_dispmanx_update_submit_sync( dispman_update );
+
+    nativeWindow = (NativeWindowType)&nativewindow;
+
+#else /* default */
+
+    if (eglSettings[CFG_MODE] == RENDER_RAW)        /* RAW FB mode */
+    {
+        nativeWindow = 0;
+    }
+    else if(eglSettings[CFG_MODE] == RENDER_SDL)    /* SDL/X11 mode */
+    {
+#if defined(USE_EGL_SDL)
+        /* SDL_GetWMInfo is populated when display was opened */
+        nativeWindow = (NativeWindowType)sysWmInfo.info.x11.window;
+
+        if (nativeWindow == 0)
+        {
+            printf( "EGLport ERROR: unable to get window!\n" );
+            return 1;
+        }
+#else
+        printf( "EGLport ERROR: SDL mode was not enabled in this compile!\n" );
+#endif
+    }
+    else
+    {
+        printf( "EGLport ERROR: Unknown EGL render mode %d!\n", eglSettings[CFG_MODE] );
+        return 1;
+    }
+
+#endif /* WIZ / CAANOO */
+
+    return 0;
+}
+
+/** @brief Release the system's native display
+ */
+void FreeNativeDisplay( void )
+{
+}
+
+/** @brief Release the system's native window
+ */
+void FreeNativeWindow( void )
+{
+#if defined(WIZ) || defined(CAANOO)
+    if (nativeWindow != NULL) {
+        free( nativeWindow );
+    }
+    nativeWindow = NULL;
+#endif /* WIZ / CAANOO */
+}
+
+/** @brief Open any system specific resources
+ */
+void Platform_Open( void )
+{
+#if defined(PANDORA)
+    /* Pandora VSync */
+    fbdev = open( "/dev/fb0", O_RDONLY /* O_RDWR */ );
+    if ( fbdev < 0 ) {
+        printf( "EGLport ERROR: Couldn't open /dev/fb0 for Pandora Vsync\n" );
+    }
+#elif defined(RPI)
+    bcm_host_init();
+#endif /* PANDORA */
+}
+
+/** @brief Release any system specific resources
+ */
+void Platform_Close( void )
+{
+#if defined(PANDORA)
+    /* Pandora VSync */
+    close( fbdev );
+    fbdev = -1;
+#endif /* PANDORA */
+}
+
+/** @brief Check the systems vsync state
+ */
+void Platform_VSync( void )
+{
+#if defined(PANDORA)
+    /* Pandora VSync */
+    if (fbdev >= 0) {
+        int arg = 0;
+        ioctl( fbdev, FBIO_WAITFORVSYNC, &arg );
+    }
+#endif /* PANDORA */
+}
+
+/** @brief Get the system tick time (ms)
+ */
+uint32_t Platform_GetTicks( void )
+{
+    uint32_t ticks = 0;
+#if defined(USE_EGL_SDL)
+    ticks = SDL_GetTicks();
+#else
+    printf( "EGLport ERROR: SDL mode was not enabled in this compile!\n" );
+#endif
+    return ticks;
+}
+
diff --git a/engines/sludge/eglport/eglport.h b/engines/sludge/eglport/eglport.h
new file mode 100644
index 0000000..20fb979
--- /dev/null
+++ b/engines/sludge/eglport/eglport.h
@@ -0,0 +1,109 @@
+/**
+ *
+ *  EGLPORT.H
+ *  Copyright (C) 2011-2013 Scott R. Smith
+ *
+ *  Permission is hereby granted, free of charge, to any person obtaining a copy
+ *  of this software and associated documentation files (the "Software"), to deal
+ *  in the Software without restriction, including without limitation the rights
+ *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ *  copies of the Software, and to permit persons to whom the Software is
+ *  furnished to do so, subject to the following conditions:
+ *
+ *  The above copyright notice and this permission notice shall be included in
+ *  all copies or substantial portions of the Software.
+ *
+ *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ *  THE SOFTWARE.
+ *
+ */
+
+#ifndef EGLPORT_H
+#define EGLPORT_H
+
+#include <stdint.h>
+#include "EGL/egl.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** Defines (in every case choose only one) */
+/**     Common: */
+/**         DEBUG : enable additional error monitoring per EGL function call */
+/**     Native display and window system for use with EGL */
+/**         USE_EGL_SDL : used for access to a SDL X11 window */
+/**     Platform: settings that are specific to that device */
+/**         PANDORA (USE_GLES1 or USE_GLES2) */
+/**         WIZ     (USE_GLES1) */
+/**         CAANOO  (USE_GLES1) */
+/**         RPI     (USE_GLES1 or USE_GLES2) */
+/**     GLES Version */
+/**         USE_GLES1 : EGL for use with OpenGL-ES 1.X contexts */
+/**         USE_GLES2 : EGL for use with OpenGL-ES 2.0 contexts */
+
+/** Public API */
+void    EGL_Init                    ( void );
+void    EGL_Close                   ( void );
+int8_t  EGL_Open                    ( /*uint16_t width, uint16_t height*/ );
+void    EGL_SwapBuffers             ( void );
+
+extern int8_t	eglColorbits;
+extern int8_t	eglDepthbits;
+extern int8_t	eglStencilbits;
+
+/** Simple Examples  */
+/**     Raw mode:
+            EGL_Open( window_width, window_height );
+            do while(!quit) {
+                ... run app
+                EGL_SwapBuffers();
+            }
+            EGL_Close();
+*/
+/**     X11/SDL mode:
+            SDL_Init( SDL_INIT_VIDEO );
+            SDL_Surface* screen = SDL_SetVideoMode(640, 480, 16, SDL_SWSURFACE|SDL_FULLSCREEN);
+            EGL_Open( window_width, window_height );
+            do while(!quit) {
+                ... run app
+                EGL_SwapBuffers();
+            }
+            EGL_Close();
+            SDL_Quit();
+*/
+
+#if defined(DEBUG)
+#define GET_EGLERROR(FUNCTION)               \
+    FUNCTION;                                \
+    {                                        \
+        CheckEGLErrors(__FILE__, __LINE__);  \
+    }
+#else
+#define GET_EGLERROR(FUNCTION) FUNCTION;
+#endif
+
+#define peglQueryString(A,B)                    GET_EGLERROR(eglQueryString(A,B))
+#define peglDestroyContext(A,B)                 GET_EGLERROR(eglDestroyContext(A,B))
+#define peglDestroySurface(A,B)                 GET_EGLERROR(eglDestroySurface(A,B))
+#define peglTerminate(A)                        GET_EGLERROR(eglTerminate(A))
+#define peglSwapBuffers(A,B)                    GET_EGLERROR(eglSwapBuffers(A,B))
+#define peglGetDisplay(A)                       GET_EGLERROR(eglGetDisplay(A))
+#define peglBindAPI(A)                          GET_EGLERROR(eglBindAPI(A))
+#define peglCreateContext(A,B,C,D)              GET_EGLERROR(eglCreateContext(A,B,C,D))
+#define peglCreateWindowSurface(A,B,C,D)        GET_EGLERROR(eglCreateWindowSurface(A,B,C,D))
+#define peglInitialize(A,B,C)                   GET_EGLERROR(eglInitialize(A,B,C))
+#define peglMakeCurrent(A,B,C,D)                GET_EGLERROR(eglMakeCurrent(A,B,C,D))
+#define peglChooseConfig(A,B,C,D,E)             GET_EGLERROR(eglChooseConfig(A,B,C,D,E))
+#define peglSwapInterval(A,B)                   GET_EGLERROR(eglSwapInterval(A,B))
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EGLPORT_H */
diff --git a/engines/sludge/errors.h b/engines/sludge/errors.h
new file mode 100644
index 0000000..0c4716c
--- /dev/null
+++ b/engines/sludge/errors.h
@@ -0,0 +1,72 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef SLUDGE_ERRRORS_H
+#define SLUDGE_ERRRORS_H
+
+#define _NO_MEMORY_GENERAL_         "\n\nTry closing down any programs you don't really need running (or freeing up a bit of disk space, which will give you more virtual memory - that should help too)."
+
+//---------------------------------------
+// Fatal errors
+//---------------------------------------
+
+#define ERROR_VERSION_TOO_LOW_1     "This SLUDGE file requires a more recent version of the SLUDGE engine"
+#define ERROR_VERSION_TOO_LOW_2     "(it was created for v%i.%i).\n\nVisit http://opensludge.github.io/ to download the most recent version."
+#define ERROR_VERSION_TOO_HIGH_1    "This SLUDGE file was created for an older version of the SLUDGE engine"
+#define ERROR_VERSION_TOO_HIGH_2    "(v%i.%i).\n\nPlease contact the author of this game to obtain a version compatible with your SLUDGE engine (v" TEXT_VERSION ")."
+#define ERROR_BAD_HEADER            "Bad header information... this isn't a valid SLUDGE game"
+#define ERROR_HACKER                "What have you been up to? Think we're a hacker, do we? Nice try."
+
+#define ERROR_GAME_LOAD_NO          "This isn't a SLUDGE saved game!\n"
+#define ERROR_GAME_LOAD_WRONG       "Can't load this saved game! It was either created by...\n\n  (a)  a different SLUDGE game to the one which you're playing, or...\n  (b)  a different (newer or older) version of the same game.\n\nFilename"
+#define ERROR_GAME_SAVE_FROZEN      "Can't save games while I'm frozen"
+#define ERROR_GAME_LOAD_CORRUPT     "This saved game appears to be corrupted"
+
+#define ERROR_NON_EMPTY_STACK       "Returning from function with non-empty stack"
+#define ERROR_UNKNOWN_MCODE         "Unknown SLUDGE machine code"
+#define ERROR_CALL_NONFUNCTION      "Call of non-function"
+#define ERROR_INCDEC_UNKNOWN        "Tried to increment/decrement index of an undefined variable"
+#define ERROR_INDEX_EMPTY           "Tried to index an empty stack"
+#define ERROR_INDEX_NONSTACK        "Tried to index a non-stack variable"
+#define ERROR_NOSTACK               "Corrupt file - no stack"
+#define ERROR_UNKNOWN_CODE          "Unimplemented internal SLUDGE command code."
+#define ERROR_OUT_OF_MEMORY         "Out of memory!" _NO_MEMORY_GENERAL_
+
+#define ERROR_MUSIC_MEMORY_LOW      "Your computer doesn't have enough memory available to load a music resource that needs playing." _NO_MEMORY_GENERAL_
+#define ERROR_SOUND_MEMORY_LOW      "Your computer doesn't have enough memory available to load a sound resource that needs playing." _NO_MEMORY_GENERAL_
+#define ERROR_MUSIC_UNKNOWN         "I can't understand a piece of music which I've been told to play!\n\n" \
+	"Maybe it's stored in a format that SLUDGE doesn't know about... " \
+	"make sure you've got a recent version of the SLUDGE engine from http://opensludge.github.io/. " \
+	"Failing that, maybe the resource in question isn't a valid music format at all... in which case, contact the game's author and tell them what's happened."
+#define ERROR_SOUND_UNKNOWN         "I can't understand a sample which I've been told to play!\nMake sure you've got the latest SLUDGE engine from http://opensludge.github.io/. Failing that, maybe the resource in question isn't a valid sound at all... in which case, contact the game's author and tell them what's happened."
+#define ERROR_MUSIC_ODDNESS         "I can't load a music resource I've been told to play. Sorry."
+#define ERROR_SOUND_ODDNESS         "I can't load a sound resource I've been told to play. Sorry."
+#define ERROR_MOVIE_ODDNESS         "I can't load a music resource I've been told to play. Sorry."
+
+//---------------------------------------
+// Startup warnings
+//---------------------------------------
+
+#define WARNING_BASS_WRONG_VERSION  "Incompatible version of BASS.DLL found!"
+#define WARNING_BASS_FAIL           "Can't initialise sound engine."
+
+#endif
diff --git a/engines/sludge/fileset.cpp b/engines/sludge/fileset.cpp
new file mode 100644
index 0000000..8d5eb52
--- /dev/null
+++ b/engines/sludge/fileset.cpp
@@ -0,0 +1,237 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#if 0
+#include <errno.h>
+#include <stdint.h>
+#include <string.h>
+// For unicode conversion
+#include <iconv.h>
+#endif
+
+#include "debug.h"
+#include "stringy.h"
+
+#include "allfiles.h"
+#include "moreio.h"
+#include "newfatal.h"
+#include "CommonCode/version.h"
+
+
+bool sliceBusy = true;
+#if ALLOW_FILE
+FILE *bigDataFile = NULL;
+#endif
+uint32_t startOfDataIndex, startOfTextIndex,
+         startOfSubIndex, startOfObjectIndex;
+
+bool openSubSlice(int num) {
+//	FILE * dbug = fopen ("debuggy.txt", "at");
+
+//	fprintf (dbug, "\nTrying to open sub %i\n", num);
+
+	if (sliceBusy) {
+		fatal("Can't read from data file", "I'm already reading something");
+		return false;
+	}
+//	fprintf (dbug, "Going to position %li\n", startOfSubIndex + (num << 2));
+	fseek(bigDataFile, startOfSubIndex + (num << 2), 0);
+	fseek(bigDataFile, get4bytes(bigDataFile), 0);
+//	fprintf (dbug, "Told to skip forward to %li\n", ftell (bigDataFile));
+//	fclose (dbug);
+
+	return sliceBusy = true;
+}
+
+bool openObjectSlice(int num) {
+//	FILE * dbug = fopen ("debuggy.txt", "at");
+
+//	fprintf (dbug, "\nTrying to open object %i\n", num);
+
+	if (sliceBusy) {
+		fatal("Can't read from data file", "I'm already reading something");
+		return false;
+	}
+
+//	fprintf (dbug, "Going to position %li\n", startOfObjectIndex + (num << 2));
+	fseek(bigDataFile, startOfObjectIndex + (num << 2), 0);
+	fseek(bigDataFile, get4bytes(bigDataFile), 0);
+//	fprintf (dbug, "Told to skip forward to %li\n", ftell (bigDataFile));
+//	fclose (dbug);
+	return sliceBusy = true;
+}
+
+unsigned int openFileFromNum(int num) {
+//	FILE * dbug = fopen ("debuggy.txt", "at");
+
+	if (sliceBusy) {
+		fatal("Can't read from data file", "I'm already reading something");
+		return 0;
+	}
+
+//	fprintf (dbug, "\nTrying to open file %i\n", num);
+//	fprintf (dbug, "Jumping to %li (for index) \n", startOfDataIndex + (num << 2));
+	fseek(bigDataFile, startOfDataIndex + (num << 2), 0);
+	fseek(bigDataFile, get4bytes(bigDataFile), 1);
+//	fprintf (dbug, "Jumping to %li (for data) \n", ftell (bigDataFile));
+	sliceBusy = true;
+//	fclose (dbug);
+
+	return get4bytes(bigDataFile);
+}
+
+
+// Converts a string from Windows CP-1252 to UTF-8.
+// This is needed for old games.
+char *convertString(char *s) {
+	static char *buf = NULL;
+
+	if (! buf) {
+		buf = new char [65536];
+		if (! checkNew(buf)) return NULL;
+	}
+
+	char **tmp1 = (char **) &s;
+	char **tmp2 = (char **) &buf;
+	char *sOrig = s;
+	char *bufOrig = buf;
+#if defined __unix__ && !(defined __APPLE__)
+	iconv_t convert = iconv_open("UTF-8", "ISO8859-2");
+#else
+	iconv_t convert = iconv_open("UTF-8", "CP1250");
+#endif
+
+	if (convert == (iconv_t) - 1) {
+		switch (errno) {
+		case EINVAL:
+			fprintf(stderr, "Error: Encoding not supported by iconv.\n");
+			break;
+		default:
+			fprintf(stderr, "Error: Could not open iconv conversion descriptor.\n");
+		}
+	}
+
+	size_t len1 = strlen(s) + 1;
+	size_t len2 = 65535;
+	size_t iconv_value =
+#ifdef _WIN32
+	    iconv(convert, (const char **) tmp1, &len1, tmp2, &len2);
+#else
+	    iconv(convert, (char **) tmp1, &len1, tmp2, &len2);
+#endif
+
+	if (iconv_value == (size_t) - 1) {
+		switch (errno) {
+		/* See "man 3 iconv" for an explanation. */
+		case EILSEQ:
+			fprintf(stderr, "Invalid multibyte sequence.\n");
+			break;
+		case EINVAL:
+			fprintf(stderr, "Incomplete multibyte sequence.\n");
+			break;
+		case E2BIG:
+			fprintf(stderr, "No more room.\n");
+			break;
+		default:
+			fprintf(stderr, "Error: %s.\n", strerror(errno));
+		}
+		fatal("Conversion to Unicode failed. This can be fixed by recompiling the game in a current version of the SLUDGE Development Kit, but this error should never happen. Congratulations, you've found a bug in the SLUDGE engine! Please let us know about it.");
+	}
+	iconv_close(convert);
+
+
+	delete [] sOrig;
+	return copyString(buf = bufOrig);
+}
+
+char *getNumberedString(int value) {
+
+	if (sliceBusy) {
+		fatal("Can't read from data file", "I'm already reading something");
+		return NULL;
+	}
+
+	fseek(bigDataFile, (value << 2) + startOfTextIndex, 0);
+	value = get4bytes(bigDataFile);
+	fseek(bigDataFile, value, 0);
+
+	char *s = readString(bigDataFile);
+
+	if (gameVersion < VERSION(2, 2)) {
+		// This is an older game - We need to convert the string to UTF-8
+		s = convertString(s);
+	}
+
+	return s;
+}
+
+bool startAccess() {
+	int wasBusy = sliceBusy;
+	sliceBusy = true;
+	return wasBusy;
+}
+void finishAccess() {
+	sliceBusy = false;
+}
+
+int32_t startIndex;
+
+void setFileIndices(FILE *fp, int numLanguages, unsigned int skipBefore) {
+	if (fp) {
+		// Keep hold of the file handle, and let things get at it
+		bigDataFile = fp;
+		startIndex = ftell(fp);
+	} else {
+		// No file pointer - this means that we reuse the bigDataFile
+		fp = bigDataFile;
+		fseek(fp, startIndex, 0);
+	}
+	sliceBusy = false;
+
+	if (skipBefore > numLanguages) {
+		warning("Not a valid language ID! Using default instead.");
+		skipBefore = 0;
+	}
+
+	// STRINGS
+	int skipAfter = numLanguages - skipBefore;
+	while (skipBefore) {
+		fseek(fp, get4bytes(fp), 0);
+		skipBefore --;
+	}
+	startOfTextIndex = ftell(fp) + 4;
+
+	fseek(fp, get4bytes(fp), 0);
+
+	while (skipAfter) {
+		fseek(fp, get4bytes(fp), 0);
+		skipAfter --;
+	}
+
+	startOfSubIndex = ftell(fp) + 4;
+	fseek(fp, get4bytes(fp), 1);
+
+	startOfObjectIndex = ftell(fp) + 4;
+	fseek(fp, get4bytes(fp), 1);
+
+	// Remember that the data section starts here
+	startOfDataIndex = ftell(fp);
+}
diff --git a/engines/sludge/fileset.h b/engines/sludge/fileset.h
new file mode 100644
index 0000000..39a6691
--- /dev/null
+++ b/engines/sludge/fileset.h
@@ -0,0 +1,39 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#ifndef SLUDGE_FILESET_H
+#define SLUDGE_FILESET_H
+
+#if ALLOW_FILE
+extern FILE *bigDataFile;
+
+void setFileIndices(FILE *fp, int, unsigned int);
+#endif
+
+unsigned int openFileFromNum(int num);
+bool openSubSlice(int num);
+bool openObjectSlice(int num);
+char *getNumberedString(int value);
+
+bool startAccess();
+void finishAccess();
+
+#endif
diff --git a/engines/sludge/fixScaleSprite.frag b/engines/sludge/fixScaleSprite.frag
new file mode 100644
index 0000000..ed9f6cf
--- /dev/null
+++ b/engines/sludge/fixScaleSprite.frag
@@ -0,0 +1,29 @@
+uniform sampler2D tex0;
+uniform sampler2D tex1;
+uniform sampler2D tex2;
+uniform bool useLightTexture;
+
+varying vec2 varCoord0;
+varying vec2 varCoord1;
+varying vec2 varCoord2;
+
+varying vec4 color;
+varying vec4 secondaryColor;
+
+void main()
+{
+	vec4 texture = texture2D (tex0, varCoord0);
+	vec4 texture2 = texture2D (tex2, varCoord2);
+	vec3 col;
+	if (useLightTexture) {
+		vec4 texture1 = texture2D (tex1, varCoord1);
+		col = texture1.rgb * texture.rgb;
+	} else {
+		col = color.rgb * texture.rgb;
+	}
+	col += vec3(secondaryColor);
+	vec4 color = vec4 (col, color.a * texture.a);
+	col = mix (texture2.rgb, color.rgb, color.a);
+	gl_FragColor = vec4 (col, max(texture.a, texture2.a));
+}
+
diff --git a/engines/sludge/fixScaleSprite.vert b/engines/sludge/fixScaleSprite.vert
new file mode 100644
index 0000000..d9f4e51
--- /dev/null
+++ b/engines/sludge/fixScaleSprite.vert
@@ -0,0 +1,25 @@
+attribute vec4 myVertex;
+attribute vec2 myUV0;
+attribute vec2 myUV1;
+attribute vec2 myUV2;
+
+uniform mat4 myPMVMatrix;
+uniform vec4 myColor;
+uniform vec4 mySecondaryColor;
+
+varying vec2 varCoord0;
+varying vec2 varCoord1;
+varying vec2 varCoord2;
+
+varying vec4 color;
+varying vec4 secondaryColor;
+
+void main() {
+	varCoord0 = myUV0.st;
+	varCoord1 = myUV1.st;
+	varCoord2 = myUV2.st;
+	gl_Position = myPMVMatrix * myVertex;
+
+	color = myColor;
+	secondaryColor = mySecondaryColor;
+}
diff --git a/engines/sludge/floor.cpp b/engines/sludge/floor.cpp
new file mode 100644
index 0000000..826632a
--- /dev/null
+++ b/engines/sludge/floor.cpp
@@ -0,0 +1,290 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#include "allfiles.h"
+#include "newfatal.h"
+#include "fileset.h"
+#include "moreio.h"
+#include "floor.h"
+#include "line.h"
+
+flor *currentFloor = NULL;
+
+bool pointInFloorPolygon(floorPolygon &floorPoly, int x, int y) {
+	int i = 0, j, c = 0;
+	float xp_i, yp_i;
+	float xp_j, yp_j;
+
+	for (j = floorPoly.numVertices - 1; i < floorPoly.numVertices;
+	        j = i ++) {
+
+		xp_i = currentFloor -> vertex[floorPoly.vertexID[i]].x;
+		yp_i = currentFloor -> vertex[floorPoly.vertexID[i]].y;
+		xp_j = currentFloor -> vertex[floorPoly.vertexID[j]].x;
+		yp_j = currentFloor -> vertex[floorPoly.vertexID[j]].y;
+
+		if ((((yp_i <= y) && (y < yp_j)) ||
+		        ((yp_j <= y) && (y < yp_i))) &&
+		        (x < (xp_j - xp_i) * (y - yp_i) / (yp_j - yp_i) + xp_i)) {
+
+			c = !c;
+		}
+	}
+	return c;
+}
+
+bool getMatchingCorners(floorPolygon &a, floorPolygon &b, int &cornerA, int &cornerB) {
+	int sharedVertices = 0;
+	int i, j;
+
+	for (i = 0; i < a.numVertices; i ++) {
+		for (j = 0; j < b.numVertices; j ++) {
+			if (a.vertexID[i] == b.vertexID[j]) {
+				if (sharedVertices ++) {
+					cornerB = a.vertexID[i];
+					return true;
+				} else {
+					cornerA = a.vertexID[i];
+				}
+			}
+		}
+	}
+
+	return false;
+}
+
+bool polysShareSide(floorPolygon &a, floorPolygon &b) {
+	int sharedVertices = 0;
+	int i, j;
+
+	for (i = 0; i < a.numVertices; i ++) {
+		for (j = 0; j < b.numVertices; j ++) {
+			if (a.vertexID[i] == b.vertexID[j]) {
+				if (sharedVertices ++) return true;
+			}
+		}
+	}
+
+	return false;
+}
+
+void noFloor() {
+	currentFloor -> numPolygons = 0;
+	currentFloor -> polygon = NULL;
+	currentFloor -> vertex = NULL;
+	currentFloor -> matrix = NULL;
+}
+
+bool initFloor() {
+	currentFloor = new flor;
+	if (! checkNew(currentFloor)) return false;
+	noFloor();
+	return true;
+}
+
+void killFloor() {
+	for (int i = 0; i < currentFloor -> numPolygons; i ++) {
+		delete currentFloor -> polygon[i].vertexID;
+		delete currentFloor -> matrix[i];
+	}
+	delete currentFloor -> polygon;
+	currentFloor -> polygon = NULL;
+	delete currentFloor -> vertex;
+	currentFloor -> vertex = NULL;
+	delete currentFloor -> matrix;
+	currentFloor -> matrix = NULL;
+}
+
+void setFloorNull() {
+	killFloor();
+	noFloor();
+}
+
+bool setFloor(int fileNum) {
+
+	int i, j;
+
+	killFloor();
+
+	setResourceForFatal(fileNum);
+#if ALLOW_FILE
+	if (! openFileFromNum(fileNum)) return false;
+
+	// Find out how many polygons there are and reserve memory
+
+	currentFloor -> originalNum = fileNum;
+	currentFloor -> numPolygons = fgetc(bigDataFile);
+	currentFloor -> polygon = new floorPolygon[currentFloor -> numPolygons];
+	if (! checkNew(currentFloor -> polygon)) return false;
+
+	// Read in each polygon
+
+	for (i = 0; i < currentFloor -> numPolygons; i ++) {
+
+		// Find out how many vertex IDs there are and reserve memory
+
+		currentFloor -> polygon[i].numVertices = fgetc(bigDataFile);
+		currentFloor -> polygon[i].vertexID = new int[currentFloor -> polygon[i].numVertices];
+		if (! checkNew(currentFloor -> polygon[i].vertexID)) return false;
+
+		// Read in each vertex ID
+
+		for (j = 0; j < currentFloor -> polygon[i].numVertices; j ++) {
+			currentFloor -> polygon[i].vertexID[j] = get2bytes(bigDataFile);
+		}
+	}
+
+	// Find out how many vertices there are and reserve memory
+
+	i = get2bytes(bigDataFile);
+	currentFloor -> vertex = new POINT[i];
+	if (! checkNew(currentFloor -> vertex)) return false;
+
+	for (j = 0; j < i; j ++) {
+
+		currentFloor -> vertex[j].x = get2bytes(bigDataFile);
+		currentFloor -> vertex[j].y = get2bytes(bigDataFile);
+	}
+
+	finishAccess();
+#endif
+	// Now build the movement martix
+
+	currentFloor -> matrix = new int *[currentFloor -> numPolygons];
+	int * * distanceMatrix = new int *[currentFloor -> numPolygons];
+
+	if (! checkNew(currentFloor -> matrix)) return false;
+
+	for (i = 0; i < currentFloor -> numPolygons; i ++) {
+		currentFloor -> matrix[i] = new int [currentFloor -> numPolygons];
+		distanceMatrix        [i] = new int [currentFloor -> numPolygons];
+		if (! checkNew(currentFloor -> matrix[i])) return false;
+		for (j = 0; j < currentFloor -> numPolygons; j ++) {
+			currentFloor -> matrix[i][j] = -1;
+			distanceMatrix        [i][j] = 10000;
+		}
+	}
+
+	for (i = 0; i < currentFloor -> numPolygons; i ++) {
+		for (j = 0; j < currentFloor -> numPolygons; j ++) {
+			if (i != j) {
+				if (polysShareSide(currentFloor -> polygon[i], currentFloor -> polygon[j])) {
+					currentFloor -> matrix[i][j] = j;
+					distanceMatrix        [i][j] = 1;
+				}
+			} else {
+				currentFloor -> matrix[i][j] = -2;
+				distanceMatrix        [i][j] = 0;
+			}
+		}
+	}
+
+	bool madeChange;
+	int lookForDistance = 0;
+
+	do {
+		lookForDistance ++;
+//		debugMatrix ();
+		madeChange = false;
+		for (i = 0; i < currentFloor -> numPolygons; i ++) {
+			for (j = 0; j < currentFloor -> numPolygons; j ++) {
+				if (currentFloor -> matrix[i][j] == -1) {
+
+					// OK, so we don't know how to get from i to j...
+					for (int d = 0; d < currentFloor -> numPolygons; d ++) {
+						if (d != i && d != j) {
+							if (currentFloor -> matrix[i][d] == d &&
+							        currentFloor -> matrix[d][j] >= 0 &&
+							        distanceMatrix        [d][j] <= lookForDistance) {
+
+								currentFloor -> matrix[i][j] = d;
+								distanceMatrix       [i][j] = lookForDistance + 1;
+								madeChange = true;
+							}
+						}
+					}
+				}
+			}
+		}
+	} while (madeChange);
+
+	for (i = 0; i < currentFloor -> numPolygons; i ++) {
+		delete distanceMatrix [i];
+	}
+
+	delete distanceMatrix;
+	distanceMatrix = NULL;
+
+	setResourceForFatal(-1);
+
+	return true;
+}
+
+void drawFloor() {
+	int i, j, nV;
+	for (i = 0; i < currentFloor -> numPolygons; i ++) {
+//		drawLine (i, 0, i + 5, 100);
+		nV = currentFloor -> polygon[i].numVertices;
+		if (nV > 1) {
+			for (j = 1; j < nV; j ++) {
+				drawLine(currentFloor -> vertex[currentFloor -> polygon[i].vertexID[j - 1]].x,
+				         currentFloor -> vertex[currentFloor -> polygon[i].vertexID[j - 1]].y,
+				         currentFloor -> vertex[currentFloor -> polygon[i].vertexID[j]].x,
+				         currentFloor -> vertex[currentFloor -> polygon[i].vertexID[j]].y);
+			}
+			drawLine(currentFloor -> vertex[currentFloor -> polygon[i].vertexID[0]].x,
+			         currentFloor -> vertex[currentFloor -> polygon[i].vertexID[0]].y,
+			         currentFloor -> vertex[currentFloor -> polygon[i].vertexID[nV - 1]].x,
+			         currentFloor -> vertex[currentFloor -> polygon[i].vertexID[nV - 1]].y);
+		}
+	}
+}
+
+int inFloor(int x, int y) {
+	int i, r = -1;
+
+	for (i = 0; i < currentFloor -> numPolygons; i ++)
+		if (pointInFloorPolygon(currentFloor -> polygon[i], x, y))
+			r = i;
+
+	return r;
+}
+
+bool closestPointOnLine(int &closestX, int &closestY, int x1, int y1, int x2, int y2, int xP, int yP) {
+	int xDiff = x2 - x1;
+	int yDiff = y2 - y1;
+
+	double m = xDiff * (xP - x1) + yDiff * (yP - y1);
+	m /= (xDiff * xDiff) + (yDiff * yDiff);
+
+	if (m < 0) {
+		closestX = x1;
+		closestY = y1;
+	} else if (m > 1) {
+		closestX = x2;
+		closestY = y2;
+	} else {
+		closestX = x1 + m * xDiff;
+		closestY = y1 + m * yDiff;
+		return true;
+	}
+	return false;
+}
diff --git a/engines/sludge/floor.h b/engines/sludge/floor.h
new file mode 100644
index 0000000..5c0d050
--- /dev/null
+++ b/engines/sludge/floor.h
@@ -0,0 +1,57 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#ifndef SLUDGE_FLOOR_H
+#define SLUDGE_FLOOR_H
+
+#ifdef _WIN32
+#include "windef.h"
+#endif
+
+struct floorPolygon {
+	int numVertices;
+	int *vertexID;
+};
+
+#ifndef _WIN32
+struct POINT {
+	int x;
+	int y;
+};
+#endif
+
+struct flor {
+	int originalNum;
+	POINT *vertex;
+	int numPolygons;
+	floorPolygon *polygon;
+	int * *matrix;
+};
+
+bool initFloor();
+void setFloorNull();
+bool setFloor(int fileNum);
+void drawFloor();
+int inFloor(int x, int y);
+bool getMatchingCorners(floorPolygon &, floorPolygon &, int &, int &);
+bool closestPointOnLine(int &closestX, int &closestY, int x1, int y1, int x2, int y2, int xP, int yP);
+
+#endif
diff --git a/engines/sludge/fonttext.cpp b/engines/sludge/fonttext.cpp
new file mode 100644
index 0000000..835c2a6
--- /dev/null
+++ b/engines/sludge/fonttext.cpp
@@ -0,0 +1,206 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#include "platform-dependent.h"
+
+#include <stdint.h>
+#include <string.h>
+
+#include "CommonCode/utf8.h"
+
+#include "debug.h"
+#include "allfiles.h"
+#include "stringy.h"
+
+#include "sprites.h"
+#include "colours.h"
+#include "fonttext.h"
+#include "newfatal.h"
+#include "moreio.h"
+
+spriteBank theFont;
+int fontHeight = 0, numFontColours, loadedFontNum;
+char *fontOrderString = NULL;
+short fontSpace = -1;
+
+uint32_t *fontTable = NULL;
+unsigned int fontTableSize = 0;
+
+#define fontInTable(x) ((x<fontTableSize) ? fontTable[(uint32_t) x] : 0)
+
+extern float cameraZoom;
+
+bool isInFont(char *theText) {
+	if (! fontTableSize) return 0;
+	if (! theText[0]) return 0;
+
+	// We don't want to compare strings. Only single characters allowed!
+	if (u8_strlen(theText) > 1) return false;
+
+	int i = 0;
+	uint32_t c = u8_nextchar(theText, &i);
+
+	return u8_strchr(fontOrderString, c, &i);
+}
+
+int stringLength(char *theText) {
+	return u8_strlen(theText);
+}
+
+int stringWidth(char *theText) {
+	int a = 0;
+	uint32_t c;
+	int xOff = 0;
+
+	if (! fontTableSize) return 0;
+
+	while (theText[a]) {
+		c = u8_nextchar(theText, &a);
+		xOff += theFont.sprites[fontInTable(c)].width + fontSpace;
+	}
+
+	return xOff;
+}
+
+void pasteString(char *theText, int xOff, int y, spritePalette &thePal) {
+	sprite *mySprite;
+	int a = 0;
+	uint32_t c;
+
+	if (! fontTableSize) return;
+
+	xOff += (int)((float)(fontSpace >> 1) / cameraZoom);
+	while (theText[a]) {
+		c = u8_nextchar(theText, &a);
+		mySprite = & theFont.sprites[fontInTable(c)];
+		fontSprite(xOff, y, * mySprite, thePal);
+		xOff += (int)((double)(mySprite -> width + fontSpace) / cameraZoom);
+	}
+}
+
+void pasteStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal) {
+	sprite *mySprite;
+	int a = 0;
+	uint32_t c;
+
+	if (! fontTableSize) return;
+
+	xOff += fontSpace >> 1;
+	while (theText[a]) {
+		c = u8_nextchar(theText, &a);
+		mySprite = & theFont.sprites[fontInTable(c)];
+		pasteSpriteToBackDrop(xOff, y, * mySprite, thePal);
+		xOff += mySprite -> width + fontSpace;
+	}
+}
+
+void burnStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal) {
+	sprite *mySprite;
+	int a = 0;
+	uint32_t c;
+
+	if (! fontTableSize) return;
+
+	xOff += fontSpace >> 1;
+	while (theText[a]) {
+		c = u8_nextchar(theText, &a);
+		mySprite = & theFont.sprites[fontInTable(c)];
+		burnSpriteToBackDrop(xOff, y, * mySprite, thePal);
+		xOff += mySprite -> width + fontSpace;
+	}
+}
+
+void fixFont(spritePalette &spal) {
+#if 0
+	delete [] spal.tex_names;
+	delete [] spal.burnTex_names;
+	delete [] spal.tex_h;
+	delete [] spal.tex_w;
+
+	spal.numTextures = theFont.myPalette.numTextures;
+
+	spal.tex_names = new GLuint [spal.numTextures];
+	if (! checkNew(spal.tex_names)) return;
+	spal.burnTex_names = new GLuint [spal.numTextures];
+	if (! checkNew(spal.burnTex_names)) return;
+	spal.tex_w = new int [spal.numTextures];
+	if (! checkNew(spal.tex_w)) return;
+	spal.tex_h = new int [spal.numTextures];
+	if (! checkNew(spal.tex_h)) return;
+
+	for (int i = 0; i < theFont.myPalette.numTextures; i++) {
+		spal.tex_names[i] = theFont.myPalette.tex_names[i];
+		spal.burnTex_names[i] = theFont.myPalette.burnTex_names[i];
+		spal.tex_w[i] = theFont.myPalette.tex_w[i];
+		spal.tex_h[i] = theFont.myPalette.tex_h[i];
+	}
+#endif
+}
+
+void setFontColour(spritePalette &sP, byte r, byte g, byte b) {
+	sP.originalRed = r;
+	sP.originalGreen = g;
+	sP.originalBlue = b;
+}
+
+bool loadFont(int filenum, const char *charOrder, int h) {
+	int a = 0;
+	uint32_t c;
+
+	delete [] fontOrderString;
+	fontOrderString = copyString(charOrder);
+
+	forgetSpriteBank(theFont);
+
+	loadedFontNum = filenum;
+
+
+	fontTableSize = 0;
+	while (charOrder[a]) {
+		c = u8_nextchar(charOrder, &a);
+		if (c > fontTableSize) fontTableSize = c;
+	}
+	fontTableSize++;
+
+	delete [] fontTable;
+	fontTable = new uint32_t [fontTableSize];
+	if (! checkNew(fontTable)) return false;
+
+	for (a = 0; a < fontTableSize; a ++) {
+		fontTable[a] = 0;
+	}
+	a = 0;
+	int i = 0;
+	while (charOrder[a]) {
+		c = u8_nextchar(charOrder, &a);
+		fontTable[c] = i;
+		i++;
+	}
+
+	if (! loadSpriteBank(filenum, theFont, true)) {
+		fatal("Can't load font");
+		return false;
+	}
+
+	numFontColours = theFont.myPalette.total;
+	fontHeight = h;
+	return true;
+}
diff --git a/engines/sludge/fonttext.h b/engines/sludge/fonttext.h
new file mode 100644
index 0000000..f33876f
--- /dev/null
+++ b/engines/sludge/fonttext.h
@@ -0,0 +1,35 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#ifndef SLUDGE_FONTTEXT_H
+#define SLUDGE_FONTTEXT_H
+
+bool loadFont(int filenum, const char *charOrder, int);
+void pasteString(char *theText, int, int, spritePalette &);
+void fixFont(spritePalette &spal);
+void setFontColour(spritePalette &sP, byte r, byte g, byte b);
+int stringWidth(char *theText);
+int stringLength(char *theText);
+void pasteStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal);
+void burnStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal);
+bool isInFont(char *theText);
+
+#endif
diff --git a/engines/sludge/freeze.cpp b/engines/sludge/freeze.cpp
new file mode 100644
index 0000000..f245ad0
--- /dev/null
+++ b/engines/sludge/freeze.cpp
@@ -0,0 +1,364 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#include "allfiles.h"
+#include "debug.h"
+#include "graphics.h"
+#include "newfatal.h"
+#include "sprites.h"
+#include "sprbanks.h"
+#include "people.h"
+#include "sludger.h"
+#include "objtypes.h"
+#include "region.h"
+#include "backdrop.h"
+#include "talk.h"
+#include "fonttext.h"
+#include "statusba.h"
+#include "freeze.h"
+#include "zbuffer.h"
+
+extern onScreenPerson *allPeople;
+extern screenRegion *allScreenRegions;
+extern screenRegion *overRegion;
+extern speechStruct *speech;
+extern inputType input;
+#if 0
+extern GLuint backdropTextureName;
+#endif
+extern parallaxLayer *parallaxStuff;
+extern int lightMapNumber, zBufferNumber;
+extern eventHandlers *currentEvents;
+extern personaAnimation *mouseCursorAnim;
+extern int mouseCursorFrameNum;
+extern int cameraX, cameraY;
+extern unsigned int sceneWidth, sceneHeight;
+extern float cameraZoom;
+extern zBufferData zBuffer;
+extern bool backdropExists;
+frozenStuffStruct *frozenStuff = NULL;
+extern unsigned int sceneWidth, sceneHeight;
+
+void shufflePeople();
+#if 0
+GLuint freezeTextureName = 0;
+#endif
+
+void freezeGraphics() {
+#if 0
+	glViewport(0, 0, realWinWidth, realWinHeight);
+
+	glGenTextures(1, &freezeTextureName);
+#endif
+	int w = winWidth;
+	int h = winHeight;
+	if (! NPOT_textures) {
+		w = getNextPOT(winWidth);
+		h = getNextPOT(winHeight);
+	}
+#if 0
+	glBindTexture(GL_TEXTURE_2D, freezeTextureName);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+
+	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0, freezeTextureName);
+#endif
+	// Temporarily disable AA
+	int antiAlias = gameSettings.antiAlias;
+	gameSettings.antiAlias = 0;
+
+
+	int x = 0;
+	while (x < winWidth) {
+		int y = 0;
+
+		if (winWidth - x < realWinWidth) {
+			w = winWidth - x;
+		} else {
+			w = realWinWidth;
+		}
+
+		while (y < winHeight) {
+
+			if (winHeight - y < realWinHeight) {
+				h = winHeight - y;
+			} else {
+				h = realWinHeight;
+			}
+#if 0
+			const GLfloat bPMVMatrix[] = {
+				2.0f / realWinWidth * cameraZoom,                            .0,   .0,  .0,
+				.0, 2.0f / realWinHeight * cameraZoom,   .0,  .0,
+				.0,                            .0, 1.0f,  .0,
+				-2.0f * (x / realWinWidth) - 1.0f,  -2.0f * (y / realWinHeight) - 1.0f,   .0, 1.0f
+
+			};
+			for (int i = 0; i < 16; i++) {
+				aPMVMatrix[i] = bPMVMatrix[i];
+			}
+			// Render scene
+			glDepthMask(GL_TRUE);
+			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen
+			glDepthMask(GL_FALSE);
+
+			drawBackDrop();                 // Draw the room
+			drawZBuffer(cameraX, cameraY, false);
+
+			glEnable(GL_DEPTH_TEST);
+
+			drawPeople();                   // Then add any moving characters...
+
+			glDisable(GL_DEPTH_TEST);
+
+
+			// Copy Our ViewPort To The Texture
+			copyTexSubImage2D(GL_TEXTURE_2D, 0, x, y, 0, 0, w, h, freezeTextureName);
+#endif
+			y += h;
+		}
+		x += w;
+	}
+
+	gameSettings.antiAlias = antiAlias;
+
+#if 0
+	glViewport(viewportOffsetX, viewportOffsetY, viewportWidth, viewportHeight);
+	setPixelCoords(false);
+#endif
+}
+
+bool freeze() {
+	debugOut("calling freeze()\n");
+	frozenStuffStruct *newFreezer = new frozenStuffStruct;
+	if (! checkNew(newFreezer)) return false;
+
+	// Grab a copy of the current scene
+	freezeGraphics();
+#if 0
+	newFreezer -> backdropTextureName = backdropTextureName;
+#endif
+	int picWidth = sceneWidth;
+	int picHeight = sceneHeight;
+	if (! NPOT_textures) {
+		picWidth = getNextPOT(picWidth);
+		picHeight = getNextPOT(picHeight);
+	}
+#if 0
+	newFreezer -> backdropTexture = new GLubyte [picHeight * picWidth * 4];
+	if (! checkNew(newFreezer -> backdropTexture)) return false;
+
+	saveTexture(backdropTextureName, newFreezer->backdropTexture);
+
+	backdropTextureName = 0;
+#endif
+	newFreezer -> sceneWidth = sceneWidth;
+	newFreezer -> sceneHeight = sceneHeight;
+	newFreezer -> cameraX = cameraX;
+	newFreezer -> cameraY = cameraY;
+	newFreezer -> cameraZoom = cameraZoom;
+#if 0
+	newFreezer -> lightMapTexture = lightMap.data;
+	newFreezer -> lightMapTextureName = lightMap.name;
+	newFreezer -> lightMapNumber = lightMapNumber;
+	lightMap.data = NULL;
+	lightMap.name = 0;
+	newFreezer -> parallaxStuff = parallaxStuff;
+	parallaxStuff = NULL;
+	newFreezer -> zBufferImage = zBuffer.tex;
+	newFreezer -> zBufferNumber = zBuffer.originalNum;
+	newFreezer -> zPanels = zBuffer.numPanels;
+	zBuffer.tex = NULL;
+#endif
+	// resizeBackdrop kills parallax stuff, light map, z-buffer...
+	if (! resizeBackdrop(winWidth, winHeight)) return fatal("Can't create new temporary backdrop buffer");
+
+	if (! NPOT_textures) {
+		picWidth = getNextPOT(sceneWidth);
+		picHeight = getNextPOT(sceneHeight);
+#if 0
+		backdropTexW = (double) sceneWidth / picWidth;
+		backdropTexH = (double) sceneHeight / picHeight;
+#endif
+	}
+
+#if 0
+	// Copy the old scene to the new backdrop
+	deleteTextures(1, &backdropTextureName);
+	backdropTextureName = freezeTextureName;
+	backdropExists = true;
+
+	// Free texture memory used by old stuff
+	parallaxStuff = newFreezer -> parallaxStuff;
+	while (parallaxStuff) {
+		deleteTextures(1, &parallaxStuff -> textureName);
+		parallaxStuff = parallaxStuff -> next;
+	}
+	if (newFreezer -> zBufferImage) {
+		deleteTextures(1, &zBuffer.texName);
+	}
+	if (newFreezer -> lightMapTextureName) {
+		deleteTextures(1, &newFreezer -> lightMapTextureName);
+	}
+	if (newFreezer -> backdropTextureName) {
+		deleteTextures(1, &newFreezer -> backdropTextureName);
+	}
+#endif
+	newFreezer -> allPeople = allPeople;
+	allPeople = NULL;
+
+	statusStuff *newStatusStuff = new statusStuff;
+	if (! checkNew(newStatusStuff)) return false;
+	newFreezer -> frozenStatus = copyStatusBarStuff(newStatusStuff);
+
+	newFreezer -> allScreenRegions = allScreenRegions;
+	allScreenRegions = NULL;
+	overRegion = NULL;
+
+	newFreezer -> mouseCursorAnim = mouseCursorAnim;
+	newFreezer -> mouseCursorFrameNum = mouseCursorFrameNum;
+	mouseCursorAnim = makeNullAnim();
+	mouseCursorFrameNum = 0;
+
+	newFreezer -> speech = speech;
+	initSpeech();
+
+	newFreezer -> currentEvents = currentEvents;
+	currentEvents = new eventHandlers;
+	if (! checkNew(currentEvents)) return false;
+	memset(currentEvents, 0, sizeof(eventHandlers));
+
+	newFreezer -> next = frozenStuff;
+	frozenStuff = newFreezer;
+
+	return true;
+}
+
+int howFrozen() {
+	int a = 0;
+	frozenStuffStruct *f = frozenStuff;
+	while (f) {
+		a ++;
+		f = f -> next;
+	}
+	return a;
+}
+
+#if 0
+extern GLubyte *backdropTexture;
+#endif
+
+void unfreeze(bool killImage) {
+	frozenStuffStruct *killMe = frozenStuff;
+
+	if (! frozenStuff) return;
+
+	sceneWidth = frozenStuff -> sceneWidth;
+	sceneHeight = frozenStuff -> sceneHeight;
+
+	cameraX = frozenStuff -> cameraX;
+	cameraY = frozenStuff -> cameraY;
+	input.mouseX = (int)(input.mouseX * cameraZoom);
+	input.mouseY = (int)(input.mouseY * cameraZoom);
+	cameraZoom = frozenStuff -> cameraZoom;
+	input.mouseX = (int)(input.mouseX / cameraZoom);
+	input.mouseY = (int)(input.mouseY / cameraZoom);
+	setPixelCoords(false);
+
+	killAllPeople();
+	allPeople = frozenStuff -> allPeople;
+
+	killAllRegions();
+	allScreenRegions = frozenStuff -> allScreenRegions;
+
+	killLightMap();
+#if 0
+	lightMap.data = frozenStuff -> lightMapTexture;
+	lightMap.name = frozenStuff -> lightMapTextureName;
+	lightMapNumber = frozenStuff -> lightMapNumber;
+	if (lightMapNumber) {
+		lightMap.name = 0;
+		loadLightMap(lightMapNumber);
+	}
+
+	killZBuffer();
+	zBuffer.tex = frozenStuff -> zBufferImage;
+	zBuffer.originalNum = frozenStuff -> zBufferNumber;
+	zBuffer.numPanels = frozenStuff -> zPanels;
+	if (zBuffer.numPanels) {
+		zBuffer.texName = 0;
+		setZBuffer(zBuffer.originalNum);
+	}
+
+	killParallax();
+	parallaxStuff = frozenStuff -> parallaxStuff;
+	reloadParallaxTextures();
+
+	if (killImage) killBackDrop();
+	backdropTextureName = frozenStuff -> backdropTextureName;
+	if (backdropTexture) delete[] backdropTexture;
+	backdropTexture = frozenStuff -> backdropTexture;
+	backdropExists = true;
+	if (backdropTextureName) {
+		backdropTextureName = 0;
+		glGenTextures(1, &backdropTextureName);
+		glBindTexture(GL_TEXTURE_2D, backdropTextureName);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+
+		if (gameSettings.antiAlias < 0) {
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+		} else {
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+		}
+
+		int picWidth = sceneWidth;
+		int picHeight = sceneHeight;
+		if (! NPOT_textures) {
+			picWidth = getNextPOT(picWidth);
+			picHeight = getNextPOT(picHeight);
+		}
+		// Restore the backdrop
+		texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, frozenStuff -> backdropTexture, backdropTextureName);
+	}
+#endif
+	deleteAnim(mouseCursorAnim);
+	mouseCursorAnim = frozenStuff -> mouseCursorAnim;
+	mouseCursorFrameNum = frozenStuff -> mouseCursorFrameNum;
+
+	restoreBarStuff(frozenStuff -> frozenStatus);
+
+	delete currentEvents;
+	currentEvents = frozenStuff -> currentEvents;
+	killAllSpeech();
+	delete speech;
+
+	speech = frozenStuff -> speech;
+	frozenStuff = frozenStuff -> next;
+
+	overRegion = NULL;
+	delete killMe;
+	killMe = NULL;
+
+}
diff --git a/engines/sludge/freeze.h b/engines/sludge/freeze.h
new file mode 100644
index 0000000..1682d3b
--- /dev/null
+++ b/engines/sludge/freeze.h
@@ -0,0 +1,55 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#ifndef SLUDGE_FREEZE_H
+#define SLUDGE_FREEZE_H
+
+
+struct frozenStuffStruct {
+	onScreenPerson *allPeople;
+	screenRegion *allScreenRegions;
+#if 0
+	GLubyte *backdropTexture;
+	GLuint backdropTextureName;
+	GLuint lightMapTextureName;
+	GLubyte *lightMapTexture;
+	GLubyte *zBufferImage;
+#endif
+	int zPanels;
+	parallaxLayer *parallaxStuff;
+	int lightMapNumber, zBufferNumber;
+	speechStruct *speech;
+	statusStuff *frozenStatus;
+	eventHandlers *currentEvents;
+	personaAnimation *mouseCursorAnim;
+	int mouseCursorFrameNum;
+	int cameraX, cameraY, sceneWidth, sceneHeight;
+	float cameraZoom;
+
+	frozenStuffStruct *next;
+};
+
+
+bool freeze();
+void unfreeze(bool killImage = true);
+int howFrozen();
+
+#endif
diff --git a/engines/sludge/graphics.cpp b/engines/sludge/graphics.cpp
new file mode 100644
index 0000000..8bdc917
--- /dev/null
+++ b/engines/sludge/graphics.cpp
@@ -0,0 +1,956 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#if 0
+#include <stdarg.h>
+
+#include <SDL/SDL.h>
+#endif
+
+#include "allfiles.h"
+#include "debug.h"
+#include "platform-dependent.h"
+#include "CommonCode/specialsettings.h"
+#include "graphics.h"
+#include "language.h"
+#include "newfatal.h"
+#include "sprbanks.h"
+#include "zbuffer.h"
+#include "backdrop.h"
+#include "shaders.h"
+#include "movie.h"
+#include "stringy.h"
+
+#include "language.h" // for settings
+
+#if 0
+#if !defined(HAVE_GLES2)
+#ifdef _WIN32
+#include <GL\glu.h> // handy for gluErrorString
+#elif defined __APPLE__
+#include <OpenGL/glu.h>
+#else
+#include <GL/glu.h>
+#endif
+#endif
+#endif
+
+unsigned int winWidth, winHeight;
+int viewportHeight, viewportWidth;
+int viewportOffsetX = 0, viewportOffsetY = 0;
+
+extern float cameraZoom;
+
+bool NPOT_textures = true;
+
+extern int specialSettings;
+
+void setMovieViewport();
+
+#if 0
+extern GLuint backdropTextureName;
+extern GLuint snapshotTextureName;
+#endif
+
+extern unsigned int sceneWidth, sceneHeight;
+extern zBufferData zBuffer;
+extern int lightMapNumber;
+#if 0
+extern GLuint yTextureName;
+extern GLuint uTextureName;
+extern GLuint vTextureName;
+//extern GLubyte * ytex, * utex, * vtex;
+
+shaders shader;
+GLfloat aPMVMatrix[16];
+
+void sludgeDisplay();
+
+GLfloat primaryColor[4];
+GLfloat secondaryColor[4];
+#endif
+
+struct textureList *firstTexture = NULL;
+
+textureList *addTexture() {
+	textureList *newTexture = new textureList;
+	newTexture -> next = firstTexture;
+	firstTexture = newTexture;
+	return newTexture;
+}
+
+#if 0
+void deleteTextures(GLsizei n,  const GLuint *textures) {
+	if (firstTexture == NULL) {
+		//debugOut("Deleting texture while list is already empty.\n");
+	} else {
+		for (int i = 0; i < n; i++) {
+			bool found = false;
+			textureList *list = firstTexture;
+			if (list->name == textures[i]) {
+				found = true;
+				firstTexture = list->next;
+				delete list;
+				continue;
+			}
+
+			while (list->next) {
+				if (list->next->name == textures[i]) {
+					found = true;
+					textureList *deleteMe = list->next;
+					list->next = list->next->next;
+					delete deleteMe;
+					break;
+				}
+				list = list->next;
+			}
+			//if (!found)
+			//  debugOut("Deleting texture that was not in list.\n");
+		}
+	}
+
+	glDeleteTextures(n, textures);
+
+}
+
+void getTextureDimensions(GLuint name, GLint *width,  GLint *height) {
+	textureList *list = firstTexture;
+	while (list) {
+		if (list->name == name)  {
+			*width = list->width;
+			*height = list->height;
+#if !defined(HAVE_GLES2)
+			//For the following test it is assumed that glBindTexture is always
+			//called for the right texture before getTextureDimensions.
+			GLint tw, th;
+			glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &tw);
+			glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &th);
+			if (tw != *width || th != *height) {
+				debugOut("Warning: Texture dimensions don't match: They are %ix%i, but SLUDGEs bookkeeping says %ix%i.\n", tw, th, *width, *height);
+			}
+#endif
+			return;
+		}
+		list = list->next;
+	}
+	fatal("Texture not found in list.\n");
+}
+
+void storeTextureDimensions(GLuint name, GLsizei width,  GLsizei height, const char *file, int line) {
+	if (! NPOT_textures && !(((height & (height - 1)) == 0) || ((width & (width - 1)) == 0))) {
+		debugOut("I was told to create a texture with dimensions %ix%i in %s @ line %d although NPOT textures are disabled.\n", width, height, file, line);
+		//height = getNextPOT(height);
+		//width = getNextPOT(width);
+	}
+
+	textureList *list = firstTexture;
+	while (list) {
+		if (list->name == name)  {
+			//debugOut("Texture dimensions are overwritten.\n");
+			break;
+		}
+		list = list->next;
+	}
+	if (list == NULL) {
+		list = addTexture();
+	}
+	list->name = name;
+	list->width = width;
+	list->height = height;
+
+}
+#endif
+
+#ifdef HAVE_GLES2
+void glesCopyTexSubImage2D(GLenum target,  GLint level, GLint xoffset, GLint yoffset, GLint x,  GLint y,  GLsizei width,  GLsizei height) {
+	// Work around for broken glCopy(Sub)TexImage2D...
+	void *tmp = malloc(width * height * 4);
+	glReadPixels(x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, tmp);
+	glTexSubImage2D(target, level, xoffset, yoffset, width, height, GL_RGBA, GL_UNSIGNED_BYTE, tmp);
+	free(tmp);
+}
+void glesCopyTexImage2D(GLenum target,  GLint level,  GLenum internalformat,  GLint x,  GLint y,  GLsizei width,  GLsizei height,  GLint border) {
+	// Work around for broken glCopy(Sub)TexImage2D...
+	void *tmp = malloc(width * height * 4);
+	glReadPixels(x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, tmp);
+	glTexImage2D(target, level, GL_RGBA, width, height, border, GL_RGBA, GL_UNSIGNED_BYTE, tmp);
+	free(tmp);
+}
+#endif
+
+#if 0
+void dcopyTexImage2D(GLenum target,  GLint level,  GLenum internalformat,  GLint x,  GLint y,  GLsizei width,  GLsizei height,  GLint border, GLuint name, const char *file, int line) {
+
+	glBindTexture(GL_TEXTURE_2D, name);
+#ifdef HAVE_GLES2_
+	glesCopyTexImage2D(target, level, internalformat, x, y, width, height, border);
+#else
+	glCopyTexImage2D(target, level, internalformat, x, y, width, height, border);
+#endif
+}
+
+void dcopyTexSubImage2D(GLenum target,  GLint level,  GLint xoffset,  GLint yoffset,  GLint x,  GLint y,  GLsizei width,  GLsizei height, GLuint name, const char *file, int line) {
+	glBindTexture(GL_TEXTURE_2D, name);
+#ifdef HAVE_GLES2_
+	glesCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
+#else
+	glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
+#endif
+}
+
+void dtexImage2D(GLenum target,  GLint level,  GLint internalformat,  GLsizei width,  GLsizei height,
+                 GLint border,  GLenum format,  GLenum type,  const GLvoid *data, GLuint name, const char *file, int line) {
+	storeTextureDimensions(name, width,  height, file, line);
+	glBindTexture(GL_TEXTURE_2D, name);
+	glTexImage2D(target, level, internalformat, width, height, border, format, type,  data);
+}
+
+void dtexSubImage2D(GLenum target,  GLint level,  GLint xoffset,  GLint yoffset,  GLsizei width,  GLsizei height,
+                    GLenum format,  GLenum type,  const GLvoid *data, GLuint name, const char *file, int line) {
+	storeTextureDimensions(name, width,  height, file, line);
+	glBindTexture(GL_TEXTURE_2D, name);
+	glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, data);
+}
+
+void setPrimaryColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a) {
+	primaryColor[0] = r;
+	primaryColor[1] = g;
+	primaryColor[2] = b;
+	primaryColor[3] = a;
+}
+
+void setSecondaryColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a) {
+	secondaryColor[0] = r;
+	secondaryColor[1] = g;
+	secondaryColor[2] = b;
+	secondaryColor[3] = a;
+}
+
+void drawQuad(GLint program, const GLfloat *vertices, int numTexCoords, ...) {
+	int i, vertexLoc, texCoordLocs[numTexCoords];
+	const GLfloat *texCoords[numTexCoords];
+
+	va_list vl;
+	va_start(vl, numTexCoords);
+	for (i = 0; i < numTexCoords; i++) {
+		texCoords[i] = va_arg(vl, const GLfloat *);
+	}
+	va_end(vl);
+
+	glUniform4f(glGetUniformLocation(program, "myColor"), primaryColor[0], primaryColor[1], primaryColor[2], primaryColor[3]);
+	if (program == shader.smartScaler || program == shader.paste) {
+		glUniform4f(glGetUniformLocation(program, "mySecondaryColor"), secondaryColor[0], secondaryColor[1], secondaryColor[2], secondaryColor[3]);
+	}
+
+	vertexLoc = glGetAttribLocation(program, "myVertex");
+	texCoordLocs[0] = glGetAttribLocation(program, "myUV0");
+	if (numTexCoords > 1) texCoordLocs[1] = glGetAttribLocation(program, "myUV1");
+	if (numTexCoords > 2) texCoordLocs[2] = glGetAttribLocation(program, "myUV2");
+	if (numTexCoords > 3) texCoordLocs[3] = glGetAttribLocation(program, "myUV3");
+
+	glEnableVertexAttribArray(vertexLoc);
+	glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, vertices);
+
+	for (i = 0; i < numTexCoords; i++) {
+		if (texCoords[i]) {
+			glEnableVertexAttribArray(texCoordLocs[i]);
+			glVertexAttribPointer(texCoordLocs[i], 2, GL_FLOAT, GL_FALSE, 0, texCoords[i]);
+		}
+	}
+
+	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
+
+	for (i = 0; i < numTexCoords; i++) {
+		if (texCoords[i]) {
+			glDisableVertexAttribArray(texCoordLocs[i]);
+		}
+	}
+	glDisableVertexAttribArray(vertexLoc);
+
+}
+
+
+void setPMVMatrix(GLint program) {
+	glUniformMatrix4fv(glGetUniformLocation(program, "myPMVMatrix"), 1, GL_FALSE, aPMVMatrix);
+}
+#endif
+// This is for swapping settings between rendering to texture or to the screen
+void setPixelCoords(bool pixels) {
+	static int current = -1;
+//	if (current == pixels) return;
+	current = pixels;
+#if 0
+	glBindTexture(GL_TEXTURE_2D, backdropTextureName);
+
+	if (pixels) {
+
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+
+		glClear(GL_COLOR_BUFFER_BIT);
+
+		const GLfloat bPMVMatrix[] = {
+			2.0f / viewportWidth,                  .0,   .0,  .0,
+			.0, 2.0f / viewportHeight,   .0,  .0,
+			.0,                  .0, 1.0f,  .0,
+			-1.0,               -1.0f,   .0, 1.0f
+
+		};
+		for (int i = 0; i < 16; i++) {
+			aPMVMatrix[i] = bPMVMatrix[i];
+		}
+	} else {
+		if (gameSettings.antiAlias < 0) {
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+		} else {
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+		}
+
+		GLfloat w = (GLfloat) winWidth / cameraZoom;
+		GLfloat h = (GLfloat) winHeight / cameraZoom;
+
+		const GLfloat bPMVMatrix[] = {
+			2.0f / w,      .0,   .0,  .0,
+			.0, -2.0f / h,   .0,  .0,
+			.0,      .0, 1.0f,  .0,
+			-1.0,    1.0f,   .0, 1.0f
+
+		};
+		for (int i = 0; i < 16; i++) {
+			aPMVMatrix[i] = bPMVMatrix[i];
+		}
+	}
+#endif
+}
+
+int desktopW = 0, desktopH = 0;
+bool runningFullscreen = false;
+
+
+#if defined(HAVE_GLES2)
+void saveTexture(GLuint tex, GLubyte *data) {
+	// use an FBO to easily grab the texture...
+	static GLuint fbo = 0;
+	GLuint old_fbo;
+	GLint tw, th;
+	GLint old_vp[4];
+	if (fbo == 0) {
+		glGenFramebuffers(1, &fbo);
+	}
+	glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint *)&old_fbo);
+	glBindFramebuffer(GL_FRAMEBUFFER, fbo);
+	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0);
+	getTextureDimensions(tex, &tw, &th);
+	glGetIntegerv(GL_VIEWPORT, old_vp);
+	glViewport(0, 0, tw, th);
+	glBindFramebuffer(GL_FRAMEBUFFER, fbo);
+	glReadPixels(0, 0, tw, th, GL_RGBA, GL_UNSIGNED_BYTE, data);
+	glViewport(old_vp[0], old_vp[1], old_vp[2], old_vp[3]);
+	glBindFramebuffer(GL_FRAMEBUFFER, old_fbo);
+}
+#elif defined _WIN32
+// Replacement for glGetTexImage, because some ATI drivers are buggy.
+void saveTexture(GLuint tex, GLubyte *data) {
+	setPixelCoords(true);
+
+	glBindTexture(GL_TEXTURE_2D, tex);
+
+	GLint tw, th;
+	getTextureDimensions(tex, &tw, &th);
+
+	//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+
+	int xoffset = 0;
+	while (xoffset < tw) {
+		int w = (tw - xoffset < viewportWidth) ? tw - xoffset : viewportWidth;
+
+		int yoffset = 0;
+		while (yoffset < th) {
+			int h = (th - yoffset < viewportHeight) ? th - yoffset : viewportHeight;
+
+			glClear(GL_COLOR_BUFFER_BIT);   // Clear The Screen
+
+			const GLfloat vertices[] = {
+				(GLfloat) - xoffset, (GLfloat) - yoffset, 0.f,
+				(GLfloat)tw - xoffset, (GLfloat) - yoffset, 0.f,
+				(GLfloat) - xoffset, (GLfloat) - yoffset + th, 0.f,
+				(GLfloat)tw - xoffset, (GLfloat) - yoffset + th, 0.f
+			};
+
+			const GLfloat texCoords[] = {
+				0.0f, 0.0f,
+				1.0f, 0.0f,
+				0.0f, 1.0f,
+				1.0f, 1.0f
+			};
+
+			glUseProgram(shader.texture);
+			setPMVMatrix(shader.texture);
+
+			drawQuad(shader.texture, vertices, 1, texCoords);
+			glUseProgram(0);
+
+			for (int i = 0; i < h; i++)   {
+				glReadPixels(viewportOffsetX, viewportOffsetY + i, w, 1, GL_RGBA, GL_UNSIGNED_BYTE, data + xoffset * 4 + (yoffset + i) * 4 * tw);
+			}
+
+			yoffset += viewportHeight;
+		}
+
+		xoffset += viewportWidth;
+	}
+	//glReadPixels(viewportOffsetX, viewportOffsetY, tw, th, GL_RGBA, GL_UNSIGNED_BYTE, data);
+
+	setPixelCoords(false);
+
+}
+#else
+#if 0
+void saveTexture(GLuint tex, GLubyte *data) {
+
+	glBindTexture(GL_TEXTURE_2D, tex);
+	glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
+}
+#endif
+#endif
+
+// This is for setting windowed or fullscreen graphics.
+// Used for switching, and for initial window creation.
+void setGraphicsWindow(bool fullscreen, bool restoreGraphics, bool resize) {
+#if defined(PANDORA)
+	fullscreen = true;
+#endif
+#if 0
+	GLubyte *snapTexture = NULL;
+
+	Uint32 videoflags = 0;
+
+	if (! desktopW) {
+
+		// Get video hardware information
+		const SDL_VideoInfo *videoInfo = SDL_GetVideoInfo();
+		desktopW = videoInfo->current_w;
+		desktopH = videoInfo->current_h;
+
+	} else if (restoreGraphics && fullscreen == runningFullscreen & ! resize) return;
+
+	runningFullscreen = fullscreen;
+
+	if (restoreGraphics) {
+		/*
+		 * Save the textures
+		 */
+		if (backdropTextureName) {
+			if (backdropTexture) delete backdropTexture;
+			int picWidth = sceneWidth;
+			int picHeight = sceneHeight;
+			if (! NPOT_textures) {
+				picWidth = getNextPOT(picWidth);
+				picHeight = getNextPOT(picHeight);
+			}
+			backdropTexture = new GLubyte [picHeight * picWidth * 4];
+			if (! checkNew(backdropTexture)) return;
+
+			saveTexture(backdropTextureName, backdropTexture);
+		}
+		if (snapshotTextureName) {
+			int picWidth = winWidth;
+			int picHeight = winHeight;
+			if (! NPOT_textures) {
+				picWidth = getNextPOT(picWidth);
+				picHeight = getNextPOT(picHeight);
+			}
+			snapTexture = new GLubyte [picHeight * picWidth * 4];
+			if (! checkNew(snapTexture)) return;
+
+			saveTexture(snapshotTextureName, snapTexture);
+		}
+	}
+
+	/*
+	 * Set the graphics mode
+	 */
+	float winAspect = (float) winWidth / winHeight;
+
+	if (fullscreen) {
+		specialSettings &= ~SPECIAL_INVISIBLE;
+#if !defined(HAVE_GLES2)
+		videoflags = SDL_OPENGL | SDL_FULLSCREEN;
+#else
+		videoflags = SDL_SWSURFACE | SDL_FULLSCREEN;
+#endif
+
+		if (gameSettings.fixedPixels) {
+			viewportWidth = realWinWidth = winWidth;
+			viewportHeight = realWinHeight = winHeight;
+			viewportOffsetY = 0;
+			viewportOffsetX = 0;
+		} else {
+			realWinWidth = desktopW;
+			realWinHeight = desktopH;
+
+			float realAspect = (float) realWinWidth / realWinHeight;
+
+			if (realAspect > winAspect) {
+				viewportHeight = realWinHeight;
+				viewportWidth = (int)(realWinHeight * winAspect);
+				viewportOffsetY = 0;
+				viewportOffsetX = (realWinWidth - viewportWidth) / 2;
+			} else {
+				viewportWidth = realWinWidth;
+				viewportHeight = (int)((float) realWinWidth / winAspect);
+				viewportOffsetY = (realWinHeight - viewportHeight) / 2;
+				viewportOffsetX = 0;
+			}
+		}
+
+	} else {
+#if !defined(HAVE_GLES2)
+		videoflags = SDL_OPENGL/* | SDL_RESIZABLE*/;
+#else
+		videoflags = SDL_SWSURFACE;
+#endif
+
+		if (resize) {
+			float realAspect = (float) desktopW / desktopH;
+
+			if (realAspect > winAspect) {
+				realWinWidth = (int)(realWinHeight * winAspect);
+			} else {
+				realWinHeight = (int)(realWinWidth / winAspect);
+			}
+
+			realAspect = (float) realWinWidth / realWinHeight;
+
+			if (realAspect > winAspect) {
+				viewportHeight = realWinHeight;
+				viewportWidth = (int)(realWinHeight * winAspect);
+				viewportOffsetY = 0;
+				viewportOffsetX = (realWinWidth - viewportWidth) / 2;
+			} else {
+				viewportWidth = realWinWidth;
+				viewportHeight = (int)((float) realWinWidth / winAspect);
+				viewportOffsetY = (realWinHeight - viewportHeight) / 2;
+				viewportOffsetX = 0;
+			}
+		} else {
+
+			if (gameSettings.fixedPixels) {
+				viewportWidth = realWinWidth = winWidth;
+				viewportHeight = realWinHeight = winHeight;
+				viewportOffsetY = 0;
+				viewportOffsetX = 0;
+			} else {
+				realWinHeight = desktopH * 3 / 4;
+				realWinWidth = (int)(realWinHeight * winAspect);
+
+				if (realWinWidth > desktopW) {
+					realWinWidth = desktopW;
+					realWinHeight = (int)((float) realWinWidth / winAspect);
+				}
+
+				viewportHeight = realWinHeight;
+				viewportWidth = realWinWidth;
+				viewportOffsetY = 0;
+				viewportOffsetX = 0;
+			}
+		}
+	}
+
+	debugHeader();
+
+	if (SDL_SetVideoMode(realWinWidth, realWinHeight, 32, videoflags) == 0) {
+		msgBox("Startup Error: Couldn't set video mode.", SDL_GetError());
+		SDL_Quit();
+		exit(2);
+	}
+	debugOut("Video mode %d %d set successfully.\n", realWinWidth, realWinHeight);
+
+#if defined(HAVE_GLES2)
+	if (EGL_Open()) {
+		msgBox("Startup Error", "Couldn't initialize EGL.");
+		SDL_Quit();
+		exit(1);
+	}
+	EGL_Init();
+#endif
+
+	GLint uniform;
+	const char *Vertex;
+	const char *Fragment;
+
+	Vertex = shaderFileRead("scale.vert");
+
+#if !defined(HAVE_GLES2)
+	Fragment = shaderFileRead("scale.frag");
+#else
+	/*  const GLubyte *str;
+	    int glDerivativesAvailable;
+	    str = glGetString (GL_EXTENSIONS);
+	    glDerivativesAvailable = (strstr((const char *)str, "GL_OES_standard_derivatives") != NULL);
+	    if (!glDerivativesAvailable) {
+	        debugOut("Extension \"GL_OES_standard_derivatives\" not available. Advanced anti-aliasing is not possible. Using linear anti-aliasing instead.");
+	        gameSettings.antiAlias = -1;
+	*/
+	Fragment = shaderFileRead("scale_noaa.frag");
+//	}
+
+	Fragment = joinStrings("precision mediump float;\n", Fragment);
+#endif
+
+	if (! Vertex || ! Fragment) {
+		fatal("Error loading \"scale\" shader program!", "Try re-installing the game. (scale.frag, scale_noaa.frag or scale.vert was not found.)");
+		gameSettings.antiAlias = -1;
+		shader.smartScaler = 0;
+	} else {
+
+		shader.smartScaler = buildShaders(Vertex, Fragment);
+
+		if (! shader.smartScaler) {
+			fatal("Error building \"scale\" shader program!");
+			gameSettings.antiAlias = -1;
+			shader.smartScaler = 0;
+		} else {
+			debugOut("Built shader program: %d (smartScaler)\n", shader.smartScaler);
+
+			glUseProgram(shader.smartScaler);
+			uniform = glGetUniformLocation(shader.smartScaler, "Texture");
+			if (uniform >= 0) glUniform1i(uniform, 0);
+			uniform = glGetUniformLocation(shader.smartScaler, "lightTexture");
+			if (uniform >= 0) glUniform1i(uniform, 1);
+			uniform = glGetUniformLocation(shader.smartScaler, "useLightTexture");
+			if (uniform >= 0) glUniform1i(uniform, 0);
+			uniform = glGetUniformLocation(shader.smartScaler, "antialias");
+			if (uniform >= 0) glUniform1i(uniform, 0);
+			uniform = glGetUniformLocation(shader.smartScaler, "scale");
+
+			float scale = (float)realWinWidth / (float)winWidth * 0.25;
+			if (scale > 1.0) scale = 1.0;
+			if (uniform >= 0) glUniform1f(uniform, scale);
+
+		}
+	}
+
+	Vertex = shaderFileRead("fixScaleSprite.vert");
+	Fragment = shaderFileRead("fixScaleSprite.frag");
+
+#if defined(HAVE_GLES2)
+	Fragment = joinStrings("precision mediump float;\n", Fragment);
+#endif
+
+	if (! Vertex || ! Fragment) {
+		fatal("Error loading \"fixScaleSprite\" shader program!", "Try re-installing the game. (fixScaleSprite.frag or fixScaleSprite.vert was not found.)");
+		shader.paste = 0;
+	} else {
+
+		shader.paste = buildShaders(Vertex, Fragment);
+		if (! shader.paste) {
+			fatal("Error building \"fixScaleSprite\" shader program!");
+		} else {
+			debugOut("Built shader program: %d (fixScaleSprite)\n", shader.paste);
+
+			glUseProgram(shader.paste);
+			uniform = glGetUniformLocation(shader.paste, "tex0");
+			if (uniform >= 0) glUniform1i(uniform, 0);
+			uniform = glGetUniformLocation(shader.paste, "tex1");
+			if (uniform >= 0) glUniform1i(uniform, 1);
+			uniform = glGetUniformLocation(shader.paste, "tex2");
+			if (uniform >= 0) glUniform1i(uniform, 2);
+			uniform = glGetUniformLocation(shader.paste, "useLightTexture");
+			if (uniform >= 0) glUniform1i(uniform, 0);
+
+		}
+	}
+
+	Vertex = shaderFileRead("yuv.vert");
+	Fragment = shaderFileRead("yuv.frag");
+
+#if defined(HAVE_GLES2)
+	Fragment = joinStrings("precision mediump float;\n", Fragment);
+#endif
+
+	if (! Vertex || ! Fragment) {
+		fatal("Error loading \"yuv\" shader program!", "Try re-installing the game. (yuv.frag or yuv.vert was not found.)");
+		shader.yuv = 0;
+	} else {
+
+		shader.yuv = buildShaders(Vertex, Fragment);
+		if (! shader.yuv) {
+			fatal("Error building \"yuv\" shader program!");
+		} else {
+			debugOut("Built shader program: %d (yuv)\n", shader.yuv);
+
+			glUseProgram(shader.yuv);
+			uniform = glGetUniformLocation(shader.yuv, "Ytex");
+			if (uniform >= 0) glUniform1i(uniform, 0);
+			uniform = glGetUniformLocation(shader.yuv, "Utex");
+			if (uniform >= 0) glUniform1i(uniform, 1);
+			uniform = glGetUniformLocation(shader.yuv, "Vtex");
+			if (uniform >= 0) glUniform1i(uniform, 2);
+
+		}
+	}
+
+	Vertex = shaderFileRead("texture.vert");
+	Fragment = shaderFileRead("texture.frag");
+
+#if defined(HAVE_GLES2)
+	Fragment = joinStrings("precision mediump float;\n", Fragment);
+#endif
+
+	if (! Vertex || ! Fragment) {
+		fatal("Error loading \"texture\" shader program!", "Try re-installing the game. (texture.frag or texture.vert was not found.)");
+		shader.texture = 0;
+	} else {
+
+		shader.texture = buildShaders(Vertex, Fragment);
+		if (! shader.texture) {
+			fatal("Error building \"texture\" shader program!");
+		} else {
+			debugOut("Built shader program: %d (texture)\n", shader.texture);
+
+			glUseProgram(shader.texture);
+			uniform = glGetUniformLocation(shader.texture, "sampler2d");
+			if (uniform >= 0) glUniform1i(uniform, 0);
+			uniform = glGetUniformLocation(shader.texture, "zBuffer");
+			if (uniform >= 0) glUniform1i(uniform, 0);
+			uniform = glGetUniformLocation(shader.texture, "zBufferLayer");
+			if (uniform >= 0) glUniform1f(uniform, 0.);
+			uniform = glGetUniformLocation(shader.texture, "modulateColor");
+			if (uniform >= 0) glUniform1i(uniform, 0);
+		}
+	}
+
+	Vertex = shaderFileRead("color.vert");
+	Fragment = shaderFileRead("color.frag");
+
+#if defined(HAVE_GLES2)
+	Fragment = joinStrings("precision mediump float;\n", Fragment);
+#endif
+
+	if (! Vertex || ! Fragment) {
+		fatal("Error loading \"color\" shader program!", "Try re-installing the game. (color.frag or color.vert was not found.)");
+		shader.color = 0;
+	} else {
+
+		shader.color = buildShaders(Vertex, Fragment);
+		if (! shader.color) {
+			fatal("Error building \"color\" shader program!");
+		} else {
+			debugOut("Built shader program: %d (color)\n", shader.color);
+			glUseProgram(shader.color);
+		}
+	}
+	glUseProgram(0);
+
+	glViewport(viewportOffsetX, viewportOffsetY, viewportWidth, viewportHeight);
+
+	/*
+	 * Set up OpenGL for 2D rendering.
+	 */
+	glDisable(GL_DEPTH_TEST);
+	glDisable(GL_CULL_FACE);
+	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+	setPixelCoords(false);
+
+	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
+	if (restoreGraphics) {
+		/*
+		 * Restore the textures
+		 */
+		if (backdropTextureName) {
+			if (!glIsTexture(backdropTextureName)) {
+				glGenTextures(1, &backdropTextureName);
+			}
+			glBindTexture(GL_TEXTURE_2D, backdropTextureName);
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+
+			if (gameSettings.antiAlias < 0) {
+				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+			} else {
+				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+			}
+			// Restore the backdrop
+			texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, sceneWidth, sceneHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, backdropTexture, backdropTextureName);
+
+		}
+		if (snapshotTextureName) {
+			if (!glIsTexture(snapshotTextureName)) {
+				glGenTextures(1, &snapshotTextureName);
+			}
+			glBindTexture(GL_TEXTURE_2D, snapshotTextureName);
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+
+			// Restore the backdrop
+			texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, winWidth, winHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, snapTexture, snapshotTextureName);
+			delete snapTexture;
+		}
+
+		if (yTextureName) {
+			if (!glIsTexture(yTextureName)) {
+				glGenTextures(1, &yTextureName);
+				glGenTextures(1, &uTextureName);
+				glGenTextures(1, &vTextureName);
+			}
+		}
+
+
+		reloadSpriteTextures();
+		reloadParallaxTextures();
+		zBuffer.texName = 0;
+		if (zBuffer.numPanels) {
+			setZBuffer(zBuffer.originalNum);
+		}
+		lightMap.name = 0;
+		if (lightMapNumber) {
+			loadLightMap(lightMapNumber);
+		}
+
+		sludgeDisplay();
+	}
+
+	if (movieIsPlaying)
+		setMovieViewport();
+#endif
+}
+
+void setupOpenGLStuff() {
+
+	/*
+	 * Time to setup our requested window attributes for our OpenGL window.
+	 * We want *at least* 8 bits of red, green and blue. We also want at least a 16-bit
+	 * depth buffer.
+	 *
+	 * The last thing we do is request a double buffered window. '1' turns on double
+	 * buffering, '0' turns it off.
+	 */
+#if 0
+	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
+	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
+	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
+	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
+	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
+	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
+#endif
+	setGraphicsWindow(gameSettings.userFullScreen, false);
+
+#if !defined(HAVE_GLES2)
+#if 0
+	/* Check for graphics capabilities... */
+	if (GLEE_VERSION_2_0) {
+		// Yes! Textures can be any size!
+		NPOT_textures = true;
+		debugOut("OpenGL 2.0! All is good.\n");
+	} else {
+		if (GLEE_VERSION_1_5) {
+			debugOut("OpenGL 1.5!\n");
+		} else if (GLEE_VERSION_1_4) {
+			debugOut("OpenGL 1.4!\n");
+		} else if (GLEE_VERSION_1_3) {
+			debugOut("OpenGL 1.3!\n");
+		} else if (GLEE_VERSION_1_2) {
+			debugOut("OpenGL 1.2!\n");
+		}
+
+		if (GLEE_ARB_texture_non_power_of_two) {
+			// Yes! Textures can be any size!
+			NPOT_textures = true;
+		} else {
+			// Workaround needed for lesser graphics cards. Let's hope this works...
+			NPOT_textures = false;
+			debugOut("Warning: Old graphics card! GLEE_ARB_texture_non_power_of_two not supported.\n");
+		}
+
+		if (GLEE_ARB_shading_language_100) {
+			debugOut("ARB_shading_language_100 supported.\n");
+		} else {
+			debugOut("Warning: Old graphics card! ARB_shading_language_100 not supported. Try updating your drivers.\n");
+		}
+		if (GLEE_ARB_shader_objects) {
+			debugOut("ARB_shader_objects supported.\n");
+		} else {
+			fatal("Error: Old graphics card! ARB_shader_objects not supported.\n");
+		}
+		if (GLEE_ARB_vertex_shader) {
+			debugOut("ARB_vertex_shader supported.\n");
+		} else {
+			fatal("Error: Old graphics card! ARB_vertex_shader not supported.\n");
+		}
+		if (GLEE_ARB_fragment_shader) {
+			debugOut("ARB_fragment_shader supported.\n");
+		} else {
+			fatal("Error: Old graphics card! ARB_fragment_shader not supported.\n");
+		}
+	}
+#else
+	NPOT_textures = false;
+#endif
+#endif
+	int n;
+#if 0
+	glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, (GLint *) &n);
+#endif
+	debugOut("Max texture image units: %d\n", n);
+
+}
+
+
+// I found this function on a coding forum on the 'net.
+// Looks a bit weird, but it should work.
+int getNextPOT(int n) {
+	--n;
+	n |= n >> 16;
+	n |= n >> 8;
+	n |= n >> 4;
+	n |= n >> 2;
+	n |= n >> 1;
+	++n;
+	return n;
+}
+
+int printOglError(const char *file, int line) {
+	/* Returns 1 if an OpenGL error occurred, 0 otherwise. */
+	int retCode = 0;
+#if 0
+	GLenum glErr;
+
+	glErr = glGetError();
+	while (glErr != GL_NO_ERROR) {
+#if !defined(HAVE_GLES2)
+		debugOut("glError in file %s @ line %d: %s\n", file, line, gluErrorString(glErr));
+#else
+		debugOut("glError in file %s @ line %d: error code %i\n", file, line, glErr);
+#endif
+		retCode = 1;
+		glErr = glGetError();
+	}
+#endif
+	return retCode;
+}
diff --git a/engines/sludge/graphics.h b/engines/sludge/graphics.h
new file mode 100644
index 0000000..ca95307
--- /dev/null
+++ b/engines/sludge/graphics.h
@@ -0,0 +1,118 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#ifndef SLUDGE_GRAPHICS_H
+#define SLUDGE_GRAPHICS_H
+
+#if 0
+#if !defined(HAVE_GLES2)
+#include "GLee.h"
+#else
+#include <GLES2/gl2.h>
+#include "eglport/eglport.h"
+#endif
+#endif
+
+
+struct texture {
+#if 0
+	GLubyte *data;
+	GLuint name;
+#endif
+	int w, h;
+	double texW, texH;
+};
+
+#if 0
+struct shaders {
+	GLuint paste;
+	GLuint smartScaler;
+	GLuint yuv;
+	GLuint texture;
+	GLuint color;
+};
+#endif
+
+struct textureList {
+#if 0
+	GLuint name;
+	GLsizei width;
+	GLsizei height;
+#endif
+	struct textureList *next;
+};
+
+#if 0
+// From Backdrop.cpp, but they're here anyway
+extern GLubyte *backdropTexture;
+extern GLfloat backdropTexW, backdropTexH;
+#endif
+
+extern unsigned int winWidth, winHeight;
+extern int viewportHeight, viewportWidth;
+extern int viewportOffsetX, viewportOffsetY;
+extern int realWinWidth, realWinHeight;
+
+extern bool NPOT_textures;
+
+#if 0
+extern shaders shader;
+extern GLfloat aPMVMatrix[];
+
+void setPrimaryColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a);
+void setSecondaryColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a);
+
+void drawQuad(GLint program, const GLfloat *vertices, int numTexCoords, ...);
+
+void setPMVMatrix(GLint program);
+#endif
+
+void setPixelCoords(bool pixels);
+void setGraphicsWindow(bool fullscreen, bool restoreGraphics = true, bool resize = false);
+
+void setupOpenGLStuff();
+
+int getNextPOT(int n);
+
+#if 0
+void saveTexture(GLuint tex, GLubyte *data);
+
+void dcopyTexImage2D(GLenum target,  GLint level,  GLenum internalformat,  GLint x,  GLint y,  GLsizei width,  GLsizei height,  GLint border, GLuint name, const char *file, int line);
+void dcopyTexSubImage2D(GLenum target,  GLint level,  GLint xoffset,  GLint yoffset,  GLint x,  GLint y,  GLsizei width,  GLsizei height, GLuint name, const char *file, int line);
+void dtexImage2D(GLenum target,  GLint level,  GLint internalformat,  GLsizei width,  GLsizei height,  GLint border,  GLenum format,  GLenum type,  const GLvoid *data, GLuint name, const char *file, int line);
+void dtexSubImage2D(GLenum target,  GLint level,  GLint xoffset,  GLint yoffset,  GLsizei width,  GLsizei height,  GLenum format,  GLenum type,  const GLvoid *data, GLuint name, const char *file, int line);
+
+#define copyTexImage2D(target, level, internalformat, x, y,  width, height, border, name) dcopyTexImage2D(target,  level,  internalformat,  x,  y,  width,height, border, name, __FILE__, __LINE__)
+
+#define copyTexSubImage2D(target,  level,  xoffset,yoffset, x,  y,   width,   height, name) dcopyTexSubImage2D(target,  level,  xoffset,  yoffset,  x,  y,   width,  height, name, __FILE__, __LINE__)
+
+#define texImage2D(target,  level,  internalformat,  width,  height,  border,  format, type,  data,name) dtexImage2D( target,   level,  internalformat, width, height, border,  format,  type,  data, name, __FILE__, __LINE__)
+
+#define texSubImage2D( target,  level,   xoffset,   yoffset,   width,  height, format,  type,   data,name) dtexSubImage2D( target, level,   xoffset,  yoffset,  width,  height, format,  type,  data,  name, __FILE__, __LINE__)
+
+void deleteTextures(GLsizei n,  const GLuint *textures);
+
+void getTextureDimensions(GLuint name, GLint *width,  GLint *height);
+
+int printOglError(const char *file, int         line);
+#define printOpenGLError() printOglError(__FILE__, __LINE__)
+#endif
+#endif
diff --git a/engines/sludge/helpers.cpp b/engines/sludge/helpers.cpp
new file mode 100644
index 0000000..f25f878
--- /dev/null
+++ b/engines/sludge/helpers.cpp
@@ -0,0 +1,36 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#include "allfiles.h"
+#include "helpers.h"
+
+bool fileExists(const char *file) {
+	bool retval = false;
+#if ALLOW_FILE
+	FILE *tester;
+	tester = fopen(file, "rb");
+	if (tester) {
+		retval = true;
+		fclose(tester);
+	}
+#endif
+	return retval;
+}
diff --git a/engines/sludge/helpers.h b/engines/sludge/helpers.h
new file mode 100644
index 0000000..82d8e40
--- /dev/null
+++ b/engines/sludge/helpers.h
@@ -0,0 +1,27 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#ifndef SLUDGE_HELPERS_H
+#define SLUDGE_HELPERS_H
+
+bool fileExists(const char *file);
+
+#endif
diff --git a/engines/sludge/language.cpp b/engines/sludge/language.cpp
new file mode 100644
index 0000000..3a95661
--- /dev/null
+++ b/engines/sludge/language.cpp
@@ -0,0 +1,210 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#include <stdio.h>
+#include <string.h>
+#include "stringy.h"
+#include "newfatal.h"
+#include "moreio.h"
+#include "language.h"
+#include "CommonCode/version.h"
+#include "platform-dependent.h"
+
+int *languageTable;
+char **languageName;
+settingsStruct gameSettings;
+
+unsigned int stringToInt(char *s) {
+	int i = 0;
+	bool negative = false;
+	for (;;) {
+		if (*s >= '0' && *s <= '9') {
+			i *= 10;
+			i += *s - '0';
+			s ++;
+		} else if (*s == '-') {
+			negative = ! negative;
+			s++;
+		} else {
+			if (negative)
+				return -i;
+			return i;
+		}
+	}
+}
+
+
+char *getPrefsFilename(char *filename) {
+	// Yes, this trashes the original string, but
+	// we also free it at the end (warning!)...
+
+	int n, i;
+
+	n = strlen(filename);
+
+	if (n > 4 && filename[n - 4] == '.') {
+		filename[n - 4] = 0;
+	}
+
+	char *f = filename;
+	for (i = 0; i < n; i++) {
+#ifdef _WIN32
+		if (filename[i] == '\\')
+#else
+		if (filename[i] == '/')
+#endif
+			f = filename + i + 1;
+	}
+
+	char *joined = joinStrings(f, ".ini");
+
+	delete filename;


Commit: c4a5af22eac930b5ed8e04fede2b9e61a76ca5d6
    https://github.com/scummvm/scummvm/commit/c4a5af22eac930b5ed8e04fede2b9e61a76ca5d6
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Add namespace

Changed paths:
    engines/sludge/allfiles.h
    engines/sludge/backdrop.cpp
    engines/sludge/backdrop.h
    engines/sludge/bg_effects.cpp
    engines/sludge/bg_effects.h
    engines/sludge/builtin.cpp
    engines/sludge/builtin.h
    engines/sludge/colours.h
    engines/sludge/csludge.h
    engines/sludge/cursors.cpp
    engines/sludge/cursors.h
    engines/sludge/debug.cpp
    engines/sludge/debug.h
    engines/sludge/errors.h
    engines/sludge/fileset.cpp
    engines/sludge/fileset.h
    engines/sludge/floor.cpp
    engines/sludge/floor.h
    engines/sludge/fonttext.cpp
    engines/sludge/fonttext.h
    engines/sludge/freeze.cpp
    engines/sludge/freeze.h
    engines/sludge/graphics.cpp
    engines/sludge/graphics.h
    engines/sludge/helpers.cpp
    engines/sludge/helpers.h
    engines/sludge/language.cpp
    engines/sludge/language.h
    engines/sludge/line.cpp
    engines/sludge/line.h
    engines/sludge/linuxstuff.cpp
    engines/sludge/linuxstuff.h
    engines/sludge/loadsave.cpp
    engines/sludge/loadsave.h
    engines/sludge/main_loop.cpp
    engines/sludge/main_loop.h
    engines/sludge/memwatch.cpp
    engines/sludge/memwatch.h
    engines/sludge/moreio.cpp
    engines/sludge/moreio.h
    engines/sludge/movie.cpp
    engines/sludge/movie.h
    engines/sludge/newfatal.cpp
    engines/sludge/newfatal.h
    engines/sludge/objtypes.cpp
    engines/sludge/objtypes.h
    engines/sludge/people.cpp
    engines/sludge/people.h
    engines/sludge/platform-dependent.h
    engines/sludge/region.cpp
    engines/sludge/region.h
    engines/sludge/savedata.cpp
    engines/sludge/savedata.h
    engines/sludge/shaders.cpp
    engines/sludge/shaders.h
    engines/sludge/sludge.cpp
    engines/sludge/sludge.h
    engines/sludge/sludger.cpp
    engines/sludge/sludger.h
    engines/sludge/sound.h
    engines/sludge/sound_bass.cpp
    engines/sludge/sound_nosound.cpp
    engines/sludge/sound_openal.cpp
    engines/sludge/sprbanks.cpp
    engines/sludge/sprbanks.h
    engines/sludge/sprites.cpp
    engines/sludge/sprites.h
    engines/sludge/statusba.cpp
    engines/sludge/statusba.h
    engines/sludge/stringy.cpp
    engines/sludge/stringy.h
    engines/sludge/talk.cpp
    engines/sludge/talk.h
    engines/sludge/thumbnail.cpp
    engines/sludge/thumbnail.h
    engines/sludge/timing.cpp
    engines/sludge/timing.h
    engines/sludge/transition.cpp
    engines/sludge/transition.h
    engines/sludge/variable.cpp
    engines/sludge/variable.h
    engines/sludge/vid.cpp
    engines/sludge/vid.h
    engines/sludge/winstuff.cpp
    engines/sludge/winstuff.h
    engines/sludge/zbuffer.cpp
    engines/sludge/zbuffer.h


diff --git a/engines/sludge/allfiles.h b/engines/sludge/allfiles.h
index 9478da5..a08df72 100644
--- a/engines/sludge/allfiles.h
+++ b/engines/sludge/allfiles.h
@@ -27,6 +27,11 @@
 
 //#define debuggy2 int
 #define IN_THE_CENTRE 65535
+
+namespace Sludge {
+
 typedef unsigned char byte;
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index ed71770..bb840b3 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -19,7 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-
 #if 0
 #if defined __unix__ && !(defined __APPLE__)
 #include <png.h>
@@ -54,11 +53,12 @@
 #include "talk.h"
 #include "sludger.h"
 #include "statusba.h"
-
+#include "variable.h"
 #include "CommonCode/version.h"
 
-extern inputType input;
+namespace Sludge {
 
+extern inputType input;
 
 bool freeze();
 void unfreeze(bool);    // Because FREEZE.H needs a load of other includes
@@ -96,7 +96,7 @@ void nosnapshot() {
 #endif
 }
 
-#if ALLOW_FILE
+#if 0
 void saveSnapshot(FILE *fp) {
 	if (snapshotTextureName) {
 		fputc(1, fp);               // 1 for snapshot follows
@@ -157,7 +157,7 @@ bool snapshot() {
 	return true;
 }
 
-#if ALLOW_FILE
+#if 0
 bool restoreSnapshot(FILE *fp) {
 	unsigned int picWidth = get2bytes(fp);
 	unsigned int picHeight = get2bytes(fp);
@@ -304,7 +304,7 @@ bool resizeBackdrop(int x, int y) {
 
 void loadBackDrop(int fileNum, int x, int y) {
 	setResourceForFatal(fileNum);
-#if ALLOW_FILE
+#if 0
 	if (! openFileFromNum(fileNum)) {
 		fatal("Can't load overlay image");
 		return;
@@ -322,7 +322,7 @@ void loadBackDrop(int fileNum, int x, int y) {
 }
 
 void mixBackDrop(int fileNum, int x, int y) {
-#if ALLOW_FILE
+#if 0
 	setResourceForFatal(fileNum);
 	if (! openFileFromNum(fileNum)) {
 		fatal("Can't load overlay image");
@@ -623,7 +623,7 @@ void drawBackDrop() {
 
 bool loadLightMap(int v) {
 	int newPicWidth, newPicHeight;
-#if ALLOW_FILE
+#if 0
 	setResourceForFatal(v);
 	if (! openFileFromNum(v)) return fatal("Can't open light map.");
 	long file_pointer = ftell(bigDataFile);
@@ -764,9 +764,9 @@ bool loadLightMap(int v) {
 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-#endif
-	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, newPicWidth, newPicHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, lightMap.data, lightMap.name);
 
+	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, newPicWidth, newPicHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, lightMap.data, lightMap.name);
+#endif
 	finishAccess();
 
 #endif
@@ -816,7 +816,7 @@ void reloadParallaxTextures() {
 
 bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY) {
 
-#if ALLOW_FILE
+#if 0
 	setResourceForFatal(v);
 	if (! openFileFromNum(v)) return fatal("Can't open parallax image");
 
@@ -1004,7 +1004,7 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 
 extern int viewportOffsetX, viewportOffsetY;
 
-#if ALLOW_FILE
+#if 0
 bool loadHSI(FILE *fp, int x, int y, bool reserve) {
 
 	int t1, t2, n;
@@ -1751,3 +1751,5 @@ bool getRGBIntoStack(unsigned int x, unsigned int y, stackHandler *sH) {
 #endif
 	return true;
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/backdrop.h b/engines/sludge/backdrop.h
index 97d3377..5dd2014 100644
--- a/engines/sludge/backdrop.h
+++ b/engines/sludge/backdrop.h
@@ -34,6 +34,8 @@
 #include "variable.h"
 #include "graphics.h"
 
+namespace Sludge {
+
 enum {
 	LIGHTMAPMODE_NONE       = -1,
 	LIGHTMAPMODE_HOTSPOT,
@@ -65,7 +67,7 @@ void mixBackDrop(int fileNum, int x, int y);
 void drawBackDrop();
 void blankScreen(int x1, int y1, int x2, int y2);
 void darkScreen();
-#if ALLOW_FILE
+#if 0
 void saveHSI(FILE *writer);
 void saveCoreHSI(FILE *writer, GLuint texture, int w, int h);
 bool loadHSI(FILE *fp, int, int, bool);
@@ -101,3 +103,5 @@ void saveSnapshot(FILE *fp);
 bool restoreSnapshot(FILE *fp);
 #endif
 #endif
+
+} // End of namespace Sludge
diff --git a/engines/sludge/bg_effects.cpp b/engines/sludge/bg_effects.cpp
index ad6438b..0a8550e 100644
--- a/engines/sludge/bg_effects.cpp
+++ b/engines/sludge/bg_effects.cpp
@@ -28,6 +28,8 @@
 #include "newfatal.h"
 #include "moreio.h"
 
+namespace Sludge {
+
 #if 0
 //extern unsigned short int * * backDropImage;
 extern GLuint backdropTextureName;
@@ -373,3 +375,5 @@ bool blurScreen() {
 #endif
 	return false;
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/bg_effects.h b/engines/sludge/bg_effects.h
index 067fa8d..d18fae6 100644
--- a/engines/sludge/bg_effects.h
+++ b/engines/sludge/bg_effects.h
@@ -23,6 +23,8 @@
 #ifndef SLUDGE_BG_EFFECTS_H
 #define SLUDGE_BG_EFFECTS_H
 
+namespace Sludge {
+
 bool blurScreen();
 #if ALLOW_FILE
 void blur_saveSettings(FILE *fp);
@@ -30,4 +32,6 @@ void blur_loadSettings(FILE *fp);
 #endif
 bool blur_createSettings(int numParams, variableStack *&stack);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 9ba633d..6f2660d 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -56,6 +56,8 @@
 #include "graphics.h"
 #include "CommonCode/utf8.h"
 
+namespace Sludge {
+
 extern char *gamePath;
 
 int speechMode = 0;
@@ -308,7 +310,7 @@ builtIn(fileExists) {
 	char *aaaaa = encodeFilename(loadNow);
 	delete loadNow;
 	if (failSecurityCheck(aaaaa)) return BR_ERROR;
-#if ALLOW_FILE
+#if 0
 	FILE *fp = fopen(aaaaa, "rb");
 	if (!fp) {
 		char currentDir[1000];
@@ -324,8 +326,10 @@ builtIn(fileExists) {
 			debugOut("Error: Failed changing to directory %s\n", currentDir);
 		}
 	}
+#endif
 	// Return value
-	setVariable(fun -> reg, SVT_INT, (fp != NULL));
+	setVariable(fun -> reg, SVT_INT, 0/*(fp != NULL)*/);//TODO:false value
+#if 0
 	if (fp) fclose(fp);
 	delete[] aaaaa;
 	loadNow = NULL;
@@ -2543,3 +2547,4 @@ builtReturn callBuiltIn(int whichFunc, int numParams, loadedFunction *fun) {
 	return BR_ERROR;
 }
 
+} // End of namespace Sludge
diff --git a/engines/sludge/builtin.h b/engines/sludge/builtin.h
index 8f5ac59..00d780e 100644
--- a/engines/sludge/builtin.h
+++ b/engines/sludge/builtin.h
@@ -23,9 +23,13 @@
 #ifndef SLUDGE_BUILTIN_H
 #define SLUDGE_BUILTIN_H
 
+namespace Sludge {
+
 enum builtReturn {BR_KEEP_AND_PAUSE, BR_ERROR, BR_CONTINUE, BR_PAUSE, BR_CALLAFUNC, BR_ALREADY_GONE};
 
 bool failSecurityCheck(char *fn);
 builtReturn callBuiltIn(int whichFunc, int numParams, loadedFunction *fun);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/colours.h b/engines/sludge/colours.h
index 503823f..2caf963 100644
--- a/engines/sludge/colours.h
+++ b/engines/sludge/colours.h
@@ -23,6 +23,8 @@
 #ifndef SLUDGE_COLOURS_H
 #define SLUDGE_COLOURS_H
 
+namespace Sludge {
+
 // Simple colour conversion routines to deal with 16-bit graphics
 //unsigned short int makeColour (byte r, byte g, byte b);
 
@@ -44,4 +46,6 @@ inline unsigned short makeColour(unsigned short int r, unsigned short int g, uns
 	return ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3);
 }
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/csludge.h b/engines/sludge/csludge.h
index 3c73a9d1..22b6125 100644
--- a/engines/sludge/csludge.h
+++ b/engines/sludge/csludge.h
@@ -23,6 +23,8 @@
 #ifndef SLUDGE_CSLUDGE_H
 #define SLUDGE_CSLUDGE_H
 
+namespace Sludge {
+
 enum sludgeCommand {SLU_UNKNOWN,
                     SLU_RETURN, SLU_BRANCH, SLU_BR_ZERO, SLU_SET_GLOBAL,
                     SLU_SET_LOCAL, SLU_LOAD_GLOBAL, SLU_LOAD_LOCAL,
@@ -40,4 +42,6 @@ enum sludgeCommand {SLU_UNKNOWN,
                     numSludgeCommands
                    };
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/cursors.cpp b/engines/sludge/cursors.cpp
index 6ad3a35..91d0112 100644
--- a/engines/sludge/cursors.cpp
+++ b/engines/sludge/cursors.cpp
@@ -36,6 +36,8 @@
 #include "people.h"
 #include "sludger.h"
 
+namespace Sludge {
+
 personaAnimation *mouseCursorAnim;
 int mouseCursorFrameNum = 0;
 int mouseCursorCountUp = 0;
@@ -84,3 +86,5 @@ void pasteCursor(int x, int y, personaAnimation *c) {
 		        c -> theSprites -> bank.sprites[c -> frames[0].frameNum],
 		        c -> theSprites -> bank.myPalette);
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/cursors.h b/engines/sludge/cursors.h
index 9c803fc..6a32665 100644
--- a/engines/sludge/cursors.h
+++ b/engines/sludge/cursors.h
@@ -23,8 +23,12 @@
 #ifndef SLUDGE_CURSORS_H
 #define SLUDGE_CURSORS_H
 
+namespace Sludge {
+
 void pickAnimCursor(struct personaAnimation *pp);
 void displayCursor();
 void pasteCursor(int x, int y, struct personaAnimation *c);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/debug.cpp b/engines/sludge/debug.cpp
index 222f411..3e256bd 100644
--- a/engines/sludge/debug.cpp
+++ b/engines/sludge/debug.cpp
@@ -28,13 +28,15 @@
 #include "debug.h"
 #include "language.h"
 
+namespace Sludge {
+
 void debugOut(const char *a, ...) {
 	if (! gameSettings.debugMode) return;
 
 	va_list argptr;
 	va_start(argptr, a);
 
-#if ALLOW_FILE
+#if 0
 #if defined __unix__ && !(defined __APPLE__)
 	vfprintf(stderr, a, argptr);
 #else
@@ -50,3 +52,5 @@ void debugOut(const char *a, ...) {
 void debugHeader() {
 	debugOut("*** Engine compiled " __DATE__ " at " __TIME__ ".\n");
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/debug.h b/engines/sludge/debug.h
index 94b6c34..aecff42 100644
--- a/engines/sludge/debug.h
+++ b/engines/sludge/debug.h
@@ -23,7 +23,11 @@
 #ifndef SLUDGE_DEDBUG_H
 #define SLUDGE_DEGBUG_H
 
+namespace Sludge {
+
 void debugOut(const char *a, ...);
 void debugHeader();
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/errors.h b/engines/sludge/errors.h
index 0c4716c..f706bad 100644
--- a/engines/sludge/errors.h
+++ b/engines/sludge/errors.h
@@ -23,6 +23,8 @@
 #ifndef SLUDGE_ERRRORS_H
 #define SLUDGE_ERRRORS_H
 
+namespace Sludge {
+
 #define _NO_MEMORY_GENERAL_         "\n\nTry closing down any programs you don't really need running (or freeing up a bit of disk space, which will give you more virtual memory - that should help too)."
 
 //---------------------------------------
@@ -69,4 +71,6 @@
 #define WARNING_BASS_WRONG_VERSION  "Incompatible version of BASS.DLL found!"
 #define WARNING_BASS_FAIL           "Can't initialise sound engine."
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/fileset.cpp b/engines/sludge/fileset.cpp
index 8d5eb52..852fd70 100644
--- a/engines/sludge/fileset.cpp
+++ b/engines/sludge/fileset.cpp
@@ -35,6 +35,7 @@
 #include "newfatal.h"
 #include "CommonCode/version.h"
 
+namespace Sludge {
 
 bool sliceBusy = true;
 #if ALLOW_FILE
@@ -235,3 +236,5 @@ void setFileIndices(FILE *fp, int numLanguages, unsigned int skipBefore) {
 	// Remember that the data section starts here
 	startOfDataIndex = ftell(fp);
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/fileset.h b/engines/sludge/fileset.h
index 39a6691..b83e47d 100644
--- a/engines/sludge/fileset.h
+++ b/engines/sludge/fileset.h
@@ -22,6 +22,8 @@
 #ifndef SLUDGE_FILESET_H
 #define SLUDGE_FILESET_H
 
+namespace Sludge {
+
 #if ALLOW_FILE
 extern FILE *bigDataFile;
 
@@ -36,4 +38,6 @@ char *getNumberedString(int value);
 bool startAccess();
 void finishAccess();
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/floor.cpp b/engines/sludge/floor.cpp
index 826632a..291961d 100644
--- a/engines/sludge/floor.cpp
+++ b/engines/sludge/floor.cpp
@@ -26,6 +26,8 @@
 #include "floor.h"
 #include "line.h"
 
+namespace Sludge {
+
 flor *currentFloor = NULL;
 
 bool pointInFloorPolygon(floorPolygon &floorPoly, int x, int y) {
@@ -288,3 +290,5 @@ bool closestPointOnLine(int &closestX, int &closestY, int x1, int y1, int x2, in
 	}
 	return false;
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/floor.h b/engines/sludge/floor.h
index 5c0d050..193b6d1 100644
--- a/engines/sludge/floor.h
+++ b/engines/sludge/floor.h
@@ -26,6 +26,8 @@
 #include "windef.h"
 #endif
 
+namespace Sludge {
+
 struct floorPolygon {
 	int numVertices;
 	int *vertexID;
@@ -54,4 +56,6 @@ int inFloor(int x, int y);
 bool getMatchingCorners(floorPolygon &, floorPolygon &, int &, int &);
 bool closestPointOnLine(int &closestX, int &closestY, int x1, int y1, int x2, int y2, int xP, int yP);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/fonttext.cpp b/engines/sludge/fonttext.cpp
index 835c2a6..6ac9209 100644
--- a/engines/sludge/fonttext.cpp
+++ b/engines/sludge/fonttext.cpp
@@ -36,6 +36,8 @@
 #include "newfatal.h"
 #include "moreio.h"
 
+namespace Sludge {
+
 spriteBank theFont;
 int fontHeight = 0, numFontColours, loadedFontNum;
 char *fontOrderString = NULL;
@@ -204,3 +206,5 @@ bool loadFont(int filenum, const char *charOrder, int h) {
 	fontHeight = h;
 	return true;
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/fonttext.h b/engines/sludge/fonttext.h
index f33876f..92520a0 100644
--- a/engines/sludge/fonttext.h
+++ b/engines/sludge/fonttext.h
@@ -22,6 +22,8 @@
 #ifndef SLUDGE_FONTTEXT_H
 #define SLUDGE_FONTTEXT_H
 
+namespace Sludge {
+
 bool loadFont(int filenum, const char *charOrder, int);
 void pasteString(char *theText, int, int, spritePalette &);
 void fixFont(spritePalette &spal);
@@ -32,4 +34,6 @@ void pasteStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal
 void burnStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal);
 bool isInFont(char *theText);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/freeze.cpp b/engines/sludge/freeze.cpp
index f245ad0..8435a9c 100644
--- a/engines/sludge/freeze.cpp
+++ b/engines/sludge/freeze.cpp
@@ -36,6 +36,8 @@
 #include "freeze.h"
 #include "zbuffer.h"
 
+namespace Sludge {
+
 extern onScreenPerson *allPeople;
 extern screenRegion *allScreenRegions;
 extern screenRegion *overRegion;
@@ -362,3 +364,5 @@ void unfreeze(bool killImage) {
 	killMe = NULL;
 
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/freeze.h b/engines/sludge/freeze.h
index 1682d3b..a9f5129 100644
--- a/engines/sludge/freeze.h
+++ b/engines/sludge/freeze.h
@@ -22,6 +22,7 @@
 #ifndef SLUDGE_FREEZE_H
 #define SLUDGE_FREEZE_H
 
+namespace Sludge {
 
 struct frozenStuffStruct {
 	onScreenPerson *allPeople;
@@ -52,4 +53,6 @@ bool freeze();
 void unfreeze(bool killImage = true);
 int howFrozen();
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/graphics.cpp b/engines/sludge/graphics.cpp
index 8bdc917..702865e 100644
--- a/engines/sludge/graphics.cpp
+++ b/engines/sludge/graphics.cpp
@@ -53,6 +53,8 @@
 #endif
 #endif
 
+namespace Sludge {
+
 unsigned int winWidth, winHeight;
 int viewportHeight, viewportWidth;
 int viewportOffsetX = 0, viewportOffsetY = 0;
@@ -954,3 +956,5 @@ int printOglError(const char *file, int line) {
 #endif
 	return retCode;
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/graphics.h b/engines/sludge/graphics.h
index ca95307..24b7671 100644
--- a/engines/sludge/graphics.h
+++ b/engines/sludge/graphics.h
@@ -31,6 +31,7 @@
 #endif
 #endif
 
+namespace Sludge {
 
 struct texture {
 #if 0
@@ -115,4 +116,7 @@ void getTextureDimensions(GLuint name, GLint *width,  GLint *height);
 int printOglError(const char *file, int         line);
 #define printOpenGLError() printOglError(__FILE__, __LINE__)
 #endif
+
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/helpers.cpp b/engines/sludge/helpers.cpp
index f25f878..30d5094 100644
--- a/engines/sludge/helpers.cpp
+++ b/engines/sludge/helpers.cpp
@@ -22,6 +22,8 @@
 #include "allfiles.h"
 #include "helpers.h"
 
+namespace Sludge {
+
 bool fileExists(const char *file) {
 	bool retval = false;
 #if ALLOW_FILE
@@ -34,3 +36,5 @@ bool fileExists(const char *file) {
 #endif
 	return retval;
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/helpers.h b/engines/sludge/helpers.h
index 82d8e40..27625d2 100644
--- a/engines/sludge/helpers.h
+++ b/engines/sludge/helpers.h
@@ -22,6 +22,10 @@
 #ifndef SLUDGE_HELPERS_H
 #define SLUDGE_HELPERS_H
 
+namespace Sludge {
+
 bool fileExists(const char *file);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/language.cpp b/engines/sludge/language.cpp
index 3a95661..a55adae 100644
--- a/engines/sludge/language.cpp
+++ b/engines/sludge/language.cpp
@@ -28,6 +28,8 @@
 #include "CommonCode/version.h"
 #include "platform-dependent.h"
 
+namespace Sludge {
+
 int *languageTable;
 char **languageName;
 settingsStruct gameSettings;
@@ -208,3 +210,5 @@ int getLanguageForFileB() {
 
 	return indexNum;
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/language.h b/engines/sludge/language.h
index fff3ef9..27faffb 100644
--- a/engines/sludge/language.h
+++ b/engines/sludge/language.h
@@ -22,6 +22,8 @@
 #ifndef LANGUAGE_H
 #define LANGUAGE_H
 
+namespace Sludge {
+
 struct settingsStruct {
 	unsigned int languageID;
 	unsigned int numLanguages;
@@ -43,4 +45,6 @@ int getLanguageForFileB();
 void makeLanguageTable(FILE *table);
 #endif
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/line.cpp b/engines/sludge/line.cpp
index f57bb64..bcb1343 100644
--- a/engines/sludge/line.cpp
+++ b/engines/sludge/line.cpp
@@ -26,6 +26,8 @@
 #include "graphics.h"
 #include "allfiles.h"
 
+namespace Sludge {
+
 extern int sceneWidth, sceneHeight;
 #if 0
 extern GLuint backdropTextureName;
@@ -141,3 +143,5 @@ void drawLine(int x1, int y1, int x2, int y2) {
 	setPixelCoords(false);
 #endif
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/line.h b/engines/sludge/line.h
index e7d00f0..49e895f 100644
--- a/engines/sludge/line.h
+++ b/engines/sludge/line.h
@@ -22,6 +22,10 @@
 #ifndef SLUDGE_LINE_H
 #define SLUDGE_LINE_H
 
+namespace Sludge {
+
 void drawLine(int x1, int y1, int x2, int y2);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/linuxstuff.cpp b/engines/sludge/linuxstuff.cpp
index d5b76a5..454cf93 100644
--- a/engines/sludge/linuxstuff.cpp
+++ b/engines/sludge/linuxstuff.cpp
@@ -35,6 +35,8 @@
 #include "debug.h"
 #include "helpers.h"
 
+namespace Sludge {
+
 extern settingsStruct gameSettings;
 cmdlineSettingsStruct cmdlineSettings;
 
@@ -222,4 +224,7 @@ uint32_t launch(char *filename) {
 bool defaultUserFullScreen() {
 	return false;
 }
+
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/linuxstuff.h b/engines/sludge/linuxstuff.h
index ba7344c..b97c7bf 100644
--- a/engines/sludge/linuxstuff.h
+++ b/engines/sludge/linuxstuff.h
@@ -22,6 +22,8 @@
 #ifndef SLUDGE_LINUXSTUFF_H
 #define SLUDGE_LINUXSTUFF_H
 
+namespace Sludge {
+
 struct cmdlineSettingsStruct {
 	bool languageSet;
 	unsigned int languageID;
@@ -37,4 +39,6 @@ struct cmdlineSettingsStruct {
 void printCmdlineUsage();
 bool parseCmdlineParameters(int argc, char *argv[]);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index 8641a67..2014095 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -41,6 +41,8 @@
 #include "fileset.h"
 #include "debug.h"
 
+namespace Sludge {
+
 //----------------------------------------------------------------------
 // From elsewhere
 //----------------------------------------------------------------------
@@ -91,7 +93,7 @@ stackLibrary *stackLib = NULL;
 //----------------------------------------------------------------------
 // For saving and loading stacks...
 //----------------------------------------------------------------------
-#if ALLOW_FILE
+#if 0
 bool saveVariable(variable *from, FILE *fp);
 bool loadVariable(variable *to, FILE *fp);
 
@@ -179,7 +181,7 @@ stackHandler *getStackFromLibrary(int n) {
 	}
 	return stackLib -> stack;
 }
-#if ALLOW_FILE
+#if 0
 stackHandler *loadStackRef(FILE *fp) {
 	stackHandler *nsh;
 
@@ -381,7 +383,7 @@ loadedFunction *loadFunction(FILE *fp) {
 //----------------------------------------------------------------------
 
 bool saveGame(char *fname) {
-#if ALLOW_FILE
+#if 0
 	int a;
 
 	FILE *fp = fopen(fname, "wb");
@@ -500,7 +502,7 @@ bool saveGame(char *fname) {
 int ssgVersion;
 
 bool loadGame(char *fname) {
-#if ALLOW_FILE
+#if 0
 	FILE *fp;
 	FILETIME savedGameTime;
 	int a;
@@ -676,3 +678,5 @@ bool loadGame(char *fname) {
 	clearStackLib();
 	return true;
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/loadsave.h b/engines/sludge/loadsave.h
index d2ce316..b91e872 100644
--- a/engines/sludge/loadsave.h
+++ b/engines/sludge/loadsave.h
@@ -22,6 +22,8 @@
 #ifndef SLUDGE_LOADSAVE_H
 #define SLUDGE_LOADSAVE_H
 
+namespace Sludge {
+
 bool saveGame(char *fname);
 bool loadGame(char *fname);
 
@@ -30,4 +32,6 @@ loadedFunction *loadFunction(FILE *fp);
 void saveFunction(loadedFunction *fun, FILE *fp);
 #endif
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index 0d807af..47bfe67 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -75,6 +75,7 @@
 #include "graphics.h"
 #include "helpers.h"
 
+namespace Sludge {
 
 #ifdef _WIN32
 #define PATHSLASH '\\'
@@ -506,3 +507,5 @@ catch (std::exception &ex) { //NOTE by reference, not value
 	return -2;
 }
 #endif
+
+} // End of namespace Sludge
diff --git a/engines/sludge/main_loop.h b/engines/sludge/main_loop.h
index 8fea28e..7ea5881 100644
--- a/engines/sludge/main_loop.h
+++ b/engines/sludge/main_loop.h
@@ -22,6 +22,10 @@
 #ifndef SLUDGE_MAIN_LOOP_H
 #define SLUDGE_MAIN_LOOP_H
 
+namespace Sludge {
+
 int main_loop(char *filename);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/memwatch.cpp b/engines/sludge/memwatch.cpp
index dab57b8..d316687 100644
--- a/engines/sludge/memwatch.cpp
+++ b/engines/sludge/memwatch.cpp
@@ -19,9 +19,10 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include <stdlib.h>
 #include "allfiles.h"
 
+namespace Sludge {
+
 void *allKnownMem[3000];
 int allKnownNum = 0;
 
@@ -59,3 +60,5 @@ void deleting(void *mem) {
 	//db ("Error! Deleted a block which hasn't been allocated!");
 	exit(1);
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/memwatch.h b/engines/sludge/memwatch.h
index 2325b2e..0fb6f26 100644
--- a/engines/sludge/memwatch.h
+++ b/engines/sludge/memwatch.h
@@ -22,7 +22,11 @@
 #ifndef SLUDGE_MEMWATCH_H
 #define SLUDGE_MEMWATCH_H
 
+namespace Sludge {
+
 void adding(void *);
 void deleting(void *);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/moreio.cpp b/engines/sludge/moreio.cpp
index 6df41fa..b8dc3f9 100644
--- a/engines/sludge/moreio.cpp
+++ b/engines/sludge/moreio.cpp
@@ -19,9 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include <string.h>
-#include <stdint.h>
-
 #include "allfiles.h"
 #include "moreio.h"
 #include "newfatal.h"
@@ -36,6 +33,8 @@
 #endif
 #endif
 
+namespace Sludge {
+
 bool allowAnyFilename = true;
 
 #if ALLOW_FILE
@@ -322,3 +321,5 @@ char *decodeFilename(char *nameIn) {
 		return copyString(nameIn);
 	}
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/moreio.h b/engines/sludge/moreio.h
index 9635ffa..5d107a8 100644
--- a/engines/sludge/moreio.h
+++ b/engines/sludge/moreio.h
@@ -24,6 +24,8 @@
 
 #include <stdint.h>
 
+namespace Sludge {
+
 #if ALLOW_FILE
 int get2bytes(FILE *fp);
 void put2bytes(int numtoput, FILE *fp);
@@ -39,4 +41,6 @@ void put4bytes(uint32_t f, FILE *fp);
 char *encodeFilename(char *nameIn);
 char *decodeFilename(char *nameIn);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/movie.cpp b/engines/sludge/movie.cpp
index debec5e..09693f1 100644
--- a/engines/sludge/movie.cpp
+++ b/engines/sludge/movie.cpp
@@ -55,6 +55,8 @@
 #include "AL/alure.h"
 #endif
 
+namespace Sludge {
+
 extern int specialSettings;
 
 // in main.c
@@ -1041,3 +1043,5 @@ int pauseMovie() {
 #endif
 	return movieIsPlaying;
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/movie.h b/engines/sludge/movie.h
index 460edb6..100439a 100644
--- a/engines/sludge/movie.h
+++ b/engines/sludge/movie.h
@@ -21,6 +21,9 @@
  */
 #ifndef SLUDGE_MOVIE_H
 #define SLUDGE_MOVIE_H
+
+namespace Sludge {
+
 /*
  movieIsPlaying tracks the state of movie playing
  */
@@ -35,4 +38,6 @@ int playMovie(int fileNumber);
 int stopMovie();
 int pauseMovie();
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/newfatal.cpp b/engines/sludge/newfatal.cpp
index b3fa74a..f05de5c 100644
--- a/engines/sludge/newfatal.cpp
+++ b/engines/sludge/newfatal.cpp
@@ -26,18 +26,18 @@
 #include <stdlib.h>
 #endif
 
-#include "common/debug.h"
+#include "allfiles.h"
 
+#include "common/debug.h"
 #include "platform-dependent.h"
-#include "allfiles.h"
 #include "CommonCode/version.h"
-
 #include "sound.h"
-
 #include "stringy.h"
 #include "errors.h"
 #include "graphics.h"
 
+namespace Sludge {
+
 const char emergencyMemoryMessage[] = "Out of memory displaying error message!";
 
 static char *fatalMessage = NULL;
@@ -85,7 +85,7 @@ extern SDL_Event quit_event;
 #endif
 
 int inFatal(const char *str) {
-#if ALLOW_FILE
+#if 0
 	FILE *fatFile = fopen("fatal.txt", "wt");
 	if (fatFile) {
 		fprintf(fatFile, "FATAL:\n%s\n", str);
@@ -156,3 +156,5 @@ int fatal(const char *str1, const char *str2) {
 	} else fatal(emergencyMemoryMessage);
 	return 0;
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/newfatal.h b/engines/sludge/newfatal.h
index 6fd5b2f..a97dca8 100644
--- a/engines/sludge/newfatal.h
+++ b/engines/sludge/newfatal.h
@@ -24,6 +24,8 @@
 
 #include "errors.h"
 
+namespace Sludge {
+
 bool hasFatal();
 
 int fatal(const char *str);
@@ -36,4 +38,6 @@ void warning(const char *l);
 void setResourceForFatal(int n);
 char *resourceNameFromNum(int i);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/objtypes.cpp b/engines/sludge/objtypes.cpp
index 7f19ee7..58572b0 100644
--- a/engines/sludge/objtypes.cpp
+++ b/engines/sludge/objtypes.cpp
@@ -27,6 +27,8 @@
 #include "fileset.h"
 #include "CommonCode/version.h"
 
+namespace Sludge {
+
 objectType *allObjectTypes = NULL;
 extern char *outputDir;
 
@@ -175,3 +177,5 @@ void removeObjectType(objectType *oT) {
 	}
 	fatal("Can't delete object type: bad pointer");
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/objtypes.h b/engines/sludge/objtypes.h
index b56b112..f61c845 100644
--- a/engines/sludge/objtypes.h
+++ b/engines/sludge/objtypes.h
@@ -22,6 +22,8 @@
 #ifndef SLUDGE_OBJTYPES_H
 #define SLUDGE_OBJTYPES_H
 
+namespace Sludge {
+
 struct combination {
 	int withObj, funcNum;
 };
@@ -46,4 +48,7 @@ void removeObjectType(objectType *oT);
 void saveObjectRef(objectType *r, FILE *fp);
 objectType *loadObjectRef(FILE *fp);
 #endif
+
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index 3853bbe..f54b1ff 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -45,6 +45,8 @@
 #define ANI_WALK 1
 #define ANI_TALK 2
 
+namespace Sludge {
+
 extern speechStruct *speech;
 
 extern variableStack *noStack;
@@ -1175,3 +1177,5 @@ bool loadPeople(FILE *fp) {
 	return true;
 }
 #endif
+
+} // End of namespace Sludge
diff --git a/engines/sludge/people.h b/engines/sludge/people.h
index fbc8fd7..11cf10b 100644
--- a/engines/sludge/people.h
+++ b/engines/sludge/people.h
@@ -22,6 +22,8 @@
 #ifndef SLUDGE_PEOPLE_H
 #define SLUDGE_PEOPLE_H
 
+namespace Sludge {
+
 struct animFrame {
 	int frameNum, howMany;
 	int noise;
@@ -131,4 +133,7 @@ bool loadPeople(FILE *fp);
 bool saveCostume(persona *cossy, FILE *fp);
 bool loadCostume(persona *cossy, FILE *fp);
 #endif
+
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/platform-dependent.h b/engines/sludge/platform-dependent.h
index 973e20f..5754ef5 100644
--- a/engines/sludge/platform-dependent.h
+++ b/engines/sludge/platform-dependent.h
@@ -26,6 +26,8 @@
  */
 #include <stdint.h>
 
+namespace Sludge {
+
 char *grabFileName();
 int showSetupWindow();
 
@@ -37,4 +39,6 @@ uint32_t launch(char *filename);
 
 bool defaultUserFullScreen();
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/region.cpp b/engines/sludge/region.cpp
index 3cd7164..8c55ece 100644
--- a/engines/sludge/region.cpp
+++ b/engines/sludge/region.cpp
@@ -27,6 +27,8 @@
 #include "moreio.h"
 #include "backdrop.h"
 
+namespace Sludge {
+
 screenRegion *allScreenRegions = NULL;
 screenRegion *overRegion = NULL;
 extern inputType input;
@@ -162,3 +164,5 @@ screenRegion *getRegionForObject(int obj) {
 
 	return NULL;
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/region.h b/engines/sludge/region.h
index 4c4843f..52c1c58 100644
--- a/engines/sludge/region.h
+++ b/engines/sludge/region.h
@@ -22,6 +22,8 @@
 #ifndef SLUDGE_REGION_H
 #define SLUDGE_REGION_H
 
+namespace Sludge {
+
 struct screenRegion {
 	int x1, y1, x2, y2, sX, sY, di;
 	objectType *thisType;
@@ -39,4 +41,6 @@ void saveRegions(FILE *);
 #endif
 void showBoxes();
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/savedata.cpp b/engines/sludge/savedata.cpp
index e8075cc..79e672b 100644
--- a/engines/sludge/savedata.cpp
+++ b/engines/sludge/savedata.cpp
@@ -31,6 +31,8 @@
 
 #define LOAD_ERROR "Can't load custom data...\n\n"
 
+namespace Sludge {
+
 unsigned short saveEncoding = false;
 char encode1 = 0;
 char encode2 = 0;
@@ -266,3 +268,5 @@ bool stackToFile(char *filename, const variable &from) {
 #endif
 	return true;
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/savedata.h b/engines/sludge/savedata.h
index 19821cc..e6422b8 100644
--- a/engines/sludge/savedata.h
+++ b/engines/sludge/savedata.h
@@ -22,7 +22,11 @@
 #ifndef SLUDGE_SAVEDATA_H
 #define SLUDGE_SAVEDATA_H
 
+namespace Sludge {
+
 bool fileToStack(char *filename, stackHandler *sH);
 bool stackToFile(char *filename, const variable &from);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/shaders.cpp b/engines/sludge/shaders.cpp
index fd4ca30..e11a834 100644
--- a/engines/sludge/shaders.cpp
+++ b/engines/sludge/shaders.cpp
@@ -19,14 +19,14 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include <stdio.h>
-#include <stdlib.h>
-
+#include "allfiles.h"
 #include "debug.h"
 #include "stringy.h"
 #include "shaders.h"
 #include "graphics.h"
 
+namespace Sludge {
+
 extern char *bundleFolder;
 
 //Function from: http://www.evl.uic.edu/aej/594/code/ogl.cpp
@@ -175,4 +175,4 @@ int buildShaders(const char *vertexShader, const char *fragmentShader) {
 	return prog;
 }
 
-
+} // End of namespace Sludge
diff --git a/engines/sludge/shaders.h b/engines/sludge/shaders.h
index f62808b..13b6e37 100644
--- a/engines/sludge/shaders.h
+++ b/engines/sludge/shaders.h
@@ -30,8 +30,12 @@
 #endif
 #endif
 
+namespace Sludge {
+
 char *shaderFileRead(const char *fn);
 int buildShaders(const char *vertexShader, const char *fragmentShader);
 
+} // End of namespace Sludge
+
 #endif
 
diff --git a/engines/sludge/sludge.cpp b/engines/sludge/sludge.cpp
index 12d0bbf..0301d73 100644
--- a/engines/sludge/sludge.cpp
+++ b/engines/sludge/sludge.cpp
@@ -41,6 +41,7 @@ SludgeEngine::SludgeEngine(OSystem *syst, const SludgeGameDescription *gameDesc)
 
 	// Add debug channels
 	DebugMan.addDebugChannel(kSludgeDebugScript, "Script", "Script debug level");
+	DebugMan.addDebugChannel(kSludgeDebugDataLoad, "DataLoad", "Data loading debug level");
 
 	// check init
 	debug("SludgeEngine::SludgeEngine");
diff --git a/engines/sludge/sludge.h b/engines/sludge/sludge.h
index 5fe7c9a..7878518 100644
--- a/engines/sludge/sludge.h
+++ b/engines/sludge/sludge.h
@@ -37,7 +37,8 @@ struct SludgeGameDescription;
 
 // debug channels
 enum {
-	kSludgeDebugScript = 1 << 0
+	kSludgeDebugScript = 1 << 0,
+	kSludgeDebugDataLoad = 1 << 1,
 };
  
 class SludgeEngine : public Engine {
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index d73c128..02a27f1 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -62,9 +62,11 @@
 #include "language.h"
 #include "CommonCode/specialsettings.h"
 #include "graphics.h"
+#include "variable.h"
+#include "common/debug.h"
+#include "sludge.h"
 
-#include "debug.h"
-
+namespace Sludge {
 
 extern personaAnimation *mouseCursorAnim;
 extern spritePalette pastePalette;
@@ -165,7 +167,7 @@ FILE *openAndVerify(char *filename, char extra1, char extra2, const char *er, in
 	}
 	char c;
 	c = fgetc(fp);
-	putchar(c);
+	debug(c);
 	while (c = fgetc(fp)) {
 		putchar(c);
 	}
@@ -264,19 +266,21 @@ bool initSludge(char *filename) {
 	}
 
 	char *checker = readString(fp);
-	printf("checker : %s\n", checker);
+	debug(kSludgeDebugDataLoad, "checker : %s\n", checker);
 
 	if (strcmp(checker, "okSoFar")) return fatal(ERROR_BAD_HEADER, filename);
 	delete checker;
 	checker = NULL;
 
 	unsigned char customIconLogo = fgetc(fp);
-	putchar(customIconLogo);
+	kSludgeDebugDataLoad(kSludgeDebugDataLoad, "Game icon: %i", customIconLogo);
 
 	if (customIconLogo & 1) {
 		// There is an icon - read it!
-		int n;
+		debug(kSludgeDebugDataLoad, "There is an icon - read it!");
 
+#if 0
+		int n;
 		long file_pointer = ftell(fp);
 
 		png_structp png_ptr;
@@ -378,10 +382,12 @@ bool initSludge(char *filename) {
 				}
 			}
 		}
+#endif
 	}
 
 	if (customIconLogo & 2) {
 		// There is an logo - read it!
+		debug(kSludgeDebugDataLoad, "There is an logo - read it!");
 		int n;
 
 		long file_pointer = ftell(fp);
@@ -519,7 +525,7 @@ bool initSludge(char *filename) {
 	delete gameNameOrig;
 
 	changeToUserDir();
-
+#if 0
 #ifdef _WIN32
 	mkdir(gameName);
 #else
@@ -527,7 +533,7 @@ bool initSludge(char *filename) {
 #endif
 
 	if (chdir(gameName)) return fatal("This game's preference folder is inaccessible!\nI can't access the following directory (maybe there's a file with the same name, or maybe it's read-protected):", gameName);
-
+#endif
 	delete [] gameName;
 
 	// Get user settings
@@ -552,6 +558,7 @@ bool initSludge(char *filename) {
 
 	if (dataFol[0]) {
 		char *dataFolder = encodeFilename(dataFol);
+#if 0
 #ifdef _WIN32
 		mkdir(dataFolder);
 #else
@@ -559,7 +566,7 @@ bool initSludge(char *filename) {
 #endif
 
 		if (chdir(dataFolder)) return fatal("This game's data folder is inaccessible!\nI can't access the following directory (maybe there's a file with the same name, or maybe it's read-protected):", dataFolder);
-
+#endif
 		delete dataFolder;
 	}
 
@@ -1561,3 +1568,5 @@ bool handleInput() {
 	lastRegion = overRegion;
 	return runSludge();
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/sludger.h b/engines/sludge/sludger.h
index fb9734a..ff24b24 100644
--- a/engines/sludge/sludger.h
+++ b/engines/sludge/sludger.h
@@ -24,10 +24,13 @@
 
 #include <stdint.h>
 
+#include "allfiles.h"
 #include "variable.h"
 #include "csludge.h"
 #include "language.h"
 
+namespace Sludge {
+
 #ifndef _WIN32
 typedef struct _FILETIME {
 	uint32_t dwLowDateTime;
@@ -35,6 +38,8 @@ typedef struct _FILETIME {
 } FILETIME;
 #endif
 
+struct variable;
+struct variableStack;
 
 struct eventHandlers {
 	int leftMouseFunction;
@@ -47,8 +52,8 @@ struct eventHandlers {
 };
 
 struct lineOfCode {
-	sludgeCommand               theCommand;
-	int32_t                     param;
+	sludgeCommand theCommand;
+	int32_t param;
 };
 
 struct loadedFunction {
@@ -95,4 +100,6 @@ void completeTimers();
 void killSpeechTimers();
 int cancelAFunction(int funcNum, loadedFunction *myself, bool &killedMyself);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/sound.h b/engines/sludge/sound.h
index 61f834b..5bb3f9d 100644
--- a/engines/sludge/sound.h
+++ b/engines/sludge/sound.h
@@ -19,13 +19,19 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "variable.h"
+
+#ifndef SLUDGE_SOUND_H
+#define SLUDGE_SOUND_H
+
 #ifdef _WIN32
 #include <windows.h>
 #else
 #define HWND void *
 #endif
 
+#include "variable.h"
+
+namespace Sludge {
 
 // Sound list stuff
 struct soundList {
@@ -38,8 +44,6 @@ struct soundList {
 soundList *deleteSoundFromList(soundList *s);
 void playSoundList(soundList *s);
 
-
-
 // GENERAL...
 bool initSoundStuff(HWND);
 void killSoundStuff();
@@ -69,3 +73,7 @@ void saveSounds(FILE *fp);
 #endif
 
 unsigned int getSoundSource(int index);
+
+} // End of namespace Sludge
+
+#endif
diff --git a/engines/sludge/sound_bass.cpp b/engines/sludge/sound_bass.cpp
index 65d8c93..017796c 100644
--- a/engines/sludge/sound_bass.cpp
+++ b/engines/sludge/sound_bass.cpp
@@ -19,8 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include <stdint.h>
-
 #include "allfiles.h"
 #include "newfatal.h"
 #include "bass.h"
@@ -33,6 +31,8 @@
 #define EFFECT_CHANNELS 8
 #define TOTAL_CHANNELS 32
 
+namespace Sludge {
+
 bool soundOK = false;
 
 struct soundThing {
@@ -389,3 +389,4 @@ bool getSoundCacheStack(stackHandler *sH) {
 	return true;
 }
 
+} // End of namespace Sludge
diff --git a/engines/sludge/sound_nosound.cpp b/engines/sludge/sound_nosound.cpp
index 0731d23..8f8bb28 100644
--- a/engines/sludge/sound_nosound.cpp
+++ b/engines/sludge/sound_nosound.cpp
@@ -19,14 +19,14 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include <stdint.h>
-
 #include "allfiles.h"
 #include "newfatal.h"
 #include "sound.h"
 #include "moreio.h"
 #include "fileset.h"
 
+namespace Sludge {
+
 bool soundOK = false;
 
 int defVol = 128;
@@ -133,3 +133,5 @@ bool getSoundCacheStack(stackHandler *sH) {
 //#pragma unused (sH)
 	return true;
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/sound_openal.cpp b/engines/sludge/sound_openal.cpp
index fdb1e0b..aa8f8e1 100644
--- a/engines/sludge/sound_openal.cpp
+++ b/engines/sludge/sound_openal.cpp
@@ -37,6 +37,8 @@
 #define MAX_MODS 3
 #define NUM_BUFS 3
 
+namespace Sludge {
+
 bool soundOK = false;
 bool cacheLoopySound = false;
 bool SilenceIKillYou = false;
@@ -815,3 +817,5 @@ int initMovieSound(int f, ALenum format, int audioChannels, ALuint samplerate,
 unsigned int getSoundSource(int index) {
 	return 0; /*soundCache[index].playingOnSource;*/ //TODO:false value
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/sprbanks.cpp b/engines/sludge/sprbanks.cpp
index bb3303b..c95e405 100644
--- a/engines/sludge/sprbanks.cpp
+++ b/engines/sludge/sprbanks.cpp
@@ -25,6 +25,8 @@
 #include "newfatal.h"
 #include "debug.h"
 
+namespace Sludge {
+
 loadedSpriteBank *allLoadedBanks = NULL;
 extern spriteBank theFont;
 extern int loadedFontNum, fontTableSize;
@@ -72,3 +74,5 @@ void reloadSpriteTextures() {
 		loadSpriteBank(loadedFontNum, theFont, true);
 	}
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/sprbanks.h b/engines/sludge/sprbanks.h
index 3c0efd3..81d1bc7 100644
--- a/engines/sludge/sprbanks.h
+++ b/engines/sludge/sprbanks.h
@@ -24,6 +24,8 @@
 
 #include "sprites.h"
 
+namespace Sludge {
+
 struct loadedSpriteBank {
 	int ID, timesUsed;
 	spriteBank bank;
@@ -33,4 +35,6 @@ struct loadedSpriteBank {
 loadedSpriteBank *loadBankForAnim(int ID);
 void reloadSpriteTextures();
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index 43ddcbe..792fe66 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -27,8 +27,6 @@
 #endif
 #endif
 
-#include <string.h>
-
 #include "allfiles.h"
 
 #include "fileset.h"
@@ -45,6 +43,8 @@
 
 #include "shaders.h"
 
+namespace Sludge {
+
 extern zBufferData zBuffer;
 
 #if 0
@@ -1109,3 +1109,4 @@ void fixScaleSprite(int x, int y, sprite &single, const spritePalette &fontPal,
 #endif
 }
 
+} // End of namespace Sludge
diff --git a/engines/sludge/sprites.h b/engines/sludge/sprites.h
index e9f053f..2a617bb 100644
--- a/engines/sludge/sprites.h
+++ b/engines/sludge/sprites.h
@@ -30,6 +30,8 @@
 #endif
 #endif
 
+namespace Sludge {
+
 struct onScreenPerson;
 
 struct sprite {
@@ -90,4 +92,6 @@ bool reserveSpritePal(spritePalette &sP, int n);
 void fixScaleSprite(int x1, int y1, sprite &single, const spritePalette &fontPal, onScreenPerson *thisPerson, const int camX, const int camY, bool);
 void burnSpriteToBackDrop(int x1, int y1, sprite &single, const spritePalette &fontPal);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/statusba.cpp b/engines/sludge/statusba.cpp
index 43674a9..e7dc4cb 100644
--- a/engines/sludge/statusba.cpp
+++ b/engines/sludge/statusba.cpp
@@ -30,6 +30,8 @@
 #include "newfatal.h"
 #include "statusba.h"
 
+namespace Sludge {
+
 spritePalette verbLinePalette;
 spritePalette litVerbLinePalette;
 
@@ -227,3 +229,5 @@ bool loadStatusBars(FILE *fp) {
 	return true;
 }
 #endif
+
+} // End of namespace Sludge
diff --git a/engines/sludge/statusba.h b/engines/sludge/statusba.h
index faa164c..2f0d30a 100644
--- a/engines/sludge/statusba.h
+++ b/engines/sludge/statusba.h
@@ -22,6 +22,8 @@
 #ifndef SLUDGE_STATUSBA_H
 #define SLUDGE_STATUSBA_H
 
+namespace Sludge {
+
 struct statusBar {
 	char *text;
 	statusBar *next;
@@ -59,4 +61,6 @@ void saveStatusBars(FILE *fp);
 void restoreBarStuff(statusStuff *here);
 statusStuff *copyStatusBarStuff(statusStuff *here);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/stringy.cpp b/engines/sludge/stringy.cpp
index fdf4536..a5440b6 100644
--- a/engines/sludge/stringy.cpp
+++ b/engines/sludge/stringy.cpp
@@ -20,10 +20,13 @@
  *
  */
 #include "allfiles.h"
-#include <string.h>
-
 #include "newfatal.h"
 
+#ifndef SLUDGE_STRINGY_H
+#define SLUDGE_STRINGY_H
+
+namespace Sludge {
+
 char *copyString(const char *copyMe) {
 	char *newString = new char [strlen(copyMe) + 1];
 	if (! checkNew(newString)) return NULL;
@@ -37,3 +40,7 @@ char *joinStrings(const char *s1, const char *s2) {
 	sprintf(newString, "%s%s", s1, s2);
 	return newString;
 }
+
+} // End of namespace Sludge
+
+#endif
diff --git a/engines/sludge/stringy.h b/engines/sludge/stringy.h
index 2306567..7c6f9ed 100644
--- a/engines/sludge/stringy.h
+++ b/engines/sludge/stringy.h
@@ -22,7 +22,11 @@
 #ifndef SLUDGE_STRINGY_H
 #define SLUDGE_STRINGY_H
 
+namespace Sludge {
+
 char *copyString(const char *copyMe);
 char *joinStrings(const char *s1, const char *s2);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/talk.cpp b/engines/sludge/talk.cpp
index 2803e2b..b6bc864 100644
--- a/engines/sludge/talk.cpp
+++ b/engines/sludge/talk.cpp
@@ -20,9 +20,6 @@
  *
  */
 #include "allfiles.h"
-
-#include <string.h>
-
 #include "backdrop.h"
 #include "sprites.h"
 #include "sludger.h"
@@ -37,6 +34,8 @@
 #include "stringy.h"
 #include "moreio.h"
 
+namespace Sludge {
+
 extern int fontHeight, cameraX, cameraY, speechMode;
 extern float cameraZoom;
 speechStruct *speech;
@@ -272,3 +271,5 @@ bool loadSpeech(speechStruct *sS, FILE *fp) {
 	return true;
 }
 #endif
+
+} // End of namespace Sludge
diff --git a/engines/sludge/talk.h b/engines/sludge/talk.h
index ba9bd7f..a0fb1a9 100644
--- a/engines/sludge/talk.h
+++ b/engines/sludge/talk.h
@@ -24,6 +24,8 @@
 
 #include "sprites.h"
 
+namespace Sludge {
+
 struct speechLine {
 	char *textLine;
 	speechLine *next;
@@ -49,4 +51,7 @@ void initSpeech();
 void saveSpeech(speechStruct *sS, FILE *fp);
 bool loadSpeech(speechStruct *sS, FILE *fp);
 #endif
+
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/thumbnail.cpp b/engines/sludge/thumbnail.cpp
index 53ab7ec..9cb471f 100644
--- a/engines/sludge/thumbnail.cpp
+++ b/engines/sludge/thumbnail.cpp
@@ -19,8 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include <stdint.h>
-
 #include "allfiles.h"
 #include "errors.h"
 #include "moreio.h"
@@ -31,6 +29,8 @@
 #include "graphics.h"
 #include "newfatal.h"
 
+namespace Sludge {
+
 bool freeze();
 void unfreeze(bool);    // Because FREEZE.H needs a load of other includes
 
@@ -264,3 +264,5 @@ bool skipThumbnail(FILE *fp) {
 	return (fgetc(fp) == '!');
 }
 #endif
+
+} // End of namespace Sludge
diff --git a/engines/sludge/thumbnail.h b/engines/sludge/thumbnail.h
index 4e505be..3836478 100644
--- a/engines/sludge/thumbnail.h
+++ b/engines/sludge/thumbnail.h
@@ -22,10 +22,15 @@
 #ifndef SLUDGE_THUMBNAIL_H
 #define SLUDGE_THUMBNAIL_H
 
+namespace Sludge {
+
 #if ALLOW_FILE
 bool saveThumbnail(FILE *fp);
 bool skipThumbnail(FILE *fp);
 #endif
 
 void showThumbnail(char *filename, int x, int y);
+
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/timing.cpp b/engines/sludge/timing.cpp
index a1dcba0..ae4c0cd 100644
--- a/engines/sludge/timing.cpp
+++ b/engines/sludge/timing.cpp
@@ -23,6 +23,8 @@
 #include <SDL/SDL.h>
 #endif
 
+namespace Sludge {
+
 int desiredfps = 300;               //holds desired frames per second
 Uint32 starttime, endtime;
 Uint32 desired_frame_time;
@@ -54,3 +56,4 @@ void Wait_Frame(void) {
 	starttime = endtime;
 }
 
+} // End of namespace Sludge
diff --git a/engines/sludge/timing.h b/engines/sludge/timing.h
index 504bf62..0fd59f5 100644
--- a/engines/sludge/timing.h
+++ b/engines/sludge/timing.h
@@ -22,10 +22,14 @@
 #ifndef SLUDGE_TIMING_H
 #define SLUDGE_TIMING_H
 
+namespace Sludge {
+
 void Init_Timer(void);
 void Init_Special_Timer(int t);
 void Get_Start_Time(void);
 void Get_End_Time(void);
 void Wait_Frame(void);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/transition.cpp b/engines/sludge/transition.cpp
index 041e2c9..0fcd4fe 100644
--- a/engines/sludge/transition.cpp
+++ b/engines/sludge/transition.cpp
@@ -20,8 +20,6 @@
  *
  */
 #include <stdint.h>
-#include <string.h>
-
 #include "allfiles.h"
 #include "colours.h"
 #include "backdrop.h"
@@ -32,13 +30,14 @@
 extern GLuint snapshotTextureName;
 #endif
 
+namespace Sludge {
+
 extern unsigned char brightnessLevel;
 
 extern float snapTexW, snapTexH;
 
 unsigned char fadeMode = 2;
 
-
 //----------------------------------------------------
 // PROPER BRIGHTNESS FADING
 //----------------------------------------------------
@@ -406,3 +405,5 @@ void fixBrightness() {
 
 	}
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/transition.h b/engines/sludge/transition.h
index f05c438..7dc29f7 100644
--- a/engines/sludge/transition.h
+++ b/engines/sludge/transition.h
@@ -22,7 +22,11 @@
 #ifndef SLUDGE_TRANSITION_H
 #define SLUDGE_TRANSITION_H
 
+namespace Sludge {
+
 void fixBrightness();
 void resetRandW();
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/variable.cpp b/engines/sludge/variable.cpp
index 2c64a7f..334beb1 100644
--- a/engines/sludge/variable.cpp
+++ b/engines/sludge/variable.cpp
@@ -19,15 +19,11 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include <string.h>
-
 #include "debug.h"
 
 #include "allfiles.h"
-
 #include "variable.h"
 #include "newfatal.h"
-
 #include "stringy.h"
 #include "objtypes.h"
 #include "people.h"
@@ -40,6 +36,8 @@
 
 #endif
 
+namespace Sludge {
+
 const char *typeName[] = {"undefined", "number", "user function", "string",
                           "built-in function", "file", "stack",
                           "object type", "animation", "costume"
@@ -667,3 +665,5 @@ void debugVar (FILE * fp, const variable & thisVar) {
     }
 }
 */
+
+} // End of namespace Sludge
diff --git a/engines/sludge/variable.h b/engines/sludge/variable.h
index 8d633c8..8f9f743 100644
--- a/engines/sludge/variable.h
+++ b/engines/sludge/variable.h
@@ -22,6 +22,11 @@
 #ifndef SLUDGE_VARIABLE_H
 #define SLUDGE_VARIABLE_H
 
+namespace Sludge {
+
+struct variable;
+struct variableStack;
+
 enum variableType {SVT_NULL, SVT_INT, SVT_FUNC, SVT_STRING,
                    SVT_BUILT, SVT_FILE, SVT_STACK,
                    SVT_OBJTYPE, SVT_ANIM, SVT_COSTUME,
@@ -114,6 +119,7 @@ variable *fastArrayGetByIndex(fastArrayHandler *vS, unsigned int theIndex);
 #define stackDebug(a)  {}
 #endif
 
+} // End of namespace Sludge
 
 #endif
 
diff --git a/engines/sludge/vid.cpp b/engines/sludge/vid.cpp
index a95a452..266c5bd 100644
--- a/engines/sludge/vid.cpp
+++ b/engines/sludge/vid.cpp
@@ -37,6 +37,8 @@
 #include "colours.h"
 #include "fileset.h"
 
+namespace Sludge {
+
 struct timStream {
 	PAVISTREAM      got;
 	AVISTREAMINFO   info;
@@ -257,3 +259,5 @@ bool nextVideoFrame() {
 
 	return true;
 }
+
+} // End of namespace Sludge
diff --git a/engines/sludge/vid.h b/engines/sludge/vid.h
index 5b28e37..1d81daf 100644
--- a/engines/sludge/vid.h
+++ b/engines/sludge/vid.h
@@ -22,9 +22,13 @@
 #ifndef SLUDGE_VID_H
 #define SLUDGE_VID_H
 
+namespace Sludge {
+
 bool startVideo(int fileNum);
 bool nextVideoFrame();
 void finishVideo();
 void initialiseMovieStuff();
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/winstuff.cpp b/engines/sludge/winstuff.cpp
index 2e51b4b..266df69 100644
--- a/engines/sludge/winstuff.cpp
+++ b/engines/sludge/winstuff.cpp
@@ -51,6 +51,8 @@
 
 #include "..\..\images\resource.h"
 
+namespace Sludge {
+
 HINSTANCE hInst;                // Handle of the main instance
 extern HWND hMainWindow;
 
@@ -224,4 +226,7 @@ uint32_t launch(char *f) {
 bool defaultUserFullScreen() {
 	return true;
 }
+
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/winstuff.h b/engines/sludge/winstuff.h
index a934f44..4a0cbbe 100644
--- a/engines/sludge/winstuff.h
+++ b/engines/sludge/winstuff.h
@@ -26,6 +26,8 @@
 #include <windows.h>
 #endif
 
+namespace Sludge {
+
 #ifndef _WIN32
 #ifndef HINSTANCE
 #define HINSTANCE int
@@ -36,4 +38,6 @@ void setWindowName(const char *tx);
 bool InitApplication(HINSTANCE hInstance);
 bool InitInstance(HINSTANCE hInstance, const char *);
 
+} // End of namespace Sludge
+
 #endif
diff --git a/engines/sludge/zbuffer.cpp b/engines/sludge/zbuffer.cpp
index 6597f37..ddcebb1 100644
--- a/engines/sludge/zbuffer.cpp
+++ b/engines/sludge/zbuffer.cpp
@@ -28,6 +28,8 @@
 #include "newfatal.h"
 #include "graphics.h"
 
+namespace Sludge {
+
 zBufferData zBuffer;
 extern int sceneWidth, sceneHeight;
 
@@ -203,3 +205,4 @@ void drawZBuffer(int x, int y, bool upsidedown) {
 #endif
 }
 
+} // End of namespace Sludge
diff --git a/engines/sludge/zbuffer.h b/engines/sludge/zbuffer.h
index 9040f57..6fdbd02 100644
--- a/engines/sludge/zbuffer.h
+++ b/engines/sludge/zbuffer.h
@@ -30,6 +30,7 @@
 #endif
 #endif
 
+namespace Sludge {
 
 struct zBufferData {
 	int width, height;
@@ -48,4 +49,6 @@ bool setZBuffer(int y);
 void killZBuffer();
 void drawZBuffer(int x, int y, bool upsidedown);
 
+} // End of namespace Sludges
+
 #endif


Commit: f2d81f6f5dd52f838518ee24080f1ebc9451c7f8
    https://github.com/scummvm/scummvm/commit/f2d81f6f5dd52f838518ee24080f1ebc9451c7f8
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Add new debug channels

Changed paths:
    engines/sludge/sludge.cpp
    engines/sludge/sludge.h


diff --git a/engines/sludge/sludge.cpp b/engines/sludge/sludge.cpp
index 0301d73..d0d6b37 100644
--- a/engines/sludge/sludge.cpp
+++ b/engines/sludge/sludge.cpp
@@ -41,7 +41,9 @@ SludgeEngine::SludgeEngine(OSystem *syst, const SludgeGameDescription *gameDesc)
 
 	// Add debug channels
 	DebugMan.addDebugChannel(kSludgeDebugScript, "Script", "Script debug level");
-	DebugMan.addDebugChannel(kSludgeDebugDataLoad, "DataLoad", "Data loading debug level");
+	DebugMan.addDebugChannel(kSludgeDebugDataLoad, "Data Load", "Data loading debug level");
+	DebugMan.addDebugChannel(kSludgeDebugStackMachine, "Stack Machine", "Stack Machine debug level");
+	DebugMan.addDebugChannel(kSludgeDebugBuiltin, "Built-in", "Built-in debug level");
 
 	// check init
 	debug("SludgeEngine::SludgeEngine");
diff --git a/engines/sludge/sludge.h b/engines/sludge/sludge.h
index 7878518..4570b04 100644
--- a/engines/sludge/sludge.h
+++ b/engines/sludge/sludge.h
@@ -22,23 +22,25 @@
 
 #ifndef SLUDGE_H
 #define SLUDGE_H
- 
+
 #include "common/random.h"
 #include "engines/engine.h"
 #include "gui/debugger.h"
- 
+
 #include "sludge/console.h"
 
 namespace Sludge {
  
 class SludgeConsole;
- 
+
 struct SludgeGameDescription;
 
 // debug channels
 enum {
 	kSludgeDebugScript = 1 << 0,
 	kSludgeDebugDataLoad = 1 << 1,
+	kSludgeDebugStackMachine = 1 << 2,
+	kSludgeDebugBuiltin = 1 << 3,
 };
  
 class SludgeEngine : public Engine {


Commit: 1aa64b5b0f1b6908e76e796cb7e683a5587d5c4d
    https://github.com/scummvm/scummvm/commit/1aa64b5b0f1b6908e76e796cb7e683a5587d5c4d
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Add namespace for file version.h

Changed paths:
    engines/sludge/CommonCode/version.h


diff --git a/engines/sludge/CommonCode/version.h b/engines/sludge/CommonCode/version.h
index 2b640a0..9307bff 100644
--- a/engines/sludge/CommonCode/version.h
+++ b/engines/sludge/CommonCode/version.h
@@ -10,4 +10,8 @@
 
 #define VERSION(a,b)    (a * 256 + b)
 
+namespace Sludge {
+
 extern int gameVersion;
+
+} // End of namespace Sludge


Commit: f5b4cf680371b5b2098c766361b5efc6e0a68e91
    https://github.com/scummvm/scummvm/commit/f5b4cf680371b5b2098c766361b5efc6e0a68e91
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Remove inner include of vorbis library

Changed paths:
    engines/sludge/movie.cpp


diff --git a/engines/sludge/movie.cpp b/engines/sludge/movie.cpp
index 09693f1..3f02f73 100644
--- a/engines/sludge/movie.cpp
+++ b/engines/sludge/movie.cpp
@@ -44,11 +44,12 @@
 #include "shaders.h"
 
 #include "sound.h"
+
+#if 0
 #include "vorbis/codec.h"
 #define OV_EXCLUDE_STATIC_CALLBACKS
 #include "vorbis/vorbisfile.h"
 
-#if 0
 #include "ogg/ogg.h"
 #include "libvorbis/vorbis_os.h"
 


Commit: 45dcfdfc0bad326800618d4d3edfd772d53c9fc6
    https://github.com/scummvm/scummvm/commit/45dcfdfc0bad326800618d4d3edfd772d53c9fc6
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Replace standard file reading functions by Common functions

Changed paths:
    engines/sludge/backdrop.cpp
    engines/sludge/backdrop.h
    engines/sludge/bg_effects.cpp
    engines/sludge/bg_effects.h
    engines/sludge/builtin.cpp
    engines/sludge/detection.cpp
    engines/sludge/fileset.cpp
    engines/sludge/fileset.h
    engines/sludge/floor.cpp
    engines/sludge/helpers.cpp
    engines/sludge/language.cpp
    engines/sludge/language.h
    engines/sludge/loadsave.cpp
    engines/sludge/loadsave.h
    engines/sludge/main_loop.cpp
    engines/sludge/memwatch.cpp
    engines/sludge/module.mk
    engines/sludge/moreio.cpp
    engines/sludge/moreio.h
    engines/sludge/newfatal.cpp
    engines/sludge/objtypes.cpp
    engines/sludge/objtypes.h
    engines/sludge/people.cpp
    engines/sludge/people.h
    engines/sludge/region.cpp
    engines/sludge/region.h
    engines/sludge/savedata.cpp
    engines/sludge/shaders.cpp
    engines/sludge/sludger.cpp
    engines/sludge/sludger.h
    engines/sludge/sound.h
    engines/sludge/sound_bass.cpp
    engines/sludge/sound_nosound.cpp
    engines/sludge/sound_openal.cpp
    engines/sludge/sprites.cpp
    engines/sludge/statusba.cpp
    engines/sludge/statusba.h
    engines/sludge/talk.cpp
    engines/sludge/talk.h
    engines/sludge/thumbnail.cpp
    engines/sludge/thumbnail.h
    engines/sludge/timing.cpp
    engines/sludge/variable.cpp
    engines/sludge/vid.cpp
    engines/sludge/zbuffer.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index bb840b3..929e67d 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -96,16 +96,16 @@ void nosnapshot() {
 #endif
 }
 
+void saveSnapshot(Common::WriteStream *stream) {
 #if 0
-void saveSnapshot(FILE *fp) {
 	if (snapshotTextureName) {
-		fputc(1, fp);               // 1 for snapshot follows
-		saveCoreHSI(fp, snapshotTextureName, winWidth, winHeight);
+		putch(1, stream);               // 1 for snapshot follows
+		saveCoreHSI(stream, snapshotTextureName, winWidth, winHeight);
 	} else {
-		fputc(0, fp);
+		putch(0, stream);
 	}
-}
 #endif
+}
 
 bool snapshot() {
 
@@ -157,17 +157,16 @@ bool snapshot() {
 	return true;
 }
 
-#if 0
-bool restoreSnapshot(FILE *fp) {
-	unsigned int picWidth = get2bytes(fp);
-	unsigned int picHeight = get2bytes(fp);
+bool restoreSnapshot(Common::SeekableReadStream *stream) {
+	unsigned int picWidth = get2bytes(stream);
+	unsigned int picHeight = get2bytes(stream);
 
 	if ((picWidth != winWidth) || (picHeight != winHeight))
 		return false;
 
 	unsigned int t1, t2, n;
 	unsigned short c;
-
+#if 0
 	GLubyte *target;
 	if (! NPOT_textures) {
 		picWidth = getNextPOT(picWidth);
@@ -177,17 +176,19 @@ bool restoreSnapshot(FILE *fp) {
 	}
 	GLubyte *snapshotTexture = new GLubyte [picHeight * picWidth * 4];
 	if (! snapshotTexture) return fatal("Out of memory while restoring snapshot.");
+#endif
 
 	for (t2 = 0; t2 < winHeight; t2 ++) {
 		t1 = 0;
 		while (t1 < winWidth) {
-			c = (unsigned short) get2bytes(fp);
+			c = (unsigned short) get2bytes(stream);
 			if (c & 32) {
-				n = fgetc(fp) + 1;
+				n = getch(stream) + 1;
 				c -= 32;
 			} else {
 				n = 1;
 			}
+#if 0
 			while (n --) {
 				target = snapshotTexture + 4 * picWidth * t2 + t1 * 4;
 				target[0] = (GLubyte) redValue(c);
@@ -196,9 +197,10 @@ bool restoreSnapshot(FILE *fp) {
 				target[3] = (GLubyte) 255;
 				t1++;
 			}
+#endif
 		}
 	}
-
+#if 0
 	if (! snapshotTextureName) glGenTextures(1, &snapshotTextureName);
 	glBindTexture(GL_TEXTURE_2D, snapshotTextureName);
 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
@@ -210,10 +212,9 @@ bool restoreSnapshot(FILE *fp) {
 
 	delete snapshotTexture;
 	snapshotTexture = NULL;
-
+#endif
 	return true;
 }
-#endif
 
 void killBackDrop() {
 #if 0
@@ -1005,7 +1006,7 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 extern int viewportOffsetX, viewportOffsetY;
 
 #if 0
-bool loadHSI(FILE *fp, int x, int y, bool reserve) {
+bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 
 	int t1, t2, n;
 	unsigned short c;
@@ -1014,7 +1015,7 @@ bool loadHSI(FILE *fp, int x, int y, bool reserve) {
 	int picWidth;
 	int picHeight;
 	int realPicWidth, realPicHeight;
-	long file_pointer = ftell(fp);
+	long file_pointer = stream->pos();
 
 	png_structp png_ptr;
 	png_infop info_ptr, end_info;
@@ -1025,20 +1026,20 @@ bool loadHSI(FILE *fp, int x, int y, bool reserve) {
 	// Is this a PNG file?
 
 	char tmp[10];
-	size_t bytes_read = fread(tmp, 1, 8, fp);
-	if (bytes_read != 8 && ferror(fp)) {
+	size_t bytes_read = stream->read(tmp, 8);
+	if (bytes_read != 8 && stream->err()) {
 		debugOut("Reading error in loadHSI.\n");
 	}
 	if (png_sig_cmp((png_byte *) tmp, 0, 8)) {
 		// No, it's old-school HSI
 		fileIsPNG = false;
-		fseek(fp, file_pointer, SEEK_SET);
+		stream->seek(file_pointer, SEEK_SET);
 
-		picWidth = realPicWidth = get2bytes(fp);
-		picHeight = realPicHeight = get2bytes(fp);
+		picWidth = realPicWidth = get2bytes(stream);
+		picHeight = realPicHeight = get2bytes(stream);
 	} else {
 		// Read the PNG header
-
+#if 0
 		png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
 		if (!png_ptr) {
 			return false;
@@ -1078,10 +1079,10 @@ bool loadHSI(FILE *fp, int x, int y, bool reserve) {
 		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
 
 		//int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
-
+#endif
 	}
 
-
+#if 0
 	GLfloat texCoordW = 1.0;
 	GLfloat texCoordH = 1.0;
 	if (! NPOT_textures) {
@@ -1138,7 +1139,7 @@ bool loadHSI(FILE *fp, int x, int y, bool reserve) {
 	}
 
 	GLuint tmpTex;
-#if 0
+
 	glGenTextures(1, &tmpTex);
 	glBindTexture(GL_TEXTURE_2D, tmpTex);
 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
@@ -1150,7 +1151,7 @@ bool loadHSI(FILE *fp, int x, int y, bool reserve) {
 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 	}
-#endif
+
 	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, backdropTexture, tmpTex);
 
 
@@ -1189,9 +1190,9 @@ bool loadHSI(FILE *fp, int x, int y, bool reserve) {
 		int yoffset = 0;
 		while (yoffset < realPicHeight) {
 			int h = (realPicHeight - yoffset < viewportHeight) ? realPicHeight - yoffset : viewportHeight;
-#if 0
+
 			glClear(GL_COLOR_BUFFER_BIT);   // Clear The Screen
-#endif
+
 			const GLfloat vertices[] = {
 				(GLfloat) - xoffset, (GLfloat) - yoffset, 0.,
 				(GLfloat)realPicWidth - xoffset, (GLfloat) - yoffset, 0.,
@@ -1207,7 +1208,7 @@ bool loadHSI(FILE *fp, int x, int y, bool reserve) {
 			};
 
 			if (backdropExists) {
-#if 0
+
 				// Render the sprite to the backdrop
 				// (using mulitexturing, so the old backdrop is seen where alpha < 1.0)
 				glActiveTexture(GL_TEXTURE2);
@@ -1217,35 +1218,34 @@ bool loadHSI(FILE *fp, int x, int y, bool reserve) {
 				glUseProgram(shader.paste);
 				GLint uniform = glGetUniformLocation(shader.paste, "useLightTexture");
 				if (uniform >= 0) glUniform1i(uniform, 0); // No lighting
-#endif
 				setPMVMatrix(shader.paste);
 
 				setPrimaryColor(1.0, 1.0, 1.0, 1.0);
-#if 0
+
 				glBindTexture(GL_TEXTURE_2D, tmpTex);
 				//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
-#endif
+
 				drawQuad(shader.paste, vertices, 3, texCoords, NULL, btexCoords);
-#if 0
+
 				glUseProgram(0);
-#endif
+
 			} else {
 				// It's all new - nothing special to be done.
 
-#if 0
+
 				glUseProgram(shader.texture);
-#endif
+
 				setPMVMatrix(shader.texture);
-#if 0
+
 				glBindTexture(GL_TEXTURE_2D, tmpTex);
-#endif
+
 				setPrimaryColor(1.0, 0.0, 0.0, 0.0);
 
 				drawQuad(shader.texture, vertices, 1, texCoords);
 
-#if 0
+
 				glUseProgram(0);
-#endif
+
 			}
 
 			// Copy Our ViewPort To The Texture
@@ -1259,17 +1259,17 @@ bool loadHSI(FILE *fp, int x, int y, bool reserve) {
 	deleteTextures(1, &tmpTex);
 
 	setPixelCoords(false);
-
+#endif
 	backdropExists = true;
 	return true;
 }
 
-bool mixHSI(FILE *fp, int x, int y) {
+bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 	int realPicWidth, realPicHeight;
 	int picWidth;
 	int picHeight;
 
-	long file_pointer = ftell(fp);
+	long file_pointer = stream->pos();
 
 	png_structp png_ptr;
 	png_infop info_ptr, end_info;
@@ -1279,17 +1279,18 @@ bool mixHSI(FILE *fp, int x, int y) {
 
 	// Is this a PNG file?
 	char tmp[10];
-	size_t bytes_read = fread(tmp, 1, 8, fp);
-	if (bytes_read != 8 && ferror(fp)) {
+	size_t bytes_read = stream->read(tmp, 8);
+	if (bytes_read != 8 && stream->err()) {
 		debugOut("Reading error in mixHSI.\n");
 	}
+#if 0
 	if (png_sig_cmp((png_byte *) tmp, 0, 8)) {
 		// No, it's old-school HSI
 		fileIsPNG = false;
-		fseek(fp, file_pointer, SEEK_SET);
+		stream->seek(file_pointer, SEEK_SET);
 
-		picWidth = realPicWidth = get2bytes(fp);
-		picHeight = realPicHeight = get2bytes(fp);
+		picWidth = realPicWidth = get2bytes(stream);
+		picHeight = realPicHeight = get2bytes(stream);
 	} else {
 		// Read the PNG header
 
@@ -1309,7 +1310,7 @@ bool mixHSI(FILE *fp, int x, int y) {
 			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
 			return false;
 		}
-		png_init_io(png_ptr, fp);       // Tell libpng which file to read
+		png_init_io(png_ptr, stream);       // Tell libpng which file to read
 		png_set_sig_bytes(png_ptr, 8);  // 8 bytes already read
 
 		png_read_info(png_ptr, info_ptr);
@@ -1398,9 +1399,9 @@ bool mixHSI(FILE *fp, int x, int y) {
 		for (t2 = 0; t2 < realPicHeight; t2 ++) {
 			t1 = 0;
 			while (t1 < realPicWidth) {
-				c = (unsigned short) get2bytes(fp);
+				c = (unsigned short) get2bytes(stream);
 				if (c & 32) {
-					n = fgetc(fp) + 1;
+					n = getch(stream) + 1;
 					c -= 32;
 				} else {
 					n = 1;
@@ -1425,7 +1426,7 @@ bool mixHSI(FILE *fp, int x, int y) {
 	}
 
 	GLuint tmpTex;
-#if 0
+
 	glGenTextures(1, &tmpTex);
 	glBindTexture(GL_TEXTURE_2D, tmpTex);
 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
@@ -1437,7 +1438,7 @@ bool mixHSI(FILE *fp, int x, int y) {
 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 	}
-#endif
+
 	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, backdropTexture, tmpTex);
 
 
@@ -1453,7 +1454,7 @@ bool mixHSI(FILE *fp, int x, int y) {
 		int yoffset = 0;
 		while (yoffset < realPicHeight) {
 			int h = (realPicHeight - yoffset < viewportHeight) ? realPicHeight - yoffset : viewportHeight;
-#if 0
+
 			glClear(GL_COLOR_BUFFER_BIT);   // Clear The Screen
 
 			// Render the sprite to the backdrop
@@ -1465,14 +1466,14 @@ bool mixHSI(FILE *fp, int x, int y) {
 			glUseProgram(shader.paste);
 			GLint uniform = glGetUniformLocation(shader.paste, "useLightTexture");
 			if (uniform >= 0) glUniform1i(uniform, 0); // No lighting
-#endif
+
 			setPMVMatrix(shader.paste);
 
 			setPrimaryColor(1.0, 1.0, 1.0, 0.5);
-#if 0
+
 			glBindTexture(GL_TEXTURE_2D, tmpTex);
 			//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
-#endif
+
 			const GLfloat vertices[] = {
 				(GLfloat) - xoffset, (GLfloat) - yoffset, 0.,
 				(GLfloat)realPicWidth - xoffset, (GLfloat) - yoffset, 0.,
@@ -1481,10 +1482,10 @@ bool mixHSI(FILE *fp, int x, int y) {
 			};
 
 			drawQuad(shader.paste, vertices, 3, texCoords, NULL, btexCoords);
-#if 0
+
 			// Copy Our ViewPort To The Texture
 			glUseProgram(0);
-#endif
+
 			copyTexSubImage2D(GL_TEXTURE_2D, 0, (int)((x < 0) ? xoffset : x + xoffset), (int)((y < 0) ? yoffset : y + yoffset), (int)((x < 0) ? viewportOffsetX - x : viewportOffsetX), (int)((y < 0) ? viewportOffsetY - y : viewportOffsetY), w, h, backdropTextureName);
 
 			yoffset += viewportHeight;
@@ -1494,19 +1495,21 @@ bool mixHSI(FILE *fp, int x, int y) {
 	}
 	deleteTextures(1, &tmpTex);
 	setPixelCoords(false);
+#endif
 	return true;
 }
 
-void saveCorePNG(FILE *writer, GLuint texture, int w, int h) {
-	GLint tw, th;
+void saveCorePNG(Common::WriteStream *stream, GLuint texture, int w, int h) {
 #if 0
+	GLint tw, th;
+
 	glBindTexture(GL_TEXTURE_2D, texture);
-#endif
+
 	getTextureDimensions(texture, &tw, &th);
 
 	GLubyte *image = new GLubyte [tw * th * 4];
 	if (! checkNew(image)) return;
-#if 0
+
 	glPixelStorei(GL_PACK_ALIGNMENT, 1);
 //	glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
 #endif
@@ -1557,11 +1560,11 @@ void saveCorePNG(FILE *writer, GLuint texture, int w, int h) {
 
 #if 0
 			glUseProgram(shader.texture);
-#endif
+
 			setPMVMatrix(shader.texture);
 
 			drawQuad(shader.texture, vertices, 1, texCoords);
-#if 0
+
 			glUseProgram(0);
 
 			for (int i = 0; i < h; i++)   {
diff --git a/engines/sludge/backdrop.h b/engines/sludge/backdrop.h
index 5dd2014..8974f92 100644
--- a/engines/sludge/backdrop.h
+++ b/engines/sludge/backdrop.h
@@ -67,12 +67,12 @@ void mixBackDrop(int fileNum, int x, int y);
 void drawBackDrop();
 void blankScreen(int x1, int y1, int x2, int y2);
 void darkScreen();
+void saveHSI(Common::WriteStream *stream);
 #if 0
-void saveHSI(FILE *writer);
-void saveCoreHSI(FILE *writer, GLuint texture, int w, int h);
-bool loadHSI(FILE *fp, int, int, bool);
-bool mixHSI(FILE *fp, int x = 0, int y = 0);
+void saveCoreHSI(Common::WriteStream *stream, GLuint texture, int w, int h);
 #endif
+bool loadHSI(Common::SeekableReadStream *stream, int, int, bool);
+bool mixHSI(Common::SeekableReadStream *stream, int x = 0, int y = 0);
 void drawHorizontalLine(unsigned int, unsigned int, unsigned int);
 void drawVerticalLine(unsigned int, unsigned int, unsigned int);
 void hardScroll(int distance);
@@ -91,17 +91,13 @@ extern texture lightMap;
 
 void killParallax();
 bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY);
-#if 0
-void saveParallaxRecursive(parallaxLayer *me, FILE *fp);
-#endif
+void saveParallaxRecursive(parallaxLayer *me, Common::WriteStream *fp);
 void reloadParallaxTextures();
 
 void nosnapshot();
 bool snapshot();
-#if ALLOW_FILE
-void saveSnapshot(FILE *fp);
-bool restoreSnapshot(FILE *fp);
-#endif
+void saveSnapshot(Common::WriteStream *stream);
+bool restoreSnapshot(Common::SeekableReadStream *stream);
 #endif
 
 } // End of namespace Sludge
diff --git a/engines/sludge/bg_effects.cpp b/engines/sludge/bg_effects.cpp
index 0a8550e..8a61551 100644
--- a/engines/sludge/bg_effects.cpp
+++ b/engines/sludge/bg_effects.cpp
@@ -28,6 +28,9 @@
 #include "newfatal.h"
 #include "moreio.h"
 
+#include "common/debug.h"
+#include "common/file.h"
+
 namespace Sludge {
 
 #if 0
@@ -113,22 +116,20 @@ static int *s_matrixEffectData = NULL;
 static int s_matrixEffectBase = 0;
 #endif
 
-#if ALLOW_FILE
-void blur_saveSettings(FILE *fp) {
+void blur_saveSettings(Common::WriteStream *stream) {
 	if (s_matrixEffectData) {
-		put4bytes(s_matrixEffectDivide, fp);
-		put4bytes(s_matrixEffectWidth, fp);
-		put4bytes(s_matrixEffectHeight, fp);
-		put4bytes(s_matrixEffectBase, fp);
-		fwrite(s_matrixEffectData, sizeof(int), s_matrixEffectWidth * s_matrixEffectHeight, fp);
+		put4bytes(s_matrixEffectDivide, stream);
+		put4bytes(s_matrixEffectWidth, stream);
+		put4bytes(s_matrixEffectHeight, stream);
+		put4bytes(s_matrixEffectBase, stream);
+		stream->write(s_matrixEffectData, sizeof(int) * s_matrixEffectWidth * s_matrixEffectHeight);
 	} else {
-		put4bytes(0, fp);
-		put4bytes(0, fp);
-		put4bytes(0, fp);
-		put4bytes(0, fp);
+		put4bytes(0, stream);
+		put4bytes(0, stream);
+		put4bytes(0, stream);
+		put4bytes(0, stream);
 	}
 }
-#endif
 
 static int *blur_allocateMemoryForEffect() {
 	free(s_matrixEffectData);
@@ -141,23 +142,21 @@ static int *blur_allocateMemoryForEffect() {
 	return s_matrixEffectData;
 }
 
-#if ALLOW_FILE
-void blur_loadSettings(FILE *fp) {
-	s_matrixEffectDivide = get4bytes(fp);
-	s_matrixEffectWidth = get4bytes(fp);
-	s_matrixEffectHeight = get4bytes(fp);
-	s_matrixEffectBase = get4bytes(fp);
+void blur_loadSettings(Common::SeekableReadStream *stream) {
+	s_matrixEffectDivide = get4bytes(stream);
+	s_matrixEffectWidth = get4bytes(stream);
+	s_matrixEffectHeight = get4bytes(stream);
+	s_matrixEffectBase = get4bytes(stream);
 
 	if (blur_allocateMemoryForEffect()) {
-		size_t bytes_read = fread(s_matrixEffectData, sizeof(int), s_matrixEffectWidth * s_matrixEffectHeight, fp);
-		if (bytes_read != sizeof(int) * s_matrixEffectWidth * s_matrixEffectHeight && ferror(fp)) {
-			debugOut("Reading error in blur_loadSettings.\n");
+		size_t bytes_read = stream->read(s_matrixEffectData, sizeof(int) * s_matrixEffectWidth * s_matrixEffectHeight);
+		if (bytes_read != sizeof(int) * s_matrixEffectWidth * s_matrixEffectHeight && stream->err()) {
+			debug("Reading error in blur_loadSettings.");
 		}
 	} else {
-		fseek(fp, sizeof(int) * s_matrixEffectWidth * s_matrixEffectHeight, SEEK_CUR);
+		stream->seek(sizeof(int) * s_matrixEffectWidth * s_matrixEffectHeight, SEEK_CUR);
 	}
 }
-#endif
 
 bool blur_createSettings(int numParams, variableStack *&stack) {
 	bool createNullThing = true;
diff --git a/engines/sludge/bg_effects.h b/engines/sludge/bg_effects.h
index d18fae6..b726ec7 100644
--- a/engines/sludge/bg_effects.h
+++ b/engines/sludge/bg_effects.h
@@ -23,13 +23,13 @@
 #ifndef SLUDGE_BG_EFFECTS_H
 #define SLUDGE_BG_EFFECTS_H
 
+#include "common/file.h"
+
 namespace Sludge {
 
 bool blurScreen();
-#if ALLOW_FILE
-void blur_saveSettings(FILE *fp);
-void blur_loadSettings(FILE *fp);
-#endif
+void blur_saveSettings(Common::WriteStream *stream);
+void blur_loadSettings(Common::SeekableReadStream *stream);
 bool blur_createSettings(int numParams, variableStack *&stack);
 
 } // End of namespace Sludge
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 6f2660d..5d5c0fa 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -99,11 +99,11 @@ extern unsigned int currentBlankColour;
 extern unsigned int languageID;
 extern unsigned char currentBurnR, currentBurnG, currentBurnB;
 
-int paramNum[] = { -1, 0, 1, 1, -1, -1, 1, 3, 4, 1, 0, 0, 8, -1,    // SAY -> MOVEMOUSE
-                   -1, 0, 0, -1, -1, 1, 1, 1, 1, 4, 1, 1, 2, 1,// FOCUS -> REMOVEREGION
-                   2, 2, 0, 0, 2,                              // ANIMATE -> SETSCALE
+int paramNum[] = { -1, 0, 1, 1, -1, -1, 1, 3, 4, 1, 0, 0, 8, -1,    // SAY->MOVEMOUSE
+                   -1, 0, 0, -1, -1, 1, 1, 1, 1, 4, 1, 1, 2, 1,// FOCUS->REMOVEREGION
+                   2, 2, 0, 0, 2,                              // ANIMATE->SETSCALE
                    -1, 2, 1, 0, 0, 0, 1, 0, 3,                 // new/push/pop stack, status stuff
-                   2, 0, 0, 3, 1, 0, 2,                        // delFromStack -> completeTimers
+                   2, 0, 0, 3, 1, 0, 2,                        // delFromStack->completeTimers
                    -1, -1, -1, 2, 2, 0, 3, 1,                  // anim, costume, pO, setC, wait, sS, substring, stringLength
                    0, 1, 1, 0, 2,                              // dark, save, load, quit, rename
                    1, 3, 3, 1, 2, 1, 1, 3, 1, 0, 0, 2, 1,      // stackSize, pasteString, startMusic, defvol, vol, stopmus, stopsound, setfont, alignStatus, show x 2, pos'Status, setFloor
@@ -166,20 +166,20 @@ static builtReturn sayCore(int numParams, loadedFunction *fun, bool sayIt) {
 
 	switch (numParams) {
 	case 3:
-		if (!getValueType(fileNum, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
-		trimStack(fun -> stack);
+		if (!getValueType(fileNum, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+		trimStack(fun->stack);
 	// No break; here
 
 	case 2:
-		newText = getTextFromAnyVar(fun -> stack -> thisVar);
+		newText = getTextFromAnyVar(fun->stack->thisVar);
 		if (!newText) return BR_ERROR;
-		trimStack(fun -> stack);
-		if (!getValueType(objT, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-		trimStack(fun -> stack);
+		trimStack(fun->stack);
+		if (!getValueType(objT, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+		trimStack(fun->stack);
 		p = wrapSpeech(newText, objT, fileNum, sayIt);
-		fun -> timeLeft = p;
+		fun->timeLeft = p;
 		//debugOut ("BUILTIN: sayCore: %s (%i)\n", newText, p);
-		fun -> isSpeech = true;
+		fun->isSpeech = true;
 		delete newText;
 		newText = NULL;
 		return BR_KEEP_AND_PAUSE;
@@ -206,7 +206,7 @@ builtIn(freeze) {
 	UNUSEDALL
 	freeze();
 	freezeSubs();
-	fun -> freezerLevel = 0;
+	fun->freezerLevel = 0;
 	return BR_CONTINUE;
 }
 
@@ -219,63 +219,63 @@ builtIn(unfreeze) {
 
 builtIn(howFrozen) {
 	UNUSEDALL
-	setVariable(fun -> reg, SVT_INT, howFrozen());
+	setVariable(fun->reg, SVT_INT, howFrozen());
 	return BR_CONTINUE;
 }
 
 builtIn(setCursor) {
 	UNUSEDALL
-	personaAnimation *aa = getAnimationFromVar(fun -> stack -> thisVar);
+	personaAnimation *aa = getAnimationFromVar(fun->stack->thisVar);
 	pickAnimCursor(aa);
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
 	return BR_CONTINUE;
 }
 
 builtIn(getMouseX) {
 	UNUSEDALL
-	setVariable(fun -> reg, SVT_INT, input.mouseX + cameraX);
+	setVariable(fun->reg, SVT_INT, input.mouseX + cameraX);
 	return BR_CONTINUE;
 }
 
 builtIn(getMouseY) {
 	UNUSEDALL
-	setVariable(fun -> reg, SVT_INT, input.mouseY + cameraY);
+	setVariable(fun->reg, SVT_INT, input.mouseY + cameraY);
 	return BR_CONTINUE;
 }
 
 builtIn(getMouseScreenX) {
 	UNUSEDALL
-	setVariable(fun -> reg, SVT_INT, input.mouseX * cameraZoom);
+	setVariable(fun->reg, SVT_INT, input.mouseX * cameraZoom);
 	return BR_CONTINUE;
 }
 
 builtIn(getMouseScreenY) {
 	UNUSEDALL
-	setVariable(fun -> reg, SVT_INT, input.mouseY * cameraZoom);
+	setVariable(fun->reg, SVT_INT, input.mouseY * cameraZoom);
 	return BR_CONTINUE;
 }
 
 builtIn(getStatusText) {
 	UNUSEDALL
-	makeTextVar(fun -> reg, statusBarText());
+	makeTextVar(fun->reg, statusBarText());
 	return BR_CONTINUE;
 }
 
 builtIn(getMatchingFiles) {
 	UNUSEDALL
-	char *newText = getTextFromAnyVar(fun -> stack -> thisVar);
+	char *newText = getTextFromAnyVar(fun->stack->thisVar);
 	if (!newText) return BR_ERROR;
-	trimStack(fun -> stack);
-	unlinkVar(fun -> reg);
+	trimStack(fun->stack);
+	unlinkVar(fun->reg);
 
 	// Return value
-	fun -> reg.varType = SVT_STACK;
-	fun -> reg.varData.theStack = new stackHandler;
-	if (!checkNew(fun -> reg.varData.theStack)) return BR_ERROR;
-	fun -> reg.varData.theStack -> first = NULL;
-	fun -> reg.varData.theStack -> last = NULL;
-	fun -> reg.varData.theStack -> timesUsed = 1;
-	if (!getSavedGamesStack(fun -> reg.varData.theStack, newText)) return BR_ERROR;
+	fun->reg.varType = SVT_STACK;
+	fun->reg.varData.theStack = new stackHandler;
+	if (!checkNew(fun->reg.varData.theStack)) return BR_ERROR;
+	fun->reg.varData.theStack->first = NULL;
+	fun->reg.varData.theStack->last = NULL;
+	fun->reg.varData.theStack->timesUsed = 1;
+	if (!getSavedGamesStack(fun->reg.varData.theStack, newText)) return BR_ERROR;
 	delete newText;
 	newText = NULL;
 	return BR_CONTINUE;
@@ -288,8 +288,8 @@ builtIn(saveGame) {
 		fatal("Can't save game state while the engine is frozen");
 	}
 
-	loadNow = getTextFromAnyVar(fun -> stack -> thisVar);
-	trimStack(fun -> stack);
+	loadNow = getTextFromAnyVar(fun->stack->thisVar);
+	trimStack(fun->stack);
 
 	char *aaaaa = encodeFilename(loadNow);
 	delete[] loadNow;
@@ -298,15 +298,15 @@ builtIn(saveGame) {
 	loadNow = joinStrings(":", aaaaa);
 	delete[] aaaaa;
 
-	setVariable(fun -> reg, SVT_INT, 0);
+	setVariable(fun->reg, SVT_INT, 0);
 	saverFunc = fun;
 	return BR_KEEP_AND_PAUSE;
 }
 
 builtIn(fileExists) {
 	UNUSEDALL
-	loadNow = getTextFromAnyVar(fun -> stack -> thisVar);
-	trimStack(fun -> stack);
+	loadNow = getTextFromAnyVar(fun->stack->thisVar);
+	trimStack(fun->stack);
 	char *aaaaa = encodeFilename(loadNow);
 	delete loadNow;
 	if (failSecurityCheck(aaaaa)) return BR_ERROR;
@@ -328,7 +328,7 @@ builtIn(fileExists) {
 	}
 #endif
 	// Return value
-	setVariable(fun -> reg, SVT_INT, 0/*(fp != NULL)*/);//TODO:false value
+	setVariable(fun->reg, SVT_INT, 0/*(fp != NULL)*/);//TODO:false value
 #if 0
 	if (fp) fclose(fp);
 	delete[] aaaaa;
@@ -339,24 +339,23 @@ builtIn(fileExists) {
 
 builtIn(loadGame) {
 	UNUSEDALL
-	char *aaaaa = getTextFromAnyVar(fun -> stack -> thisVar);
-	trimStack(fun -> stack);
+	char *aaaaa = getTextFromAnyVar(fun->stack->thisVar);
+	trimStack(fun->stack);
 	loadNow = encodeFilename(aaaaa);
 	delete aaaaa;
 
 	if (frozenStuff) {
 		fatal("Can't load a saved game while the engine is frozen");
 	}
-#if ALLOW_FILE
 	if (failSecurityCheck(loadNow)) return BR_ERROR;
-	FILE *fp = fopen(loadNow, "rb");
-	if (fp) {
-		fclose(fp);
+	Common::File fd;
+	if (fd.open(loadNow)) {
+		fd.close();
 		return BR_KEEP_AND_PAUSE;
 	}
 	delete loadNow;
 	loadNow = NULL;
-#endif
+
 	return BR_CONTINUE;
 }
 
@@ -373,14 +372,14 @@ builtIn(blankScreen) {
 builtIn(blankArea) {
 	UNUSEDALL
 	int x1, y1, x2, y2;
-	if (!getValueType(y2, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(x2, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(y1, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(x1, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(y2, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(x2, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(y1, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(x1, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	blankScreen(x1, y1, x2, y2);
 	return BR_CONTINUE;
 }
@@ -394,12 +393,12 @@ builtIn(darkBackground) {
 builtIn(addOverlay) {
 	UNUSEDALL
 	int fileNumber, xPos, yPos;
-	if (!getValueType(yPos, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(xPos, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(yPos, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(xPos, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	loadBackDrop(fileNumber, xPos, yPos);
 	return BR_CONTINUE;
 }
@@ -407,12 +406,12 @@ builtIn(addOverlay) {
 builtIn(mixOverlay) {
 	UNUSEDALL
 	int fileNumber, xPos, yPos;
-	if (!getValueType(yPos, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(xPos, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(yPos, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(xPos, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	mixBackDrop(fileNumber, xPos, yPos);
 	return BR_CONTINUE;
 }
@@ -420,12 +419,12 @@ builtIn(mixOverlay) {
 builtIn(pasteImage) {
 	UNUSEDALL
 	int x, y;
-	if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	personaAnimation *pp = getAnimationFromVar(fun -> stack -> thisVar);
-	trimStack(fun -> stack);
+	if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	personaAnimation *pp = getAnimationFromVar(fun->stack->thisVar);
+	trimStack(fun->stack);
 	if (pp == NULL) return BR_CONTINUE;
 
 	pasteCursor(x, y, pp);
@@ -438,10 +437,10 @@ builtIn(pasteImage) {
 builtIn(setSceneDimensions) {
 	UNUSEDALL
 	int x, y;
-	if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	if (resizeBackdrop(x, y)) {
 		blankScreen(0, 0, x, y);
 		return BR_CONTINUE;
@@ -452,10 +451,10 @@ builtIn(setSceneDimensions) {
 
 builtIn(aimCamera) {
 	UNUSEDALL
-	if (!getValueType(cameraY, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(cameraX, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(cameraY, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(cameraX, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 
 	cameraX -= (float)(winWidth >> 1) / cameraZoom;
 	cameraY -= (float)(winHeight >> 1) / cameraZoom;
@@ -471,8 +470,8 @@ builtIn(aimCamera) {
 builtIn(zoomCamera) {
 	UNUSEDALL
 	int z;
-	if (!getValueType(z, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(z, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 
 	input.mouseX = input.mouseX * cameraZoom;
 	input.mouseY = input.mouseY * cameraZoom;
@@ -507,8 +506,8 @@ builtIn(pickOne) {
 
 	// Return value
 	while (numParams --) {
-		if (i == numParams) copyVariable(fun -> stack -> thisVar, fun -> reg);
-		trimStack(fun -> stack);
+		if (i == numParams) copyVariable(fun->stack->thisVar, fun->reg);
+		trimStack(fun->stack);
 	}
 	return BR_CONTINUE;
 }
@@ -521,12 +520,12 @@ builtIn(substring) {
 
 	//debugOut ("BUILTIN: substring\n");
 
-	if (!getValueType(length, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(start, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	wholeString = getTextFromAnyVar(fun -> stack -> thisVar);
-	trimStack(fun -> stack);
+	if (!getValueType(length, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(start, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	wholeString = getTextFromAnyVar(fun->stack->thisVar);
+	trimStack(fun->stack);
 
 	if (u8_strlen(wholeString) < start + length) {
 		length = u8_strlen(wholeString) - start;
@@ -549,37 +548,37 @@ builtIn(substring) {
 	memcpy(newString, wholeString + startoffset, endoffset - startoffset);
 	newString[endoffset - startoffset] = 0;
 
-	makeTextVar(fun -> reg, newString);
+	makeTextVar(fun->reg, newString);
 	delete newString;
 	return BR_CONTINUE;
 }
 
 builtIn(stringLength) {
 	UNUSEDALL
-	char *newText = getTextFromAnyVar(fun -> stack -> thisVar);
-	trimStack(fun -> stack);
-	setVariable(fun -> reg, SVT_INT, stringLength(newText));
+	char *newText = getTextFromAnyVar(fun->stack->thisVar);
+	trimStack(fun->stack);
+	setVariable(fun->reg, SVT_INT, stringLength(newText));
 	delete[] newText;
 	return BR_CONTINUE;
 }
 
 builtIn(newStack) {
 	UNUSEDALL
-	unlinkVar(fun -> reg);
+	unlinkVar(fun->reg);
 
 	// Return value
-	fun -> reg.varType = SVT_STACK;
-	fun -> reg.varData.theStack = new stackHandler;
-	if (!checkNew(fun -> reg.varData.theStack)) return BR_ERROR;
-	fun -> reg.varData.theStack -> first = NULL;
-	fun -> reg.varData.theStack -> last = NULL;
-	fun -> reg.varData.theStack -> timesUsed = 1;
+	fun->reg.varType = SVT_STACK;
+	fun->reg.varData.theStack = new stackHandler;
+	if (!checkNew(fun->reg.varData.theStack)) return BR_ERROR;
+	fun->reg.varData.theStack->first = NULL;
+	fun->reg.varData.theStack->last = NULL;
+	fun->reg.varData.theStack->timesUsed = 1;
 	while (numParams --) {
-		if (!addVarToStack(fun -> stack -> thisVar, fun -> reg.varData.theStack -> first)) return BR_ERROR;
-		if (fun -> reg.varData.theStack -> last == NULL) {
-			fun -> reg.varData.theStack -> last = fun -> reg.varData.theStack -> first;
+		if (!addVarToStack(fun->stack->thisVar, fun->reg.varData.theStack->first)) return BR_ERROR;
+		if (fun->reg.varData.theStack->last == NULL) {
+			fun->reg.varData.theStack->last = fun->reg.varData.theStack->first;
 		}
-		trimStack(fun -> stack);
+		trimStack(fun->stack);
 	}
 	return BR_CONTINUE;
 }
@@ -589,17 +588,17 @@ builtIn(newStack) {
 
 builtIn(stackSize) {
 	UNUSEDALL
-	switch (fun -> stack -> thisVar.varType) {
+	switch (fun->stack->thisVar.varType) {
 	case SVT_STACK:
 		// Return value
-		setVariable(fun -> reg, SVT_INT, stackSize(fun -> stack -> thisVar.varData.theStack));
-		trimStack(fun -> stack);
+		setVariable(fun->reg, SVT_INT, stackSize(fun->stack->thisVar.varData.theStack));
+		trimStack(fun->stack);
 		return BR_CONTINUE;
 
 	case SVT_FASTARRAY:
 		// Return value
-		setVariable(fun -> reg, SVT_INT, fun -> stack -> thisVar.varData.fastArray -> size);
-		trimStack(fun -> stack);
+		setVariable(fun->reg, SVT_INT, fun->stack->thisVar.varData.fastArray->size);
+		trimStack(fun->stack);
 		return BR_CONTINUE;
 
 	default:
@@ -611,147 +610,147 @@ builtIn(stackSize) {
 
 builtIn(copyStack) {
 	UNUSEDALL
-	if (fun -> stack -> thisVar.varType != SVT_STACK) {
+	if (fun->stack->thisVar.varType != SVT_STACK) {
 		fatal("Parameter isn't a stack.");
 		return BR_ERROR;
 	}
 	// Return value
-	if (!copyStack(fun -> stack -> thisVar, fun -> reg)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!copyStack(fun->stack->thisVar, fun->reg)) return BR_ERROR;
+	trimStack(fun->stack);
 	return BR_CONTINUE;
 }
 
 builtIn(pushToStack) {
 	UNUSEDALL
-	if (fun -> stack -> next -> thisVar.varType != SVT_STACK) {
+	if (fun->stack->next->thisVar.varType != SVT_STACK) {
 		fatal("Parameter isn't a stack");
 		return BR_ERROR;
 	}
 
-	if (!addVarToStack(fun -> stack -> thisVar, fun -> stack -> next -> thisVar.varData.theStack -> first))
+	if (!addVarToStack(fun->stack->thisVar, fun->stack->next->thisVar.varData.theStack->first))
 		return BR_ERROR;
 
-	if (fun -> stack -> next -> thisVar.varData.theStack -> first -> next == NULL)
-		fun -> stack -> next -> thisVar.varData.theStack -> last = fun -> stack -> next -> thisVar.varData.theStack -> first;
+	if (fun->stack->next->thisVar.varData.theStack->first->next == NULL)
+		fun->stack->next->thisVar.varData.theStack->last = fun->stack->next->thisVar.varData.theStack->first;
 
-	trimStack(fun -> stack);
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
+	trimStack(fun->stack);
 	return BR_CONTINUE;
 }
 
 builtIn(enqueue) {
 	UNUSEDALL
-	if (fun -> stack -> next -> thisVar.varType != SVT_STACK) {
+	if (fun->stack->next->thisVar.varType != SVT_STACK) {
 		fatal("Parameter isn't a stack");
 		return BR_ERROR;
 	}
 
-	if (fun -> stack -> next -> thisVar.varData.theStack -> first == NULL) {
-		if (!addVarToStack(fun -> stack -> thisVar, fun -> stack -> next -> thisVar.varData.theStack -> first))
+	if (fun->stack->next->thisVar.varData.theStack->first == NULL) {
+		if (!addVarToStack(fun->stack->thisVar, fun->stack->next->thisVar.varData.theStack->first))
 			return BR_ERROR;
 
-		fun -> stack -> next -> thisVar.varData.theStack -> last = fun -> stack -> next -> thisVar.varData.theStack -> first;
+		fun->stack->next->thisVar.varData.theStack->last = fun->stack->next->thisVar.varData.theStack->first;
 	} else {
-		if (!addVarToStack(fun -> stack -> thisVar,
-		                    fun -> stack -> next -> thisVar.varData.theStack -> last -> next))
+		if (!addVarToStack(fun->stack->thisVar,
+		                    fun->stack->next->thisVar.varData.theStack->last->next))
 			return BR_ERROR;
-		fun -> stack -> next -> thisVar.varData.theStack -> last = fun -> stack -> next -> thisVar.varData.theStack -> last -> next;
+		fun->stack->next->thisVar.varData.theStack->last = fun->stack->next->thisVar.varData.theStack->last->next;
 	}
 
-	trimStack(fun -> stack);
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
+	trimStack(fun->stack);
 	return BR_CONTINUE;
 }
 
 builtIn(deleteFromStack) {
 	UNUSEDALL
-	if (fun -> stack -> next -> thisVar.varType != SVT_STACK) {
+	if (fun->stack->next->thisVar.varType != SVT_STACK) {
 		fatal("Parameter isn't a stack.");
 		return BR_ERROR;
 	}
 
 	// Return value
-	setVariable(fun -> reg, SVT_INT,
-	            deleteVarFromStack(fun -> stack -> thisVar,
-	                               fun -> stack -> next -> thisVar.varData.theStack -> first, false));
+	setVariable(fun->reg, SVT_INT,
+	            deleteVarFromStack(fun->stack->thisVar,
+	                               fun->stack->next->thisVar.varData.theStack->first, false));
 
 	// Horrible hacking because 'last' value might now be wrong!
 	fun->stack->next->thisVar.varData.theStack->last = stackFindLast(fun->stack->next->thisVar.varData.theStack->first);
 
-	trimStack(fun -> stack);
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
+	trimStack(fun->stack);
 	return BR_CONTINUE;
 }
 
 builtIn(deleteAllFromStack) {
 	UNUSEDALL
-	if (fun -> stack -> next -> thisVar.varType != SVT_STACK) {
+	if (fun->stack->next->thisVar.varType != SVT_STACK) {
 		fatal("Parameter isn't a stack.");
 		return BR_ERROR;
 	}
 
 	// Return value
-	setVariable(fun -> reg, SVT_INT,
-	            deleteVarFromStack(fun -> stack -> thisVar,
-	                               fun -> stack -> next -> thisVar.varData.theStack -> first, true));
+	setVariable(fun->reg, SVT_INT,
+	            deleteVarFromStack(fun->stack->thisVar,
+	                               fun->stack->next->thisVar.varData.theStack->first, true));
 
 	// Horrible hacking because 'last' value might now be wrong!
 	fun->stack->next->thisVar.varData.theStack->last = stackFindLast(fun->stack->next->thisVar.varData.theStack->first);
 
-	trimStack(fun -> stack);
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
+	trimStack(fun->stack);
 	return BR_CONTINUE;
 }
 
 builtIn(popFromStack) {
 	UNUSEDALL
-	if (fun -> stack -> thisVar.varType != SVT_STACK) {
+	if (fun->stack->thisVar.varType != SVT_STACK) {
 		fatal("Parameter isn't a stack.");
 		return BR_ERROR;
 	}
-	if (fun -> stack -> thisVar.varData.theStack -> first == NULL) {
+	if (fun->stack->thisVar.varData.theStack->first == NULL) {
 		fatal("The stack's empty.");
 		return BR_ERROR;
 	}
 
 	// Return value
-	copyVariable(fun -> stack -> thisVar.varData.theStack -> first -> thisVar, fun -> reg);
-	trimStack(fun -> stack -> thisVar.varData.theStack -> first);
-	trimStack(fun -> stack);
+	copyVariable(fun->stack->thisVar.varData.theStack->first->thisVar, fun->reg);
+	trimStack(fun->stack->thisVar.varData.theStack->first);
+	trimStack(fun->stack);
 	return BR_CONTINUE;
 }
 
 builtIn(peekStart) {
 	UNUSEDALL
-	if (fun -> stack -> thisVar.varType != SVT_STACK) {
+	if (fun->stack->thisVar.varType != SVT_STACK) {
 		fatal("Parameter isn't a stack.");
 		return BR_ERROR;
 	}
-	if (fun -> stack -> thisVar.varData.theStack -> first == NULL) {
+	if (fun->stack->thisVar.varData.theStack->first == NULL) {
 		fatal("The stack's empty.");
 		return BR_ERROR;
 	}
 
 	// Return value
-	copyVariable(fun -> stack -> thisVar.varData.theStack -> first -> thisVar, fun -> reg);
-	trimStack(fun -> stack);
+	copyVariable(fun->stack->thisVar.varData.theStack->first->thisVar, fun->reg);
+	trimStack(fun->stack);
 	return BR_CONTINUE;
 }
 
 builtIn(peekEnd) {
 	UNUSEDALL
-	if (fun -> stack -> thisVar.varType != SVT_STACK) {
+	if (fun->stack->thisVar.varType != SVT_STACK) {
 		fatal("Parameter isn't a stack.");
 		return BR_ERROR;
 	}
-	if (fun -> stack -> thisVar.varData.theStack -> first == NULL) {
+	if (fun->stack->thisVar.varData.theStack->first == NULL) {
 		fatal("The stack's empty.");
 		return BR_ERROR;
 	}
 
 	// Return value
-	copyVariable(fun -> stack -> thisVar.varData.theStack -> last -> thisVar, fun -> reg);
-	trimStack(fun -> stack);
+	copyVariable(fun->stack->thisVar.varData.theStack->last->thisVar, fun->reg);
+	trimStack(fun->stack);
 	return BR_CONTINUE;
 }
 
@@ -759,22 +758,22 @@ builtIn(random) {
 	UNUSEDALL
 	int num;
 
-	if (!getValueType(num, SVT_INT, fun -> stack -> thisVar))
+	if (!getValueType(num, SVT_INT, fun->stack->thisVar))
 		return BR_ERROR;
 
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
 	if (num <= 0) num = 1;
-	setVariable(fun -> reg, SVT_INT, 0 /*rand() % num*/); //TODO:false value
+	setVariable(fun->reg, SVT_INT, 0 /*rand() % num*/); //TODO:false value
 	return BR_CONTINUE;
 }
 
 static bool getRGBParams(int &red, int &green, int &blue, loadedFunction *fun) {
-	if (!getValueType(blue, SVT_INT, fun -> stack -> thisVar)) return false;
-	trimStack(fun -> stack);
-	if (!getValueType(green, SVT_INT, fun -> stack -> thisVar)) return false;
-	trimStack(fun -> stack);
-	if (!getValueType(red, SVT_INT, fun -> stack -> thisVar)) return false;
-	trimStack(fun -> stack);
+	if (!getValueType(blue, SVT_INT, fun->stack->thisVar)) return false;
+	trimStack(fun->stack);
+	if (!getValueType(green, SVT_INT, fun->stack->thisVar)) return false;
+	trimStack(fun->stack);
+	if (!getValueType(red, SVT_INT, fun->stack->thisVar)) return false;
+	trimStack(fun->stack);
 	return true;
 }
 
@@ -819,7 +818,7 @@ builtIn(setBlankColour) {
 		return BR_ERROR;
 
 	currentBlankColour = makeColour(red & 255, green & 255, blue & 255);
-	setVariable(fun -> reg, SVT_INT, 1);
+	setVariable(fun->reg, SVT_INT, 1);
 	return BR_CONTINUE;
 }
 
@@ -833,7 +832,7 @@ builtIn(setBurnColour) {
 	currentBurnR = red;
 	currentBurnG = green;
 	currentBurnB = blue;
-	setVariable(fun -> reg, SVT_INT, 1);
+	setVariable(fun->reg, SVT_INT, 1);
 	return BR_CONTINUE;
 }
 
@@ -841,16 +840,16 @@ builtIn(setBurnColour) {
 builtIn(setFont) {
 	UNUSEDALL
 	int fileNumber, newHeight;
-	if (!getValueType(newHeight, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	if (!getValueType(newHeight, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
 	//              newDebug ("  Height:", newHeight);
-	trimStack(fun -> stack);
-	char *newText = getTextFromAnyVar(fun -> stack -> thisVar);
+	trimStack(fun->stack);
+	char *newText = getTextFromAnyVar(fun->stack->thisVar);
 	if (!newText) return BR_ERROR;
 	//              newDebug ("  Character supported:", newText);
-	trimStack(fun -> stack);
-	if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
 	//              newDebug ("  File:", fileNumber);
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
 	if (!loadFont(fileNumber, newText, newHeight)) return BR_ERROR;
 	//              newDebug ("  Done!");
 	delete newText;
@@ -860,25 +859,25 @@ builtIn(setFont) {
 
 builtIn(inFont) {
 	UNUSEDALL
-	char *newText = getTextFromAnyVar(fun -> stack -> thisVar);
+	char *newText = getTextFromAnyVar(fun->stack->thisVar);
 	if (!newText) return BR_ERROR;
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
 
 	// Return value
 
-	setVariable(fun -> reg, SVT_INT, isInFont(newText));
+	setVariable(fun->reg, SVT_INT, isInFont(newText));
 	return BR_CONTINUE;
 }
 
 builtIn(pasteString) {
 	UNUSEDALL
-	char *newText = getTextFromAnyVar(fun -> stack -> thisVar);
-	trimStack(fun -> stack);
+	char *newText = getTextFromAnyVar(fun->stack->thisVar);
+	trimStack(fun->stack);
 	int y, x;
-	if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	if (x == IN_THE_CENTRE) x = (winWidth - stringWidth(newText)) >> 1;
 	fixFont(pastePalette);
 	pasteStringToBackdrop(newText, x, y, pastePalette);
@@ -894,12 +893,12 @@ builtIn(anim) {
 	}
 
 	// First store the frame numbers and take 'em off the stack
-	personaAnimation *ba = createPersonaAnim(numParams - 1, fun -> stack);
+	personaAnimation *ba = createPersonaAnim(numParams - 1, fun->stack);
 
 	// Only remaining paramter is the file number
 	int fileNumber;
-	if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 
 	// Load the required sprite bank
 	loadedSpriteBank *sprBanky = loadBankForAnim(fileNumber);
@@ -907,7 +906,7 @@ builtIn(anim) {
 	setBankFile(ba, sprBanky);
 
 	// Return value
-	newAnimationVariable(fun -> reg, ba);
+	newAnimationVariable(fun->reg, ba);
 
 	return BR_CONTINUE;
 }
@@ -916,32 +915,32 @@ builtIn(costume) {
 	UNUSEDALL
 	persona *newPersona = new persona;
 	if (!checkNew(newPersona)) return BR_ERROR;
-	newPersona -> numDirections = numParams / 3;
-	if (numParams == 0 || newPersona -> numDirections * 3 != numParams) {
+	newPersona->numDirections = numParams / 3;
+	if (numParams == 0 || newPersona->numDirections * 3 != numParams) {
 		fatal("Illegal number of parameters (should be greater than 0 and divisible by 3)");
 		return BR_ERROR;
 	}
 	int iii;
-	newPersona -> animation = new personaAnimation * [numParams];
-	if (!checkNew(newPersona -> animation)) return BR_ERROR;
+	newPersona->animation = new personaAnimation * [numParams];
+	if (!checkNew(newPersona->animation)) return BR_ERROR;
 	for (iii = numParams - 1; iii >= 0; iii --) {
-		newPersona -> animation[iii] = getAnimationFromVar(fun -> stack -> thisVar);
-		trimStack(fun -> stack);
+		newPersona->animation[iii] = getAnimationFromVar(fun->stack->thisVar);
+		trimStack(fun->stack);
 	}
 
 	// Return value
-	newCostumeVariable(fun -> reg, newPersona);
+	newCostumeVariable(fun->reg, newPersona);
 	return BR_CONTINUE;
 }
 
 builtIn(launch) {
 	UNUSEDALL
-	char *newTextA = getTextFromAnyVar(fun -> stack -> thisVar);
+	char *newTextA = getTextFromAnyVar(fun->stack->thisVar);
 	if (!newTextA) return BR_ERROR;
 
 	char *newText = encodeFilename(newTextA);
 
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
 	if (newTextA[0] == 'h' &&
 	        newTextA[1] == 't' &&
 	        newTextA[2] == 't' &&
@@ -963,7 +962,7 @@ builtIn(launch) {
 	}
 	delete newTextA;
 	setGraphicsWindow(false);
-	setVariable(fun -> reg, SVT_INT, 1);
+	setVariable(fun->reg, SVT_INT, 1);
 	launchResult = &fun->reg;
 
 	return BR_KEEP_AND_PAUSE;
@@ -972,11 +971,11 @@ builtIn(launch) {
 builtIn(pause) {
 	UNUSEDALL
 	int theTime;
-	if (!getValueType(theTime, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(theTime, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	if (theTime > 0) {
-		fun -> timeLeft = theTime - 1;
-		fun -> isSpeech = false;
+		fun->timeLeft = theTime - 1;
+		fun->isSpeech = false;
 		return BR_KEEP_AND_PAUSE;
 	}
 	return BR_CONTINUE;
@@ -991,19 +990,19 @@ builtIn(completeTimers) {
 builtIn(callEvent) {
 	UNUSEDALL
 	int obj1, obj2;
-	if (!getValueType(obj2, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(obj1, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(obj2, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(obj1, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 
 	int fNum = getCombinationFunction(obj1, obj2);
 
 	// Return value
 	if (fNum) {
-		setVariable(fun -> reg, SVT_FUNC, fNum);
+		setVariable(fun->reg, SVT_FUNC, fNum);
 		return BR_CALLAFUNC;
 	}
-	setVariable(fun -> reg, SVT_INT, 0);
+	setVariable(fun->reg, SVT_INT, 0);
 	return BR_CONTINUE;
 }
 
@@ -1030,19 +1029,19 @@ builtIn(quitGame) {
 // The old movie functions are deprecated and does nothing.
 builtIn(_rem_movieStart) {
 	UNUSEDALL
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
 	return BR_CONTINUE;
 }
 
 builtIn(_rem_movieAbort) {
 	UNUSEDALL
-	setVariable(fun -> reg, SVT_INT, 0);
+	setVariable(fun->reg, SVT_INT, 0);
 	return BR_CONTINUE;
 }
 
 builtIn(_rem_moviePlaying) {
 	UNUSEDALL
-	setVariable(fun -> reg, SVT_INT, 0);
+	setVariable(fun->reg, SVT_INT, 0);
 	return BR_CONTINUE;
 }
 
@@ -1052,12 +1051,12 @@ builtIn(playMovie) {
 
 	if (movieIsPlaying) return BR_PAUSE;
 
-	if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 
 	r = playMovie(fileNumber);
 
-	setVariable(fun -> reg, SVT_INT, r);
+	setVariable(fun->reg, SVT_INT, r);
 
 	if (r && (!fun->next)) {
 		restartFunction(fun);
@@ -1072,7 +1071,7 @@ builtIn(stopMovie) {
 
 	r = stopMovie();
 
-	setVariable(fun -> reg, SVT_INT, 0);
+	setVariable(fun->reg, SVT_INT, 0);
 	return BR_CONTINUE;
 }
 
@@ -1082,7 +1081,7 @@ builtIn(pauseMovie) {
 
 	r = pauseMovie();
 
-	setVariable(fun -> reg, SVT_INT, 0);
+	setVariable(fun->reg, SVT_INT, 0);
 	return BR_CONTINUE;
 }
 
@@ -1093,12 +1092,12 @@ builtIn(pauseMovie) {
 builtIn(startMusic) {
 	UNUSEDALL
 	int fromTrack, musChan, fileNumber;
-	if (!getValueType(fromTrack, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(musChan, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(fromTrack, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(musChan, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	if (!playMOD(fileNumber, musChan, fromTrack)) return BR_CONTINUE;  //BR_ERROR;
 	return BR_CONTINUE;
 }
@@ -1106,8 +1105,8 @@ builtIn(startMusic) {
 builtIn(stopMusic) {
 	UNUSEDALL
 	int v;
-	if (!getValueType(v, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(v, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	stopMOD(v);
 	return BR_CONTINUE;
 }
@@ -1115,10 +1114,10 @@ builtIn(stopMusic) {
 builtIn(setMusicVolume) {
 	UNUSEDALL
 	int musChan, v;
-	if (!getValueType(v, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(musChan, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(v, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(musChan, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	setMusicVolume(musChan, v);
 	return BR_CONTINUE;
 }
@@ -1126,8 +1125,8 @@ builtIn(setMusicVolume) {
 builtIn(setDefaultMusicVolume) {
 	UNUSEDALL
 	int v;
-	if (!getValueType(v, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(v, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	setDefaultMusicVolume(v);
 	return BR_CONTINUE;
 }
@@ -1135,8 +1134,8 @@ builtIn(setDefaultMusicVolume) {
 builtIn(playSound) {
 	UNUSEDALL
 	int fileNumber;
-	if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	if (!startSound(fileNumber, false)) return BR_CONTINUE;    // Was BR_ERROR
 	return BR_CONTINUE;
 }
@@ -1149,8 +1148,8 @@ builtIn(loopSound) {
 		return BR_ERROR;
 	} else if (numParams < 2) {
 
-		if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
-		trimStack(fun -> stack);
+		if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+		trimStack(fun->stack);
 		if (!startSound(fileNumber, true)) return BR_CONTINUE;     // Was BR_ERROR
 		return BR_CONTINUE;
 	} else {
@@ -1162,12 +1161,12 @@ builtIn(loopSound) {
 
 		// Should we loop?
 		if (fun->stack->thisVar.varType != SVT_FILE) {
-			getValueType(doLoop, SVT_INT, fun -> stack -> thisVar);
-			trimStack(fun -> stack);
+			getValueType(doLoop, SVT_INT, fun->stack->thisVar);
+			trimStack(fun->stack);
 			numParams--;
 		}
 		while (numParams) {
-			if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) {
+			if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) {
 				fatal("Illegal parameter given built-in function loopSound().");
 				return BR_ERROR;
 			}
@@ -1198,8 +1197,8 @@ builtIn(loopSound) {
 builtIn(stopSound) {
 	UNUSEDALL
 	int v;
-	if (!getValueType(v, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(v, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	huntKillSound(v);
 	return BR_CONTINUE;
 }
@@ -1207,8 +1206,8 @@ builtIn(stopSound) {
 builtIn(setDefaultSoundVolume) {
 	UNUSEDALL
 	int v;
-	if (!getValueType(v, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(v, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	setDefaultSoundVolume(v);
 	return BR_CONTINUE;
 }
@@ -1216,10 +1215,10 @@ builtIn(setDefaultSoundVolume) {
 builtIn(setSoundVolume) {
 	UNUSEDALL
 	int musChan, v;
-	if (!getValueType(v, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(musChan, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(v, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(musChan, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	setSoundVolume(musChan, v);
 	return BR_CONTINUE;
 }
@@ -1228,12 +1227,12 @@ builtIn(setSoundVolume) {
 builtIn(setSoundLoopPoints) {
 	UNUSEDALL
 	int musChan, theEnd, theStart;
-	if (!getValueType(theEnd, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(theStart, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(musChan, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(theEnd, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(theStart, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(musChan, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	setSoundLoop(musChan, theStart, theEnd);
 	return BR_CONTINUE;
 }
@@ -1243,13 +1242,13 @@ builtIn(setSoundLoopPoints) {
 
 builtIn(setFloor) {
 	UNUSEDALL
-	if (fun -> stack -> thisVar.varType == SVT_FILE) {
+	if (fun->stack->thisVar.varType == SVT_FILE) {
 		int v;
-		getValueType(v, SVT_FILE, fun -> stack -> thisVar);
-		trimStack(fun -> stack);
+		getValueType(v, SVT_FILE, fun->stack->thisVar);
+		trimStack(fun->stack);
 		if (!setFloor(v)) return BR_ERROR;
 	} else {
-		trimStack(fun -> stack);
+		trimStack(fun->stack);
 		setFloorNull();
 	}
 	return BR_CONTINUE;
@@ -1263,13 +1262,13 @@ builtIn(showFloor) {
 
 builtIn(setZBuffer) {
 	UNUSEDALL
-	if (fun -> stack -> thisVar.varType == SVT_FILE) {
+	if (fun->stack->thisVar.varType == SVT_FILE) {
 		int v;
-		getValueType(v, SVT_FILE, fun -> stack -> thisVar);
-		trimStack(fun -> stack);
+		getValueType(v, SVT_FILE, fun->stack->thisVar);
+		trimStack(fun->stack);
 		if (!setZBuffer(v)) return BR_ERROR;
 	} else {
-		trimStack(fun -> stack);
+		trimStack(fun->stack);
 		killZBuffer();
 	}
 	return BR_CONTINUE;
@@ -1279,22 +1278,22 @@ builtIn(setLightMap) {
 	UNUSEDALL
 	switch (numParams) {
 	case 2:
-		if (!getValueType(lightMapMode, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-		trimStack(fun -> stack);
+		if (!getValueType(lightMapMode, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+		trimStack(fun->stack);
 		lightMapMode %= LIGHTMAPMODE_NUM;
 	// No break;
 
 	case 1:
-		if (fun -> stack -> thisVar.varType == SVT_FILE) {
+		if (fun->stack->thisVar.varType == SVT_FILE) {
 			int v;
-			getValueType(v, SVT_FILE, fun -> stack -> thisVar);
-			trimStack(fun -> stack);
+			getValueType(v, SVT_FILE, fun->stack->thisVar);
+			trimStack(fun->stack);
 			if (!loadLightMap(v)) return BR_ERROR;
-			setVariable(fun -> reg, SVT_INT, 1);
+			setVariable(fun->reg, SVT_INT, 1);
 		} else {
-			trimStack(fun -> stack);
+			trimStack(fun->stack);
 			killLightMap();
-			setVariable(fun -> reg, SVT_INT, 0);
+			setVariable(fun->reg, SVT_INT, 0);
 		}
 		break;
 
@@ -1311,8 +1310,8 @@ builtIn(setLightMap) {
 
 builtIn(setSpeechMode) {
 	UNUSEDALL
-	if (!getValueType(speechMode, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(speechMode, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	if (speechMode < 0 || speechMode > 2) {
 		fatal("Valid parameters are be SPEECHANDTEXT, SPEECHONLY or TEXTONLY");
 		return BR_ERROR;
@@ -1324,9 +1323,9 @@ builtIn(somethingSpeaking) {
 	UNUSEDALL
 	int i = isThereAnySpeechGoingOn();
 	if (i == -1) {
-		setVariable(fun -> reg, SVT_INT, 0);
+		setVariable(fun->reg, SVT_INT, 0);
 	} else {
-		setVariable(fun -> reg, SVT_OBJTYPE, i);
+		setVariable(fun->reg, SVT_OBJTYPE, i);
 	}
 	return BR_CONTINUE;
 }
@@ -1341,42 +1340,42 @@ builtIn(getOverObject) {
 	UNUSEDALL
 	if (overRegion)
 		// Return value
-		setVariable(fun -> reg, SVT_OBJTYPE, overRegion -> thisType -> objectNum);
+		setVariable(fun->reg, SVT_OBJTYPE, overRegion->thisType->objectNum);
 	else
 		// Return value
-		setVariable(fun -> reg, SVT_INT, 0);
+		setVariable(fun->reg, SVT_INT, 0);
 	return BR_CONTINUE;
 }
 
 builtIn(rename) {
 	UNUSEDALL
-	char *newText = getTextFromAnyVar(fun -> stack -> thisVar);
+	char *newText = getTextFromAnyVar(fun->stack->thisVar);
 	int objT;
 	if (!newText) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(objT, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
+	if (!getValueType(objT, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	objectType *o = findObjectType(objT);
-	delete o -> screenName;
-	o -> screenName = newText;
+	delete o->screenName;
+	o->screenName = newText;
 	return BR_CONTINUE;
 }
 
 builtIn(getObjectX) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 
 	onScreenPerson *pers = findPerson(objectNumber);
 	if (pers) {
-		setVariable(fun -> reg, SVT_INT, pers -> x);
+		setVariable(fun->reg, SVT_INT, pers->x);
 	} else {
 		screenRegion *la = getRegionForObject(objectNumber);
 		if (la) {
-			setVariable(fun -> reg, SVT_INT, la -> sX);
+			setVariable(fun->reg, SVT_INT, la->sX);
 		} else {
-			setVariable(fun -> reg, SVT_INT, 0);
+			setVariable(fun->reg, SVT_INT, 0);
 		}
 	}
 	return BR_CONTINUE;
@@ -1385,18 +1384,18 @@ builtIn(getObjectX) {
 builtIn(getObjectY) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 
 	onScreenPerson *pers = findPerson(objectNumber);
 	if (pers) {
-		setVariable(fun -> reg, SVT_INT, pers -> y);
+		setVariable(fun->reg, SVT_INT, pers->y);
 	} else {
 		screenRegion *la = getRegionForObject(objectNumber);
 		if (la) {
-			setVariable(fun -> reg, SVT_INT, la -> sY);
+			setVariable(fun->reg, SVT_INT, la->sY);
 		} else {
-			setVariable(fun -> reg, SVT_INT, 0);
+			setVariable(fun->reg, SVT_INT, 0);
 		}
 	}
 	return BR_CONTINUE;
@@ -1406,22 +1405,22 @@ builtIn(getObjectY) {
 builtIn(addScreenRegion) {
 	UNUSEDALL
 	int sX, sY, x1, y1, x2, y2, di, objectNumber;
-	if (!getValueType(di, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(sY, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(sX, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(y2, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(x2, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(y1, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(x1, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(di, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(sY, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(sX, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(y2, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(x2, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(y1, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(x1, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	if (addScreenRegion(x1, y1, x2, y2, sX, sY, di, objectNumber)) return BR_CONTINUE;
 	return BR_ERROR;
 
@@ -1430,8 +1429,8 @@ builtIn(addScreenRegion) {
 builtIn(removeScreenRegion) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	removeScreenRegion(objectNumber);
 	return BR_CONTINUE;
 }
@@ -1453,16 +1452,16 @@ builtIn(addCharacter) {
 	persona *p;
 	int x, y, objectNumber;
 
-	p = getCostumeFromVar(fun -> stack -> thisVar);
+	p = getCostumeFromVar(fun->stack->thisVar);
 	if (p == NULL) return BR_ERROR;
 
-	trimStack(fun -> stack);
-	if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
+	if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	if (addPerson(x, y, objectNumber, p)) return BR_CONTINUE;
 	return BR_ERROR;
 }
@@ -1470,8 +1469,8 @@ builtIn(addCharacter) {
 builtIn(hideCharacter) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	setShown(false, objectNumber);
 	return BR_CONTINUE;
 }
@@ -1479,8 +1478,8 @@ builtIn(hideCharacter) {
 builtIn(showCharacter) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	setShown(true, objectNumber);
 	return BR_CONTINUE;
 }
@@ -1495,36 +1494,36 @@ builtIn(removeAllCharacters) {
 builtIn(setCharacterDrawMode) {
 	UNUSEDALL
 	int obj, di;
-	if (!getValueType(di, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(di, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	setDrawMode(di, obj);
 	return BR_CONTINUE;
 }
 builtIn(setCharacterTransparency) {
 	UNUSEDALL
 	int obj, x;
-	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	setPersonTransparency(obj, x);
 	return BR_CONTINUE;
 }
 builtIn(setCharacterColourise) {
 	UNUSEDALL
 	int obj, r, g, b, mix;
-	if (!getValueType(mix, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(b, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(g, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(r, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(mix, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(b, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(g, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(r, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	setPersonColourise(obj, r, g, b, mix);
 	return BR_CONTINUE;
 }
@@ -1532,10 +1531,10 @@ builtIn(setCharacterColourise) {
 builtIn(setScale) {
 	UNUSEDALL
 	int val1, val2;
-	if (!getValueType(val2, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(val1, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(val2, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(val1, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	setScale((short int) val1, (short int) val2);
 	return BR_CONTINUE;
 }
@@ -1543,35 +1542,35 @@ builtIn(setScale) {
 builtIn(stopCharacter) {
 	UNUSEDALL
 	int obj;
-	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 
 	// Return value
-	setVariable(fun -> reg, SVT_INT, stopPerson(obj));
+	setVariable(fun->reg, SVT_INT, stopPerson(obj));
 	return BR_CONTINUE;
 }
 
 builtIn(pasteCharacter) {
 	UNUSEDALL
 	int obj;
-	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 
 	onScreenPerson *thisPerson = findPerson(obj);
 	if (thisPerson) {
 		personaAnimation *myAnim;
-		myAnim = thisPerson -> myAnim;
-		if (myAnim != thisPerson -> lastUsedAnim) {
-			thisPerson -> lastUsedAnim = myAnim;
-			thisPerson -> frameNum = 0;
-			thisPerson -> frameTick = myAnim -> frames[0].howMany;
+		myAnim = thisPerson->myAnim;
+		if (myAnim != thisPerson->lastUsedAnim) {
+			thisPerson->lastUsedAnim = myAnim;
+			thisPerson->frameNum = 0;
+			thisPerson->frameTick = myAnim->frames[0].howMany;
 		}
 
-		int fNum = myAnim -> frames[thisPerson -> frameNum].frameNum;
-		fixScaleSprite(thisPerson -> x, thisPerson -> y, myAnim -> theSprites -> bank.sprites[abs(fNum)], myAnim -> theSprites -> bank.myPalette, thisPerson, 0, 0, fNum < 0);
-		setVariable(fun -> reg, SVT_INT, 1);
+		int fNum = myAnim->frames[thisPerson->frameNum].frameNum;
+		fixScaleSprite(thisPerson->x, thisPerson->y, myAnim->theSprites->bank.sprites[abs(fNum)], myAnim->theSprites->bank.myPalette, thisPerson, 0, 0, fNum < 0);
+		setVariable(fun->reg, SVT_INT, 1);
 	} else {
-		setVariable(fun -> reg, SVT_INT, 0);
+		setVariable(fun->reg, SVT_INT, 0);
 	}
 	return BR_CONTINUE;
 }
@@ -1579,24 +1578,24 @@ builtIn(pasteCharacter) {
 builtIn(animate) {
 	UNUSEDALL
 	int obj;
-	personaAnimation *pp = getAnimationFromVar(fun -> stack -> thisVar);
+	personaAnimation *pp = getAnimationFromVar(fun->stack->thisVar);
 	if (pp == NULL) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	animatePerson(obj, pp);
-	setVariable(fun -> reg, SVT_INT, timeForAnim(pp));
+	setVariable(fun->reg, SVT_INT, timeForAnim(pp));
 	return BR_CONTINUE;
 }
 
 builtIn(setCostume) {
 	UNUSEDALL
 	int obj;
-	persona *pp = getCostumeFromVar(fun -> stack -> thisVar);
+	persona *pp = getCostumeFromVar(fun->stack->thisVar);
 	if (pp == NULL) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	animatePerson(obj, pp);
 	return BR_CONTINUE;
 }
@@ -1604,52 +1603,52 @@ builtIn(setCostume) {
 builtIn(floatCharacter) {
 	UNUSEDALL
 	int obj, di;
-	if (!getValueType(di, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	setVariable(fun -> reg, SVT_INT, floatCharacter(di, obj));
+	if (!getValueType(di, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	setVariable(fun->reg, SVT_INT, floatCharacter(di, obj));
 	return BR_CONTINUE;
 }
 
 builtIn(setCharacterWalkSpeed) {
 	UNUSEDALL
 	int obj, di;
-	if (!getValueType(di, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	setVariable(fun -> reg, SVT_INT, setCharacterWalkSpeed(di, obj));
+	if (!getValueType(di, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	setVariable(fun->reg, SVT_INT, setCharacterWalkSpeed(di, obj));
 	return BR_CONTINUE;
 }
 
 builtIn(turnCharacter) {
 	UNUSEDALL
 	int obj, di;
-	if (!getValueType(di, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	setVariable(fun -> reg, SVT_INT, turnPersonToFace(obj, di));
+	if (!getValueType(di, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	setVariable(fun->reg, SVT_INT, turnPersonToFace(obj, di));
 	return BR_CONTINUE;
 }
 
 builtIn(setCharacterExtra) {
 	UNUSEDALL
 	int obj, di;
-	if (!getValueType(di, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	setVariable(fun -> reg, SVT_INT, setPersonExtra(obj, di));
+	if (!getValueType(di, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	setVariable(fun->reg, SVT_INT, setPersonExtra(obj, di));
 	return BR_CONTINUE;
 }
 
 builtIn(removeCharacter) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	removeOneCharacter(objectNumber);
 	return BR_CONTINUE;
 }
@@ -1659,12 +1658,12 @@ static builtReturn moveChr(int numParams, loadedFunction *fun, bool force, bool
 	case 3: {
 		int x, y, objectNumber;
 
-		if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-		trimStack(fun -> stack);
-		if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-		trimStack(fun -> stack);
-		if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-		trimStack(fun -> stack);
+		if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+		trimStack(fun->stack);
+		if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+		trimStack(fun->stack);
+		if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+		trimStack(fun->stack);
 
 		if (force) {
 			if (forceWalkingPerson(x, y, objectNumber, fun, -1)) return BR_PAUSE;
@@ -1680,19 +1679,19 @@ static builtReturn moveChr(int numParams, loadedFunction *fun, bool force, bool
 		int toObj, objectNumber;
 		screenRegion *reggie;
 
-		if (!getValueType(toObj, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-		trimStack(fun -> stack);
-		if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-		trimStack(fun -> stack);
+		if (!getValueType(toObj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+		trimStack(fun->stack);
+		if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+		trimStack(fun->stack);
 		reggie = getRegionForObject(toObj);
 		if (reggie == NULL) return BR_CONTINUE;
 
 		if (force) {
-			if (forceWalkingPerson(reggie -> sX, reggie -> sY, objectNumber, fun, reggie -> di)) return BR_PAUSE;
+			if (forceWalkingPerson(reggie->sX, reggie->sY, objectNumber, fun, reggie->di)) return BR_PAUSE;
 		} else if (immediate) {
-			jumpPerson(reggie -> sX, reggie -> sY, objectNumber);
+			jumpPerson(reggie->sX, reggie->sY, objectNumber);
 		} else {
-			if (makeWalkingPerson(reggie -> sX, reggie -> sY, objectNumber, fun, reggie -> di)) return BR_PAUSE;
+			if (makeWalkingPerson(reggie->sX, reggie->sY, objectNumber, fun, reggie->di)) return BR_PAUSE;
 		}
 		return BR_CONTINUE;
 	}
@@ -1738,9 +1737,9 @@ builtIn(addStatus) {
 
 builtIn(statusText) {
 	UNUSEDALL
-	char *newText = getTextFromAnyVar(fun -> stack -> thisVar);
+	char *newText = getTextFromAnyVar(fun->stack->thisVar);
 	if (!newText) return BR_ERROR;
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
 	setStatusBar(newText);
 	delete newText;
 	return BR_CONTINUE;
@@ -1749,8 +1748,8 @@ builtIn(statusText) {
 builtIn(lightStatus) {
 	UNUSEDALL
 	int val;
-	if (!getValueType(val, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(val, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	setLitStatus(val);
 	return BR_CONTINUE;
 }
@@ -1758,10 +1757,10 @@ builtIn(lightStatus) {
 builtIn(positionStatus) {
 	UNUSEDALL
 	int x, y;
-	if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	positionStatus(x, y);
 	return BR_CONTINUE;
 }
@@ -1769,9 +1768,9 @@ builtIn(positionStatus) {
 builtIn(alignStatus) {
 	UNUSEDALL
 	int val;
-	if (!getValueType(val, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	nowStatus -> alignStatus = (short) val;
+	if (!getValueType(val, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	nowStatus->alignStatus = (short) val;
 	return BR_CONTINUE;
 }
 
@@ -1782,8 +1781,8 @@ static bool getFuncNumForCallback(int numParams, loadedFunction *fun, int &funct
 		break;
 
 	case 1:
-		if (!getValueType(functionNum, SVT_FUNC, fun -> stack -> thisVar)) return false;
-		trimStack(fun -> stack);
+		if (!getValueType(functionNum, SVT_FUNC, fun->stack->thisVar)) return false;
+		trimStack(fun->stack);
 		break;
 
 	default:
@@ -1797,7 +1796,7 @@ builtIn(onLeftMouse) {
 	UNUSEDALL
 	int functionNum;
 	if (getFuncNumForCallback(numParams, fun, functionNum)) {
-		currentEvents -> leftMouseFunction = functionNum;
+		currentEvents->leftMouseFunction = functionNum;
 		return BR_CONTINUE;
 	}
 	return BR_ERROR;
@@ -1807,7 +1806,7 @@ builtIn(onLeftMouseUp) {
 	UNUSEDALL
 	int functionNum;
 	if (getFuncNumForCallback(numParams, fun, functionNum)) {
-		currentEvents -> leftMouseUpFunction = functionNum;
+		currentEvents->leftMouseUpFunction = functionNum;
 		return BR_CONTINUE;
 	}
 	return BR_ERROR;
@@ -1817,7 +1816,7 @@ builtIn(onRightMouse) {
 	UNUSEDALL
 	int functionNum;
 	if (getFuncNumForCallback(numParams, fun, functionNum)) {
-		currentEvents -> rightMouseFunction = functionNum;
+		currentEvents->rightMouseFunction = functionNum;
 		return BR_CONTINUE;
 	}
 	return BR_ERROR;
@@ -1827,7 +1826,7 @@ builtIn(onRightMouseUp) {
 	UNUSEDALL
 	int functionNum;
 	if (getFuncNumForCallback(numParams, fun, functionNum)) {
-		currentEvents -> rightMouseUpFunction = functionNum;
+		currentEvents->rightMouseUpFunction = functionNum;
 		return BR_CONTINUE;
 	}
 	return BR_ERROR;
@@ -1837,7 +1836,7 @@ builtIn(onFocusChange) {
 	UNUSEDALL
 	int functionNum;
 	if (getFuncNumForCallback(numParams, fun, functionNum)) {
-		currentEvents -> focusFunction = functionNum;
+		currentEvents->focusFunction = functionNum;
 		return BR_CONTINUE;
 	}
 	return BR_ERROR;
@@ -1847,7 +1846,7 @@ builtIn(onMoveMouse) {
 	UNUSEDALL
 	int functionNum;
 	if (getFuncNumForCallback(numParams, fun, functionNum)) {
-		currentEvents -> moveMouseFunction = functionNum;
+		currentEvents->moveMouseFunction = functionNum;
 		return BR_CONTINUE;
 	}
 	return BR_ERROR;
@@ -1857,7 +1856,7 @@ builtIn(onKeyboard) {
 	UNUSEDALL
 	int functionNum;
 	if (getFuncNumForCallback(numParams, fun, functionNum)) {
-		currentEvents -> spaceFunction = functionNum;
+		currentEvents->spaceFunction = functionNum;
 		return BR_CONTINUE;
 	}
 	return BR_ERROR;
@@ -1890,12 +1889,12 @@ builtIn(cancelSub) {
 
 builtIn(stringWidth) {
 	UNUSEDALL
-	char *theText = getTextFromAnyVar(fun -> stack -> thisVar);
+	char *theText = getTextFromAnyVar(fun->stack->thisVar);
 	if (!theText) return BR_ERROR;
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
 
 	// Return value
-	setVariable(fun -> reg, SVT_INT, stringWidth(theText));
+	setVariable(fun->reg, SVT_INT, stringWidth(theText));
 	delete theText;
 	return BR_CONTINUE;
 }
@@ -1903,8 +1902,8 @@ builtIn(stringWidth) {
 builtIn(hardScroll) {
 	UNUSEDALL
 	int v;
-	if (!getValueType(v, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(v, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	hardScroll(v);
 	return BR_CONTINUE;
 }
@@ -1913,37 +1912,37 @@ builtIn(hardScroll) {
 builtIn(isScreenRegion) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	setVariable(fun -> reg, SVT_INT, getRegionForObject(objectNumber) != NULL);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	setVariable(fun->reg, SVT_INT, getRegionForObject(objectNumber) != NULL);
 	return BR_CONTINUE;
 }
 
 builtIn(setSpeechSpeed) {
 	UNUSEDALL
 	int number;
-	if (!getValueType(number, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(number, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	speechSpeed = number * 0.01;
-	setVariable(fun -> reg, SVT_INT, 1);
+	setVariable(fun->reg, SVT_INT, 1);
 	return BR_CONTINUE;
 }
 
 builtIn(setFontSpacing) {
 	UNUSEDALL
 	int fontSpaceI;
-	if (!getValueType(fontSpaceI, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	if (!getValueType(fontSpaceI, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
 	fontSpace = fontSpaceI;
-	trimStack(fun -> stack);
-	setVariable(fun -> reg, SVT_INT, 1);
+	trimStack(fun->stack);
+	setVariable(fun->reg, SVT_INT, 1);
 	return BR_CONTINUE;
 }
 
 builtIn(transitionLevel) {
 	UNUSEDALL
 	int number;
-	if (!getValueType(number, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(number, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 
 	if (number < 0)
 		brightnessLevel = 0;
@@ -1952,15 +1951,15 @@ builtIn(transitionLevel) {
 	else
 		brightnessLevel = number;
 
-	setVariable(fun -> reg, SVT_INT, 1);
+	setVariable(fun->reg, SVT_INT, 1);
 	return BR_CONTINUE;
 }
 
 builtIn(captureAllKeys) {
 	UNUSEDALL
-	captureAllKeys = getBoolean(fun -> stack -> thisVar);
-	trimStack(fun -> stack);
-	setVariable(fun -> reg, SVT_INT, captureAllKeys);
+	captureAllKeys = getBoolean(fun->stack->thisVar);
+	trimStack(fun->stack);
+	setVariable(fun->reg, SVT_INT, captureAllKeys);
 	return BR_CONTINUE;
 }
 
@@ -1968,20 +1967,20 @@ builtIn(captureAllKeys) {
 builtIn(spinCharacter) {
 	UNUSEDALL
 	int number, objectNumber;
-	if (!getValueType(number, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(number, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 
 	onScreenPerson *thisPerson = findPerson(objectNumber);
 	if (thisPerson) {
-		thisPerson -> wantAngle = number;
-		thisPerson -> spinning = true;
-		thisPerson -> continueAfterWalking = fun;
-		setVariable(fun -> reg, SVT_INT, 1);
+		thisPerson->wantAngle = number;
+		thisPerson->spinning = true;
+		thisPerson->continueAfterWalking = fun;
+		setVariable(fun->reg, SVT_INT, 1);
 		return BR_PAUSE;
 	} else {
-		setVariable(fun -> reg, SVT_INT, 0);
+		setVariable(fun->reg, SVT_INT, 0);
 		return BR_CONTINUE;
 	}
 }
@@ -1989,13 +1988,13 @@ builtIn(spinCharacter) {
 builtIn(getCharacterDirection) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	onScreenPerson *thisPerson = findPerson(objectNumber);
 	if (thisPerson) {
-		setVariable(fun -> reg, SVT_INT, thisPerson -> direction);
+		setVariable(fun->reg, SVT_INT, thisPerson->direction);
 	} else {
-		setVariable(fun -> reg, SVT_INT, 0);
+		setVariable(fun->reg, SVT_INT, 0);
 	}
 	return BR_CONTINUE;
 }
@@ -2003,24 +2002,24 @@ builtIn(getCharacterDirection) {
 builtIn(isCharacter) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	onScreenPerson *thisPerson = findPerson(objectNumber);
-	setVariable(fun -> reg, SVT_INT, thisPerson != NULL);
+	setVariable(fun->reg, SVT_INT, thisPerson != NULL);
 	return BR_CONTINUE;
 }
 
 builtIn(normalCharacter) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	onScreenPerson *thisPerson = findPerson(objectNumber);
 	if (thisPerson) {
-		thisPerson -> myAnim = thisPerson -> myPersona -> animation[thisPerson -> direction];
-		setVariable(fun -> reg, SVT_INT, 1);
+		thisPerson->myAnim = thisPerson->myPersona->animation[thisPerson->direction];
+		setVariable(fun->reg, SVT_INT, 1);
 	} else {
-		setVariable(fun -> reg, SVT_INT, 0);
+		setVariable(fun->reg, SVT_INT, 0);
 	}
 	return BR_CONTINUE;
 }
@@ -2028,13 +2027,13 @@ builtIn(normalCharacter) {
 builtIn(isMoving) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	onScreenPerson *thisPerson = findPerson(objectNumber);
 	if (thisPerson) {
-		setVariable(fun -> reg, SVT_INT, thisPerson -> walking);
+		setVariable(fun->reg, SVT_INT, thisPerson->walking);
 	} else {
-		setVariable(fun -> reg, SVT_INT, 0);
+		setVariable(fun->reg, SVT_INT, 0);
 	}
 	return BR_CONTINUE;
 }
@@ -2042,18 +2041,18 @@ builtIn(isMoving) {
 builtIn(fetchEvent) {
 	UNUSEDALL
 	int obj1, obj2;
-	if (!getValueType(obj2, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(obj1, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(obj2, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(obj1, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 
 	int fNum = getCombinationFunction(obj1, obj2);
 
 	// Return value
 	if (fNum) {
-		setVariable(fun -> reg, SVT_FUNC, fNum);
+		setVariable(fun->reg, SVT_FUNC, fNum);
 	} else {
-		setVariable(fun -> reg, SVT_INT, 0);
+		setVariable(fun->reg, SVT_INT, 0);
 	}
 	return BR_CONTINUE;
 }
@@ -2061,12 +2060,12 @@ builtIn(fetchEvent) {
 builtIn(deleteFile) {
 	UNUSEDALL
 
-	char *namNormal = getTextFromAnyVar(fun -> stack -> thisVar);
-	trimStack(fun -> stack);
+	char *namNormal = getTextFromAnyVar(fun->stack->thisVar);
+	trimStack(fun->stack);
 	char *nam = encodeFilename(namNormal);
 	delete namNormal;
 	if (failSecurityCheck(nam)) return BR_ERROR;
-	setVariable(fun -> reg, SVT_INT, remove(nam));
+	setVariable(fun->reg, SVT_INT, remove(nam));
 	delete nam;
 
 	return BR_CONTINUE;
@@ -2076,19 +2075,19 @@ builtIn(renameFile) {
 	UNUSEDALL
 	char *temp;
 
-	temp = getTextFromAnyVar(fun -> stack -> thisVar);
+	temp = getTextFromAnyVar(fun->stack->thisVar);
 	char *newnam = encodeFilename(temp);
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
 	if (failSecurityCheck(newnam)) return BR_ERROR;
 	delete temp;
 
-	temp = getTextFromAnyVar(fun -> stack -> thisVar);
+	temp = getTextFromAnyVar(fun->stack->thisVar);
 	char *nam = encodeFilename(temp);
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
 	if (failSecurityCheck(nam)) return BR_ERROR;
 	delete temp;
 
-	setVariable(fun -> reg, SVT_INT, rename(nam, newnam));
+	setVariable(fun->reg, SVT_INT, rename(nam, newnam));
 	delete nam;
 	delete newnam;
 
@@ -2099,21 +2098,21 @@ builtIn(renameFile) {
 builtIn(cacheSound) {
 	UNUSEDALL
 	int fileNumber;
-	if (!getValueType(fileNumber, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	if (cacheSound(fileNumber) == -1) return BR_ERROR;
 	return BR_CONTINUE;
 }
 
 builtIn(burnString) {
 	UNUSEDALL
-	char *newText = getTextFromAnyVar(fun -> stack -> thisVar);
-	trimStack(fun -> stack);
+	char *newText = getTextFromAnyVar(fun->stack->thisVar);
+	trimStack(fun->stack);
 	int y, x;
-	if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	if (x == IN_THE_CENTRE) x = (winWidth - stringWidth(newText)) >> 1;
 	fixFont(pastePalette);
 	burnStringToBackdrop(newText, x, y, pastePalette);
@@ -2124,18 +2123,18 @@ builtIn(burnString) {
 builtIn(setCharacterSpinSpeed) {
 	UNUSEDALL
 	int speed, who;
-	if (!getValueType(speed, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(who, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(speed, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(who, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 
 	onScreenPerson *thisPerson = findPerson(who);
 
 	if (thisPerson) {
-		thisPerson -> spinSpeed = speed;
-		setVariable(fun -> reg, SVT_INT, 1);
+		thisPerson->spinSpeed = speed;
+		setVariable(fun->reg, SVT_INT, 1);
 	} else {
-		setVariable(fun -> reg, SVT_INT, 0);
+		setVariable(fun->reg, SVT_INT, 0);
 	}
 	return BR_CONTINUE;
 }
@@ -2143,18 +2142,18 @@ builtIn(setCharacterSpinSpeed) {
 builtIn(setCharacterAngleOffset) {
 	UNUSEDALL
 	int angle, who;
-	if (!getValueType(angle, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(who, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(angle, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(who, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 
 	onScreenPerson *thisPerson = findPerson(who);
 
 	if (thisPerson) {
-		thisPerson -> angleOffset = angle;
-		setVariable(fun -> reg, SVT_INT, 1);
+		thisPerson->angleOffset = angle;
+		setVariable(fun->reg, SVT_INT, 1);
 	} else {
-		setVariable(fun -> reg, SVT_INT, 0);
+		setVariable(fun->reg, SVT_INT, 0);
 	}
 	return BR_CONTINUE;
 }
@@ -2163,10 +2162,10 @@ builtIn(setCharacterAngleOffset) {
 builtIn(transitionMode) {
 	UNUSEDALL
 	int n;
-	if (!getValueType(n, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	if (!getValueType(n, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
 	fadeMode = n;
-	trimStack(fun -> stack);
-	setVariable(fun -> reg, SVT_INT, 1);
+	trimStack(fun->stack);
+	setVariable(fun->reg, SVT_INT, 1);
 	return BR_CONTINUE;
 }
 
@@ -2174,41 +2173,41 @@ builtIn(transitionMode) {
 // Removed function - does nothing
 builtIn(_rem_updateDisplay) {
 	UNUSEDALL
-	trimStack(fun -> stack);
-	setVariable(fun -> reg, SVT_INT, true);
+	trimStack(fun->stack);
+	setVariable(fun->reg, SVT_INT, true);
 	return BR_CONTINUE;
 }
 
 builtIn(getSoundCache) {
 	UNUSEDALL
-	fun -> reg.varType = SVT_STACK;
-	fun -> reg.varData.theStack = new stackHandler;
-	if (!checkNew(fun -> reg.varData.theStack)) return BR_ERROR;
-	fun -> reg.varData.theStack -> first = NULL;
-	fun -> reg.varData.theStack -> last = NULL;
-	fun -> reg.varData.theStack -> timesUsed = 1;
-	if (!getSoundCacheStack(fun -> reg.varData.theStack)) return BR_ERROR;
+	fun->reg.varType = SVT_STACK;
+	fun->reg.varData.theStack = new stackHandler;
+	if (!checkNew(fun->reg.varData.theStack)) return BR_ERROR;
+	fun->reg.varData.theStack->first = NULL;
+	fun->reg.varData.theStack->last = NULL;
+	fun->reg.varData.theStack->timesUsed = 1;
+	if (!getSoundCacheStack(fun->reg.varData.theStack)) return BR_ERROR;
 	return BR_CONTINUE;
 }
 
 builtIn(saveCustomData) {
 	UNUSEDALL
 	// saveCustomData (thisStack, fileName);
-	char *fileNameB = getTextFromAnyVar(fun -> stack -> thisVar);
+	char *fileNameB = getTextFromAnyVar(fun->stack->thisVar);
 	if (!checkNew(fileNameB)) return BR_ERROR;
 
 	char *fileName = encodeFilename(fileNameB);
 	delete fileNameB;
 
 	if (failSecurityCheck(fileName)) return BR_ERROR;
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
 
-	if (fun -> stack -> thisVar.varType != SVT_STACK) {
+	if (fun->stack->thisVar.varType != SVT_STACK) {
 		fatal("First parameter isn't a stack");
 		return BR_ERROR;
 	}
-	if (!stackToFile(fileName, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!stackToFile(fileName, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	delete fileName;
 	return BR_CONTINUE;
 }
@@ -2216,23 +2215,23 @@ builtIn(saveCustomData) {
 builtIn(loadCustomData) {
 	UNUSEDALL
 
-	char *newTextA = getTextFromAnyVar(fun -> stack -> thisVar);
+	char *newTextA = getTextFromAnyVar(fun->stack->thisVar);
 	if (!checkNew(newTextA)) return BR_ERROR;
 
 	char *newText = encodeFilename(newTextA);
 	delete newTextA;
 
 	if (failSecurityCheck(newText)) return BR_ERROR;
-	trimStack(fun -> stack);
-
-	unlinkVar(fun -> reg);
-	fun -> reg.varType = SVT_STACK;
-	fun -> reg.varData.theStack = new stackHandler;
-	if (!checkNew(fun -> reg.varData.theStack)) return BR_ERROR;
-	fun -> reg.varData.theStack -> first = NULL;
-	fun -> reg.varData.theStack -> last = NULL;
-	fun -> reg.varData.theStack -> timesUsed = 1;
-	if (!fileToStack(newText, fun -> reg.varData.theStack)) return BR_ERROR;
+	trimStack(fun->stack);
+
+	unlinkVar(fun->reg);
+	fun->reg.varType = SVT_STACK;
+	fun->reg.varData.theStack = new stackHandler;
+	if (!checkNew(fun->reg.varData.theStack)) return BR_ERROR;
+	fun->reg.varData.theStack->first = NULL;
+	fun->reg.varData.theStack->last = NULL;
+	fun->reg.varData.theStack->timesUsed = 1;
+	if (!fileToStack(newText, fun->reg.varData.theStack)) return BR_ERROR;
 	delete newText;
 	return BR_CONTINUE;
 }
@@ -2240,18 +2239,18 @@ builtIn(loadCustomData) {
 builtIn(setCustomEncoding) {
 	UNUSEDALL
 	int n;
-	if (!getValueType(n, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
+	if (!getValueType(n, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
 	saveEncoding = n;
-	trimStack(fun -> stack);
-	setVariable(fun -> reg, SVT_INT, 1);
+	trimStack(fun->stack);
+	setVariable(fun->reg, SVT_INT, 1);
 	return BR_CONTINUE;
 }
 
 builtIn(freeSound) {
 	UNUSEDALL
 	int v;
-	if (!getValueType(v, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(v, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	huntKillFreeSound(v);
 	return BR_CONTINUE;
 }
@@ -2263,15 +2262,15 @@ builtIn(parallaxAdd) {
 		return BR_ERROR;
 	} else {
 		int wrapX, wrapY, v;
-		if (!getValueType(wrapY, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-		trimStack(fun -> stack);
-		if (!getValueType(wrapX, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-		trimStack(fun -> stack);
-		if (!getValueType(v, SVT_FILE, fun -> stack -> thisVar)) return BR_ERROR;
-		trimStack(fun -> stack);
+		if (!getValueType(wrapY, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+		trimStack(fun->stack);
+		if (!getValueType(wrapX, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+		trimStack(fun->stack);
+		if (!getValueType(v, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+		trimStack(fun->stack);
 
 		if (!loadParallax(v, wrapX, wrapY)) return BR_ERROR;
-		setVariable(fun -> reg, SVT_INT, 1);
+		setVariable(fun->reg, SVT_INT, 1);
 	}
 	return BR_CONTINUE;
 }
@@ -2279,44 +2278,44 @@ builtIn(parallaxAdd) {
 builtIn(parallaxClear) {
 	UNUSEDALL
 	killParallax();
-	setVariable(fun -> reg, SVT_INT, 1);
+	setVariable(fun->reg, SVT_INT, 1);
 	return BR_CONTINUE;
 }
 
 builtIn(getPixelColour) {
 	UNUSEDALL
 	int x, y;
-	if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 
-	unlinkVar(fun -> reg);
-	fun -> reg.varType = SVT_STACK;
-	fun -> reg.varData.theStack = new stackHandler;
-	if (!checkNew(fun -> reg.varData.theStack)) return BR_ERROR;
-	fun -> reg.varData.theStack -> first = NULL;
-	fun -> reg.varData.theStack -> last = NULL;
-	fun -> reg.varData.theStack -> timesUsed = 1;
-	if (!getRGBIntoStack(x, y, fun -> reg.varData.theStack)) return BR_ERROR;
+	unlinkVar(fun->reg);
+	fun->reg.varType = SVT_STACK;
+	fun->reg.varData.theStack = new stackHandler;
+	if (!checkNew(fun->reg.varData.theStack)) return BR_ERROR;
+	fun->reg.varData.theStack->first = NULL;
+	fun->reg.varData.theStack->last = NULL;
+	fun->reg.varData.theStack->timesUsed = 1;
+	if (!getRGBIntoStack(x, y, fun->reg.varData.theStack)) return BR_ERROR;
 
 	return BR_CONTINUE;
 }
 
 builtIn(makeFastArray) {
 	UNUSEDALL
-	switch (fun -> stack -> thisVar.varType) {
+	switch (fun->stack->thisVar.varType) {
 	case SVT_STACK: {
-		bool success = makeFastArrayFromStack(fun -> reg, fun -> stack -> thisVar.varData.theStack);
-		trimStack(fun -> stack);
+		bool success = makeFastArrayFromStack(fun->reg, fun->stack->thisVar.varData.theStack);
+		trimStack(fun->stack);
 		return success ? BR_CONTINUE : BR_ERROR;
 	}
 	break;
 
 	case SVT_INT: {
-		int i = fun -> stack -> thisVar.varData.intValue;
-		trimStack(fun -> stack);
-		return makeFastArraySize(fun -> reg, i) ? BR_CONTINUE : BR_ERROR;
+		int i = fun->stack->thisVar.varData.intValue;
+		trimStack(fun->stack);
+		return makeFastArraySize(fun->reg, i) ? BR_CONTINUE : BR_ERROR;
 	}
 	break;
 
@@ -2330,21 +2329,21 @@ builtIn(makeFastArray) {
 builtIn(getCharacterScale) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 
 	onScreenPerson *pers = findPerson(objectNumber);
 	if (pers) {
-		setVariable(fun -> reg, SVT_INT, pers -> scale * 100);
+		setVariable(fun->reg, SVT_INT, pers->scale * 100);
 	} else {
-		setVariable(fun -> reg, SVT_INT, 0);
+		setVariable(fun->reg, SVT_INT, 0);
 	}
 	return BR_CONTINUE;
 }
 
 builtIn(getLanguageID) {
 	UNUSEDALL
-	setVariable(fun -> reg, SVT_INT, gameSettings.languageID);
+	setVariable(fun->reg, SVT_INT, gameSettings.languageID);
 	return BR_CONTINUE;
 }
 
@@ -2352,9 +2351,9 @@ builtIn(getLanguageID) {
 builtIn(_rem_launchWith) {
 	UNUSEDALL
 
-	trimStack(fun -> stack);
-	trimStack(fun -> stack);
-	setVariable(fun -> reg, SVT_INT, false);
+	trimStack(fun->stack);
+	trimStack(fun->stack);
+	setVariable(fun->reg, SVT_INT, false);
 
 	return BR_CONTINUE;
 
@@ -2362,22 +2361,22 @@ builtIn(_rem_launchWith) {
 
 builtIn(getFramesPerSecond) {
 	UNUSEDALL
-	setVariable(fun -> reg, SVT_INT, lastFramesPerSecond);
+	setVariable(fun->reg, SVT_INT, lastFramesPerSecond);
 	return BR_CONTINUE;
 }
 
 builtIn(showThumbnail) {
 	UNUSEDALL
 	int x, y;
-	if (!getValueType(y, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(x, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 
 	// Encode the name!Encode the name!
-	char *aaaaa = getTextFromAnyVar(fun -> stack -> thisVar);
+	char *aaaaa = getTextFromAnyVar(fun->stack->thisVar);
 	//              deb ("Got name:", aaaaa;)
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
 	//              deb ("About to encode", aaaaa);
 	char *file = encodeFilename(aaaaa);
 	//              deb ("Made new name", file);
@@ -2391,10 +2390,10 @@ builtIn(showThumbnail) {
 
 builtIn(setThumbnailSize) {
 	UNUSEDALL
-	if (!getValueType(thumbHeight, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(thumbWidth, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(thumbHeight, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(thumbWidth, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	if (thumbWidth < 0 || thumbHeight < 0 || thumbWidth > winWidth || thumbHeight > winHeight) {
 		char buff[50];
 		sprintf(buff, "%d x %d", thumbWidth, thumbHeight);
@@ -2407,13 +2406,13 @@ builtIn(setThumbnailSize) {
 builtIn(hasFlag) {
 	UNUSEDALL
 	int objNum, flagIndex;
-	if (!getValueType(flagIndex, SVT_INT, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
-	if (!getValueType(objNum, SVT_OBJTYPE, fun -> stack -> thisVar)) return BR_ERROR;
-	trimStack(fun -> stack);
+	if (!getValueType(flagIndex, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
+	if (!getValueType(objNum, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	trimStack(fun->stack);
 	objectType *objT = findObjectType(objNum);
 	if (!objT) return BR_ERROR;
-	setVariable(fun -> reg, SVT_INT, objT->flags & (1 << flagIndex));
+	setVariable(fun->reg, SVT_INT, objT->flags & (1 << flagIndex));
 	return BR_CONTINUE;
 }
 
@@ -2431,26 +2430,26 @@ builtIn(snapshotClear) {
 builtIn(bodgeFilenames) {
 	UNUSEDALL
 	bool lastValue = allowAnyFilename;
-	allowAnyFilename = getBoolean(fun -> stack -> thisVar);
-	trimStack(fun -> stack);
-	setVariable(fun -> reg, SVT_INT, lastValue);
+	allowAnyFilename = getBoolean(fun->stack->thisVar);
+	trimStack(fun->stack);
+	setVariable(fun->reg, SVT_INT, lastValue);
 	return BR_CONTINUE;
 }
 
 // Deprecated - does nothing.
 builtIn(_rem_registryGetString) {
 	UNUSEDALL
-	trimStack(fun -> stack);
-	trimStack(fun -> stack);
-	setVariable(fun -> reg, SVT_INT, 0);
+	trimStack(fun->stack);
+	trimStack(fun->stack);
+	setVariable(fun->reg, SVT_INT, 0);
 
 	return BR_CONTINUE;
 }
 
 builtIn(quitWithFatalError) {
 	UNUSEDALL
-	char *mess = getTextFromAnyVar(fun -> stack -> thisVar);
-	trimStack(fun -> stack);
+	char *mess = getTextFromAnyVar(fun->stack->thisVar);
+	trimStack(fun->stack);
 	fatal(mess);
 	return BR_ERROR;
 }
@@ -2458,10 +2457,10 @@ builtIn(quitWithFatalError) {
 builtIn(_rem_setCharacterAA) {
 	UNUSEDALL
 
-	trimStack(fun -> stack);
-	trimStack(fun -> stack);
-	trimStack(fun -> stack);
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
+	trimStack(fun->stack);
+	trimStack(fun->stack);
+	trimStack(fun->stack);
 
 	return BR_CONTINUE;
 }
@@ -2469,9 +2468,9 @@ builtIn(_rem_setCharacterAA) {
 builtIn(_rem_setMaximumAA) {
 	UNUSEDALL
 
-	trimStack(fun -> stack);
-	trimStack(fun -> stack);
-	trimStack(fun -> stack);
+	trimStack(fun->stack);
+	trimStack(fun->stack);
+	trimStack(fun->stack);
 
 	return BR_CONTINUE;
 
@@ -2480,14 +2479,14 @@ builtIn(_rem_setMaximumAA) {
 builtIn(setBackgroundEffect) {
 	UNUSEDALL
 	bool done = blur_createSettings(numParams, fun->stack);
-	setVariable(fun -> reg, SVT_INT, done ? 1 : 0);
+	setVariable(fun->reg, SVT_INT, done ? 1 : 0);
 	return BR_CONTINUE;
 }
 
 builtIn(doBackgroundEffect) {
 	UNUSEDALL
 	bool done = blurScreen();
-	setVariable(fun -> reg, SVT_INT, done ? 1 : 0);
+	setVariable(fun->reg, SVT_INT, done ? 1 : 0);
 	return BR_CONTINUE;
 }
 
@@ -2516,11 +2515,11 @@ builtReturn callBuiltIn(int whichFunc, int numParams, loadedFunction *fun) {
 	// fprintf (stderr, "Calling function %d: %s\n", whichFunc, builtInFunctionNames[whichFunc]);    fflush (stderr);
 	if (numBIFNames) {
 
-		//      deb ("IN:", (fun -> originalNumber < numUserFunc) ? allUserFunc[fun -> originalNumber] : "Unknown user function");
+		//      deb ("IN:", (fun->originalNumber < numUserFunc) ? allUserFunc[fun->originalNumber] : "Unknown user function");
 		//      deb ("GO:", (whichFunc < numBIFNames) ? allBIFNames[whichFunc] : "Unknown built-in function");
 
 		setFatalInfo(
-		    (fun -> originalNumber < numUserFunc) ? allUserFunc[fun -> originalNumber] : "Unknown user function",
+		    (fun->originalNumber < numUserFunc) ? allUserFunc[fun->originalNumber] : "Unknown user function",
 		    (whichFunc < numBIFNames) ? allBIFNames[whichFunc] : "Unknown built-in function");
 	}
 
diff --git a/engines/sludge/detection.cpp b/engines/sludge/detection.cpp
index 8297165..7e5c124 100644
--- a/engines/sludge/detection.cpp
+++ b/engines/sludge/detection.cpp
@@ -43,6 +43,8 @@ Common::Language SludgeEngine::getLanguage() const { return _gameDescription->de
 static const PlainGameDescriptor sludgeGames[] = {
 	{ "sludge", "Sludge Game" },
 	{ "welcome", "Welcome Example" },
+	{ "welcome2", "Welcome Example 2" },
+	{ "verbcoin", "Verb Coin" },
 	{ 0, 0 }
 };
  
@@ -61,6 +63,32 @@ static const SludgeGameDescription gameDescriptions[] = {
 		0
 	},
 
+	{
+		{
+			"welcome2",
+			"",
+			AD_ENTRY1("Welcome.slg", "cb1f307c05b8ae4107bcc7f86a3d2f99"),
+			Common::EN_ANY,
+			Common::kPlatformUnknown,
+			ADGF_NO_FLAGS,
+			GUIO0()
+		},
+		0
+	},
+
+	{
+		{
+			"verbcoin",
+			"",
+			AD_ENTRY1("Welcome.slg", "e39ec315dcbf3a1137481f0a5fe1617d"),
+			Common::EN_ANY,
+			Common::kPlatformUnknown,
+			ADGF_NO_FLAGS,
+			GUIO0()
+		},
+		0
+	},
+
 	{ AD_TABLE_END_MARKER, 0 }
 };
 
diff --git a/engines/sludge/fileset.cpp b/engines/sludge/fileset.cpp
index 852fd70..3c653f4 100644
--- a/engines/sludge/fileset.cpp
+++ b/engines/sludge/fileset.cpp
@@ -29,18 +29,19 @@
 
 #include "debug.h"
 #include "stringy.h"
-
 #include "allfiles.h"
 #include "moreio.h"
 #include "newfatal.h"
 #include "CommonCode/version.h"
 
+#include "common/file.h"
+
 namespace Sludge {
 
 bool sliceBusy = true;
-#if ALLOW_FILE
-FILE *bigDataFile = NULL;
-#endif
+
+Common::File *bigDataFile = NULL;
+
 uint32_t startOfDataIndex, startOfTextIndex,
          startOfSubIndex, startOfObjectIndex;
 
@@ -54,8 +55,8 @@ bool openSubSlice(int num) {
 		return false;
 	}
 //	fprintf (dbug, "Going to position %li\n", startOfSubIndex + (num << 2));
-	fseek(bigDataFile, startOfSubIndex + (num << 2), 0);
-	fseek(bigDataFile, get4bytes(bigDataFile), 0);
+	bigDataFile->seek(startOfSubIndex + (num << 2), 0);
+	bigDataFile->seek(get4bytes(bigDataFile), 0);
 //	fprintf (dbug, "Told to skip forward to %li\n", ftell (bigDataFile));
 //	fclose (dbug);
 
@@ -73,8 +74,8 @@ bool openObjectSlice(int num) {
 	}
 
 //	fprintf (dbug, "Going to position %li\n", startOfObjectIndex + (num << 2));
-	fseek(bigDataFile, startOfObjectIndex + (num << 2), 0);
-	fseek(bigDataFile, get4bytes(bigDataFile), 0);
+	bigDataFile->seek(startOfObjectIndex + (num << 2), 0);
+	bigDataFile->seek(get4bytes(bigDataFile), 0);
 //	fprintf (dbug, "Told to skip forward to %li\n", ftell (bigDataFile));
 //	fclose (dbug);
 	return sliceBusy = true;
@@ -90,8 +91,8 @@ unsigned int openFileFromNum(int num) {
 
 //	fprintf (dbug, "\nTrying to open file %i\n", num);
 //	fprintf (dbug, "Jumping to %li (for index) \n", startOfDataIndex + (num << 2));
-	fseek(bigDataFile, startOfDataIndex + (num << 2), 0);
-	fseek(bigDataFile, get4bytes(bigDataFile), 1);
+	bigDataFile->seek(startOfDataIndex + (num << 2), 0);
+	bigDataFile->seek(get4bytes(bigDataFile), 1);
 //	fprintf (dbug, "Jumping to %li (for data) \n", ftell (bigDataFile));
 	sliceBusy = true;
 //	fclose (dbug);
@@ -103,6 +104,7 @@ unsigned int openFileFromNum(int num) {
 // Converts a string from Windows CP-1252 to UTF-8.
 // This is needed for old games.
 char *convertString(char *s) {
+#if 0
 	static char *buf = NULL;
 
 	if (! buf) {
@@ -161,6 +163,8 @@ char *convertString(char *s) {
 
 	delete [] sOrig;
 	return copyString(buf = bufOrig);
+#endif
+	return s;//TODO: false value
 }
 
 char *getNumberedString(int value) {
@@ -170,9 +174,9 @@ char *getNumberedString(int value) {
 		return NULL;
 	}
 
-	fseek(bigDataFile, (value << 2) + startOfTextIndex, 0);
+	bigDataFile->seek((value << 2) + startOfTextIndex, 0);
 	value = get4bytes(bigDataFile);
-	fseek(bigDataFile, value, 0);
+	bigDataFile->seek(value, 0);
 
 	char *s = readString(bigDataFile);
 
@@ -195,15 +199,15 @@ void finishAccess() {
 
 int32_t startIndex;
 
-void setFileIndices(FILE *fp, int numLanguages, unsigned int skipBefore) {
+void setFileIndices(Common::File *fp, int numLanguages, unsigned int skipBefore) {
 	if (fp) {
 		// Keep hold of the file handle, and let things get at it
 		bigDataFile = fp;
-		startIndex = ftell(fp);
+		startIndex = fp->pos();
 	} else {
 		// No file pointer - this means that we reuse the bigDataFile
 		fp = bigDataFile;
-		fseek(fp, startIndex, 0);
+		fp->seek(startIndex, SEEK_SET);
 	}
 	sliceBusy = false;
 
@@ -215,26 +219,26 @@ void setFileIndices(FILE *fp, int numLanguages, unsigned int skipBefore) {
 	// STRINGS
 	int skipAfter = numLanguages - skipBefore;
 	while (skipBefore) {
-		fseek(fp, get4bytes(fp), 0);
+		fp->seek(get4bytes(fp), SEEK_SET);
 		skipBefore --;
 	}
-	startOfTextIndex = ftell(fp) + 4;
+	startOfTextIndex = fp->pos() + 4;
 
-	fseek(fp, get4bytes(fp), 0);
+	fp->seek(get4bytes(fp), SEEK_SET);
 
 	while (skipAfter) {
-		fseek(fp, get4bytes(fp), 0);
+		fp->seek(get4bytes(fp), SEEK_SET);
 		skipAfter --;
 	}
 
-	startOfSubIndex = ftell(fp) + 4;
-	fseek(fp, get4bytes(fp), 1);
+	startOfSubIndex = fp->pos() + 4;
+	fp->seek(get4bytes(fp), SEEK_CUR);
 
-	startOfObjectIndex = ftell(fp) + 4;
-	fseek(fp, get4bytes(fp), 1);
+	startOfObjectIndex = fp->pos() + 4;
+	fp->seek(get4bytes(fp), SEEK_CUR);
 
 	// Remember that the data section starts here
-	startOfDataIndex = ftell(fp);
+	startOfDataIndex = fp->pos();
 }
 
 } // End of namespace Sludge
diff --git a/engines/sludge/fileset.h b/engines/sludge/fileset.h
index b83e47d..2dec0d3 100644
--- a/engines/sludge/fileset.h
+++ b/engines/sludge/fileset.h
@@ -22,13 +22,13 @@
 #ifndef SLUDGE_FILESET_H
 #define SLUDGE_FILESET_H
 
+#include "common/file.h"
+
 namespace Sludge {
 
-#if ALLOW_FILE
-extern FILE *bigDataFile;
+extern Common::File *bigDataFile;
 
-void setFileIndices(FILE *fp, int, unsigned int);
-#endif
+void setFileIndices(Common::File *fp, int, unsigned int);
 
 unsigned int openFileFromNum(int num);
 bool openSubSlice(int num);
diff --git a/engines/sludge/floor.cpp b/engines/sludge/floor.cpp
index 291961d..7ca30b6 100644
--- a/engines/sludge/floor.cpp
+++ b/engines/sludge/floor.cpp
@@ -127,13 +127,13 @@ bool setFloor(int fileNum) {
 	killFloor();
 
 	setResourceForFatal(fileNum);
-#if ALLOW_FILE
+
 	if (! openFileFromNum(fileNum)) return false;
 
 	// Find out how many polygons there are and reserve memory
 
 	currentFloor -> originalNum = fileNum;
-	currentFloor -> numPolygons = fgetc(bigDataFile);
+	currentFloor -> numPolygons = getch(bigDataFile);
 	currentFloor -> polygon = new floorPolygon[currentFloor -> numPolygons];
 	if (! checkNew(currentFloor -> polygon)) return false;
 
@@ -143,7 +143,7 @@ bool setFloor(int fileNum) {
 
 		// Find out how many vertex IDs there are and reserve memory
 
-		currentFloor -> polygon[i].numVertices = fgetc(bigDataFile);
+		currentFloor -> polygon[i].numVertices = getch(bigDataFile);
 		currentFloor -> polygon[i].vertexID = new int[currentFloor -> polygon[i].numVertices];
 		if (! checkNew(currentFloor -> polygon[i].vertexID)) return false;
 
@@ -167,7 +167,7 @@ bool setFloor(int fileNum) {
 	}
 
 	finishAccess();
-#endif
+
 	// Now build the movement martix
 
 	currentFloor -> matrix = new int *[currentFloor -> numPolygons];
diff --git a/engines/sludge/helpers.cpp b/engines/sludge/helpers.cpp
index 30d5094..60a29af 100644
--- a/engines/sludge/helpers.cpp
+++ b/engines/sludge/helpers.cpp
@@ -22,18 +22,19 @@
 #include "allfiles.h"
 #include "helpers.h"
 
+#include "common/file.h"
+
 namespace Sludge {
 
 bool fileExists(const char *file) {
 	bool retval = false;
-#if ALLOW_FILE
-	FILE *tester;
-	tester = fopen(file, "rb");
-	if (tester) {
+
+	Common::File tester;
+	if (tester.open(file)) {
 		retval = true;
-		fclose(tester);
+		tester.close();
 	}
-#endif
+
 	return retval;
 }
 
diff --git a/engines/sludge/language.cpp b/engines/sludge/language.cpp
index a55adae..4fe2780 100644
--- a/engines/sludge/language.cpp
+++ b/engines/sludge/language.cpp
@@ -19,8 +19,7 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include <stdio.h>
-#include <string.h>
+#include "allfiles.h"
 #include "stringy.h"
 #include "newfatal.h"
 #include "moreio.h"
@@ -28,6 +27,10 @@
 #include "CommonCode/version.h"
 #include "platform-dependent.h"
 
+#include "sludge.h"
+
+#include "common/debug.h"
+
 namespace Sludge {
 
 int *languageTable;
@@ -84,13 +87,17 @@ char *getPrefsFilename(char *filename) {
 }
 
 void readIniFile(char *filename) {
-#if ALLOW_FILE
+
 	char *langName = getPrefsFilename(copyString(filename));
 
-	FILE *fp = fopen(langName, "rb");
+	Common::File fd;
+	if (!fd.open(langName)) {
+		debug(kSludgeDebugDataLoad, "Fail to open language file : %s", langName);
+		return;
+	}
 
 	gameSettings.languageID = 0;
-	gameSettings.userFullScreen = defaultUserFullScreen();
+	gameSettings.userFullScreen = false; //defaultUserFullScreen(); TODO: false value
 	gameSettings.refreshRate = 0;
 	gameSettings.antiAlias = 1;
 	gameSettings.fixedPixels = false;
@@ -100,70 +107,67 @@ void readIniFile(char *filename) {
 	delete langName;
 	langName = NULL;
 
-	if (fp) {
-		char lineSoFar[257] = "";
-		char secondSoFar[257] = "";
-		unsigned char here = 0;
-		char readChar = ' ';
-		bool keepGoing = true;
-		bool doingSecond = false;
-
-		do {
-			readChar = fgetc(fp);
-			if (feof(fp)) {
-				readChar = '\n';
-				keepGoing = false;
-			}
-			switch (readChar) {
-			case '\n':
-			case '\r':
-				if (doingSecond) {
-					if (strcmp(lineSoFar, "LANGUAGE") == 0) {
-						gameSettings.languageID = stringToInt(secondSoFar);
-					} else if (strcmp(lineSoFar, "WINDOW") == 0) {
-						gameSettings.userFullScreen = ! stringToInt(secondSoFar);
-					} else if (strcmp(lineSoFar, "REFRESH") == 0) {
-						gameSettings.refreshRate = stringToInt(secondSoFar);
-					} else if (strcmp(lineSoFar, "ANTIALIAS") == 0) {
-						gameSettings.antiAlias = stringToInt(secondSoFar);
-					} else if (strcmp(lineSoFar, "FIXEDPIXELS") == 0) {
-						gameSettings.fixedPixels = stringToInt(secondSoFar);
-					} else if (strcmp(lineSoFar, "NOSTARTWINDOW") == 0) {
-						gameSettings.noStartWindow = stringToInt(secondSoFar);
-					} else if (strcmp(lineSoFar, "DEBUGMODE") == 0) {
-						gameSettings.debugMode = stringToInt(secondSoFar);
-					}
-				}
-				here = 0;
-				doingSecond = false;
-				lineSoFar[0] = 0;
-				secondSoFar[0] = 0;
-				break;
-
-			case '=':
-				doingSecond = true;
-				here = 0;
-				break;
-
-			default:
-				if (doingSecond) {
-					secondSoFar[here ++] = readChar;
-					secondSoFar[here] = 0;
-				} else {
-					lineSoFar[here ++] = readChar;
-					lineSoFar[here] = 0;
+	char lineSoFar[257] = "";
+	char secondSoFar[257] = "";
+	unsigned char here = 0;
+	char readChar = ' ';
+	bool keepGoing = true;
+	bool doingSecond = false;
+
+	do {
+		readChar = getch(&fd);
+		if (fd.eos()) {
+			readChar = '\n';
+			keepGoing = false;
+		}
+		switch (readChar) {
+		case '\n':
+		case '\r':
+			if (doingSecond) {
+				if (strcmp(lineSoFar, "LANGUAGE") == 0) {
+					gameSettings.languageID = stringToInt(secondSoFar);
+				} else if (strcmp(lineSoFar, "WINDOW") == 0) {
+					gameSettings.userFullScreen = ! stringToInt(secondSoFar);
+				} else if (strcmp(lineSoFar, "REFRESH") == 0) {
+					gameSettings.refreshRate = stringToInt(secondSoFar);
+				} else if (strcmp(lineSoFar, "ANTIALIAS") == 0) {
+					gameSettings.antiAlias = stringToInt(secondSoFar);
+				} else if (strcmp(lineSoFar, "FIXEDPIXELS") == 0) {
+					gameSettings.fixedPixels = stringToInt(secondSoFar);
+				} else if (strcmp(lineSoFar, "NOSTARTWINDOW") == 0) {
+					gameSettings.noStartWindow = stringToInt(secondSoFar);
+				} else if (strcmp(lineSoFar, "DEBUGMODE") == 0) {
+					gameSettings.debugMode = stringToInt(secondSoFar);
 				}
-				break;
 			}
-		} while (keepGoing);
+			here = 0;
+			doingSecond = false;
+			lineSoFar[0] = 0;
+			secondSoFar[0] = 0;
+			break;
+
+		case '=':
+			doingSecond = true;
+			here = 0;
+			break;
+
+		default:
+			if (doingSecond) {
+				secondSoFar[here ++] = readChar;
+				secondSoFar[here] = 0;
+			} else {
+				lineSoFar[here ++] = readChar;
+				lineSoFar[here] = 0;
+			}
+			break;
+		}
+	} while (keepGoing);
 
-		fclose(fp);
-	}
-#endif
+	fd.close();
 }
 
 void saveIniFile(char *filename) {
-#if ALLOW_FILE
+#if 0
 	char *langName = getPrefsFilename(copyString(filename));
 	FILE *fp = fopen(langName, "wt");
 	delete langName;
@@ -179,8 +183,7 @@ void saveIniFile(char *filename) {
 #endif
 }
 
-#if ALLOW_FILE
-void makeLanguageTable(FILE *table) {
+void makeLanguageTable(Common::File *table) {
 	languageTable = new int[gameSettings.numLanguages + 1];
 	if (! checkNew(languageTable)) return;
 
@@ -189,17 +192,16 @@ void makeLanguageTable(FILE *table) {
 
 	for (unsigned int i = 0; i <= gameSettings.numLanguages; i ++) {
 		languageTable[i] = i ? get2bytes(table) : 0;
-		printf("languageTable %i: %i\n", i, languageTable[i]);
+		debug(kSludgeDebugDataLoad, "languageTable %i: %i", i, languageTable[i]);
 		languageName[i] = 0;
 		if (gameVersion >= VERSION(2, 0)) {
 			if (gameSettings.numLanguages) {
 				languageName[i] = readString(table);
-				printf("languageName %i: %s\n", i, languageName[i]);
+				debug(kSludgeDebugDataLoad, "languageName %i: %s\n", i, languageName[i]);
 			}
 		}
 	}
 }
-#endif
 
 int getLanguageForFileB() {
 	int indexNum = -1;
diff --git a/engines/sludge/language.h b/engines/sludge/language.h
index 27faffb..93805c2 100644
--- a/engines/sludge/language.h
+++ b/engines/sludge/language.h
@@ -22,6 +22,10 @@
 #ifndef LANGUAGE_H
 #define LANGUAGE_H
 
+#include "allfiles.h"
+
+#include "common/file.h"
+
 namespace Sludge {
 
 struct settingsStruct {
@@ -41,9 +45,7 @@ void readIniFile(char *filename);
 void saveIniFile(char *filename);
 int getLanguageForFileB();
 
-#if ALLOW_FILE
-void makeLanguageTable(FILE *table);
-#endif
+void makeLanguageTable(Common::File *table);
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index 2014095..959885f 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -40,6 +40,7 @@
 #include "sound.h"
 #include "fileset.h"
 #include "debug.h"
+#include "loadsave.h"
 
 namespace Sludge {
 
@@ -93,81 +94,76 @@ stackLibrary *stackLib = NULL;
 //----------------------------------------------------------------------
 // For saving and loading stacks...
 //----------------------------------------------------------------------
-#if 0
-bool saveVariable(variable *from, FILE *fp);
-bool loadVariable(variable *to, FILE *fp);
-
-void saveStack(variableStack *vs, FILE *fp) {
+void saveStack(variableStack *vs, Common::WriteStream *stream) {
 	int elements = 0;
 	int a;
 
 	variableStack *search = vs;
 	while (search) {
 		elements ++;
-		search = search -> next;
+		search = search->next;
 	}
 
 	stackDebug((stackfp, "  stack contains %d elements\n", elements));
 
-	put2bytes(elements, fp);
+	put2bytes(elements, stream);
 	search = vs;
-	for (a = 0; a < elements; a ++) {
-		saveVariable(& search -> thisVar, fp);
-		search = search -> next;
+	for (a = 0; a < elements; ++a) {
+		saveVariable(&search->thisVar, stream);
+		search = search->next;
 	}
 }
 
-variableStack *loadStack(FILE *fp, variableStack **last) {
-	int elements = get2bytes(fp);
+variableStack *loadStack(Common::SeekableReadStream *stream, variableStack **last) {
+	int elements = get2bytes(stream);
 	int a;
 	variableStack *first = NULL;
-	variableStack * * changeMe = & first;
+	variableStack * * changeMe = &first;
 
-	for (a = 0; a < elements; a ++) {
+	for (a = 0; a < elements; ++a) {
 		variableStack *nS = new variableStack;
 		if (!checkNew(nS)) return NULL;
-		loadVariable(& (nS -> thisVar), fp);
+		loadVariable(&(nS->thisVar), stream);
 		if (last && a == elements - 1) {
 			stackDebug((stackfp, "Setting last to %p\n", nS));
 			*last = nS;
 		}
-		nS -> next = NULL;
+		nS->next = NULL;
 		(* changeMe) = nS;
-		changeMe = & (nS -> next);
+		changeMe = &(nS->next);
 	}
 
 	return first;
 }
 
-bool saveStackRef(stackHandler *vs, FILE *fp) {
+bool saveStackRef(stackHandler *vs, Common::WriteStream *stream) {
 	stackLibrary *s = stackLib;
 	int a = 0;
 	while (s) {
-		if (s -> stack == vs) {
-			fputc(1, fp);
-			put2bytes(stackLibTotal - a, fp);
+		if (s->stack == vs) {
+			putch(1, stream);
+			put2bytes(stackLibTotal - a, stream);
 			return true;
 		}
-		s = s -> next;
-		a ++;
+		s = s->next;
+		++a;
 	}
-	fputc(0, fp);
-	saveStack(vs -> first, fp);
+	putch(0, stream);
+	saveStack(vs->first, stream);
 	s = new stackLibrary;
 	stackLibTotal ++;
 	if (! checkNew(s)) return false;
-	s -> next = stackLib;
-	s -> stack = vs;
+	s->next = stackLib;
+	s->stack = vs;
 	stackLib = s;
 	return true;
 }
-#endif
 
 void clearStackLib() {
 	stackLibrary *k;
 	while (stackLib) {
 		k = stackLib;
-		stackLib = stackLib -> next;
+		stackLib = stackLib->next;
 		delete k;
 	}
 	stackLibTotal = 0;
@@ -176,20 +172,20 @@ void clearStackLib() {
 stackHandler *getStackFromLibrary(int n) {
 	n = stackLibTotal - n;
 	while (n) {
-		stackLib = stackLib -> next;
+		stackLib = stackLib->next;
 		n --;
 	}
-	return stackLib -> stack;
+	return stackLib->stack;
 }
-#if 0
-stackHandler *loadStackRef(FILE *fp) {
+
+stackHandler *loadStackRef(Common::SeekableReadStream *stream) {
 	stackHandler *nsh;
 
-	if (fgetc(fp)) {    // It's one we've loaded already...
+	if (getch(stream)) {    // It's one we've loaded already...
 		stackDebug((stackfp, "loadStackRef (duplicate, get from library)\n"));
 
-		nsh = getStackFromLibrary(get2bytes(fp));
-		nsh -> timesUsed ++;
+		nsh = getStackFromLibrary(get2bytes(stream));
+		nsh->timesUsed ++;
 	} else {
 		stackDebug((stackfp, "loadStackRef (new one)\n"));
 
@@ -197,9 +193,9 @@ stackHandler *loadStackRef(FILE *fp) {
 
 		nsh = new stackHandler;
 		if (! checkNew(nsh)) return NULL;
-		nsh -> last = NULL;
-		nsh -> first = loadStack(fp, & nsh->last);
-		nsh -> timesUsed = 1;
+		nsh->last = NULL;
+		nsh->first = loadStack(stream, &nsh->last);
+		nsh->timesUsed = 1;
 		stackDebug((stackfp, "  first = %p\n", nsh->first));
 		if (nsh->first)
 			stackDebug((stackfp, "  first->next = %p\n", nsh->first->next));
@@ -211,8 +207,8 @@ stackHandler *loadStackRef(FILE *fp) {
 
 		stackLibrary *s = new stackLibrary;
 		if (! checkNew(s)) return NULL;
-		s -> stack = nsh;
-		s -> next = stackLib;
+		s->stack = nsh;
+		s->next = stackLib;
 		stackLib = s;
 		stackLibTotal ++;
 	}
@@ -222,8 +218,7 @@ stackHandler *loadStackRef(FILE *fp) {
 //----------------------------------------------------------------------
 // For saving and loading variables...
 //----------------------------------------------------------------------
-
-bool saveVariable(variable *from, FILE *fp) {
+bool saveVariable(variable *from, Common::WriteStream *stream) {
 #if DEBUG_STACKINESS
 	{
 		char *str = getTextFromAnyVar(*from);
@@ -232,29 +227,29 @@ bool saveVariable(variable *from, FILE *fp) {
 	}
 #endif
 
-	fputc(from -> varType, fp);
-	switch (from -> varType) {
+	putch(from->varType, stream);
+	switch (from->varType) {
 	case SVT_INT:
 	case SVT_FUNC:
 	case SVT_BUILT:
 	case SVT_FILE:
 	case SVT_OBJTYPE:
-		put4bytes(from -> varData.intValue, fp);
+		put4bytes(from->varData.intValue, stream);
 		return true;
 
 	case SVT_STRING:
-		writeString(from -> varData.theString, fp);
+		writeString(from->varData.theString, stream);
 		return true;
 
 	case SVT_STACK:
-		return saveStackRef(from -> varData.theStack, fp);
+		return saveStackRef(from->varData.theStack, stream);
 
 	case SVT_COSTUME:
-		saveCostume(from -> varData.costumeHandler, fp);
+		saveCostume(from->varData.costumeHandler, stream);
 		return false;
 
 	case SVT_ANIM:
-		saveAnim(from -> varData.animHandler, fp);
+		saveAnim(from->varData.animHandler, stream);
 		return false;
 
 	case SVT_NULL:
@@ -269,23 +264,23 @@ bool saveVariable(variable *from, FILE *fp) {
 	return true;
 }
 
-bool loadVariable(variable *to, FILE *fp) {
-	to -> varType = (variableType) fgetc(fp);
-	switch (to -> varType) {
+bool loadVariable(variable *to, Common::SeekableReadStream *stream) {
+	to->varType = (variableType)getch(stream);
+	switch (to->varType) {
 	case SVT_INT:
 	case SVT_FUNC:
 	case SVT_BUILT:
 	case SVT_FILE:
 	case SVT_OBJTYPE:
-		to -> varData.intValue = get4bytes(fp);
+		to->varData.intValue = get4bytes(stream);
 		return true;
 
 	case SVT_STRING:
-		to -> varData.theString = readString(fp);
+		to->varData.theString = readString(stream);
 		return true;
 
 	case SVT_STACK:
-		to -> varData.theStack = loadStackRef(fp);
+		to->varData.theStack = loadStackRef(stream);
 #if DEBUG_STACKINESS
 		{
 			char *str = getTextFromAnyVar(*to);
@@ -296,15 +291,15 @@ bool loadVariable(variable *to, FILE *fp) {
 		return true;
 
 	case SVT_COSTUME:
-		to -> varData.costumeHandler = new persona;
-		if (! checkNew(to -> varData.costumeHandler)) return false;
-		loadCostume(to -> varData.costumeHandler, fp);
+		to->varData.costumeHandler = new persona;
+		if (! checkNew(to->varData.costumeHandler)) return false;
+		loadCostume(to->varData.costumeHandler, stream);
 		return true;
 
 	case SVT_ANIM:
-		to -> varData.animHandler = new personaAnimation;
-		if (! checkNew(to -> varData.animHandler)) return false;
-		loadAnim(to -> varData.animHandler, fp);
+		to->varData.animHandler = new personaAnimation;
+		if (! checkNew(to->varData.animHandler)) return false;
+		loadAnim(to->varData.animHandler, stream);
 		return true;
 
 	default:
@@ -316,34 +311,32 @@ bool loadVariable(variable *to, FILE *fp) {
 //----------------------------------------------------------------------
 // For saving and loading functions
 //----------------------------------------------------------------------
-
-void saveFunction(loadedFunction *fun, FILE *fp) {
+void saveFunction(loadedFunction *fun, Common::WriteStream *stream) {
 	int a;
-	put2bytes(fun -> originalNumber, fp);
-	if (fun -> calledBy) {
-		fputc(1, fp);
-		saveFunction(fun -> calledBy, fp);
+	put2bytes(fun->originalNumber, stream);
+	if (fun->calledBy) {
+		putch(1, stream);
+		saveFunction(fun->calledBy, stream);
 	} else {
-		fputc(0, fp);
+		putch(0, stream);
 	}
-	put4bytes(fun -> timeLeft, fp);
-	put2bytes(fun -> runThisLine, fp);
-	fputc(fun -> cancelMe, fp);
-	fputc(fun -> returnSomething, fp);
-	fputc(fun -> isSpeech, fp);
-	saveVariable(& (fun -> reg), fp);
+	put4bytes(fun->timeLeft, stream);
+	put2bytes(fun->runThisLine, stream);
+	putch(fun->cancelMe, stream);
+	putch(fun->returnSomething, stream);
+	putch(fun->isSpeech, stream);
+	saveVariable(&(fun->reg), stream);
 
-	if (fun -> freezerLevel) {
+	if (fun->freezerLevel) {
 		fatal(ERROR_GAME_SAVE_FROZEN);
 	}
-	saveStack(fun -> stack, fp);
-	for (a = 0; a < fun -> numLocals; a ++) {
-		saveVariable(& (fun -> localVars[a]), fp);
+	saveStack(fun->stack, stream);
+	for (a = 0; a < fun->numLocals; ++a) {
+		saveVariable(&(fun->localVars[a]), stream);
 	}
 }
 
-
-loadedFunction *loadFunction(FILE *fp) {
+loadedFunction *loadFunction(Common::SeekableReadStream *stream) {
 	int a;
 
 	// Reserve memory...
@@ -353,31 +346,31 @@ loadedFunction *loadFunction(FILE *fp) {
 
 	// See what it was called by and load if we need to...
 
-	buildFunc -> originalNumber = get2bytes(fp);
-	buildFunc -> calledBy = NULL;
-	if (fgetc(fp)) {
-		buildFunc -> calledBy = loadFunction(fp);
-		if (! buildFunc -> calledBy) return NULL;
+	buildFunc->originalNumber = get2bytes(stream);
+	buildFunc->calledBy = NULL;
+	if (getch(stream)) {
+		buildFunc->calledBy = loadFunction(stream);
+		if (! buildFunc->calledBy) return NULL;
 	}
 
-	buildFunc -> timeLeft = get4bytes(fp);
-	buildFunc -> runThisLine = get2bytes(fp);
-	buildFunc -> freezerLevel = 0;
-	buildFunc -> cancelMe = fgetc(fp);
-	buildFunc -> returnSomething = fgetc(fp);
-	buildFunc -> isSpeech = fgetc(fp);
-	loadVariable(& (buildFunc -> reg), fp);
+	buildFunc->timeLeft = get4bytes(stream);
+	buildFunc->runThisLine = get2bytes(stream);
+	buildFunc->freezerLevel = 0;
+	buildFunc->cancelMe = getch(stream);
+	buildFunc->returnSomething = getch(stream);
+	buildFunc->isSpeech = getch(stream);
+	loadVariable(&(buildFunc->reg), stream);
 	loadFunctionCode(buildFunc);
 
-	buildFunc -> stack = loadStack(fp, NULL);
+	buildFunc->stack = loadStack(stream, NULL);
 
-	for (a = 0; a < buildFunc -> numLocals; a ++) {
-		loadVariable(& (buildFunc -> localVars[a]), fp);
+	for (a = 0; a < buildFunc->numLocals; ++a) {
+		loadVariable(&(buildFunc->localVars[a]), stream);
 	}
 
 	return buildFunc;
 }
-#endif
+
 //----------------------------------------------------------------------
 // Save everything
 //----------------------------------------------------------------------
@@ -397,7 +390,7 @@ bool saveGame(char *fname) {
 
 	if (! saveThumbnail(fp)) return false;
 
-	fwrite(& fileTime, sizeof(FILETIME), 1, fp);
+	fwrite(&fileTime, sizeof(FILETIME), 1, fp);
 
 	// DON'T ADD ANYTHING NEW BEFORE THIS POINT!
 
@@ -435,25 +428,25 @@ bool saveGame(char *fname) {
 	int countFunctions = 0;
 	while (thisFunction) {
 		countFunctions ++;
-		thisFunction = thisFunction -> next;
+		thisFunction = thisFunction->next;
 	}
 	put2bytes(countFunctions, fp);
 
 	thisFunction = allRunningFunctions;
 	while (thisFunction) {
 		saveFunction(thisFunction, fp);
-		thisFunction = thisFunction -> next;
+		thisFunction = thisFunction->next;
 	}
 
-	for (a = 0; a < numGlobals; a ++) {
-		saveVariable(& globalVars[a], fp);
+	for (a = 0; a < numGlobals; ++a) {
+		saveVariable(&globalVars[a], fp);
 	}
 
 	savePeople(fp);
 
-	if (currentFloor -> numPolygons) {
+	if (currentFloor->numPolygons) {
 		fputc(1, fp);
-		put2bytes(currentFloor -> originalNum, fp);
+		put2bytes(currentFloor->originalNum, fp);
 	} else fputc(0, fp);
 
 	if (zBuffer.tex) {
@@ -516,7 +509,7 @@ bool loadGame(char *fname) {
 		if (! skipThumbnail(fp)) return fatal(ERROR_GAME_LOAD_CORRUPT, fname);
 	}
 
-	size_t bytes_read = fread(& savedGameTime, sizeof(FILETIME), 1, fp);
+	size_t bytes_read = fread(&savedGameTime, sizeof(FILETIME), 1, fp);
 	if (bytes_read != sizeof(FILETIME) && ferror(fp)) {
 		debugOut("Reading error in loadGame.\n");
 	}
@@ -546,7 +539,7 @@ bool loadGame(char *fname) {
 			charOrder = new char[257];
 			if (! checkNew(charOrder)) return false;
 
-			for (int a = 0; a < 256; a ++) {
+			for (int a = 0; a < 256; ++a) {
 				x = fgetc(fp);
 				charOrder[x] = a;
 			}
@@ -584,20 +577,20 @@ bool loadGame(char *fname) {
 	mouseCursorFrameNum = get2bytes(fp);
 
 	loadedFunction *rFunc;
-	loadedFunction * * buildList = & allRunningFunctions;
+	loadedFunction * * buildList = &allRunningFunctions;
 
 
 	int countFunctions = get2bytes(fp);
 	while (countFunctions --) {
 		rFunc = loadFunction(fp);
-		rFunc -> next = NULL;
+		rFunc->next = NULL;
 		(* buildList) = rFunc;
-		buildList = & (rFunc -> next);
+		buildList = &(rFunc->next);
 	}
 
-	for (a = 0; a < numGlobals; a ++) {
+	for (a = 0; a < numGlobals; ++a) {
 		unlinkVar(globalVars[a]);
-		loadVariable(& globalVars[a], fp);
+		loadVariable(&globalVars[a], fp);
 	}
 
 	loadPeople(fp);
diff --git a/engines/sludge/loadsave.h b/engines/sludge/loadsave.h
index b91e872..87024f2 100644
--- a/engines/sludge/loadsave.h
+++ b/engines/sludge/loadsave.h
@@ -27,10 +27,15 @@ namespace Sludge {
 bool saveGame(char *fname);
 bool loadGame(char *fname);
 
-#if ALLOW_FILE
-loadedFunction *loadFunction(FILE *fp);
-void saveFunction(loadedFunction *fun, FILE *fp);
-#endif
+bool saveVariable(variable *from, Common::WriteStream *stream);
+bool loadVariable(variable *to, Common::SeekableReadStream *stream);
+
+variableStack *loadStack(Common::SeekableReadStream *stream, variableStack **last);
+bool saveStackRef(stackHandler *vs, Common::WriteStream *stream);
+stackHandler *loadStackRef(Common::SeekableReadStream *stream);
+
+loadedFunction *loadFunction(Common::SeekableReadStream *stream);
+void saveFunction(loadedFunction *fun, Common::WriteStream *stream);
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index 47bfe67..b278a35 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -138,9 +138,7 @@ void setGameFilePath(char *f) {
 #endif
 }
 
-#if ALLOW_FILE
-void saveHSI(FILE *writer);
-#endif
+void saveHSI(Common::WriteStream *writer);
 
 extern bool reallyWantToQuit;
 
@@ -440,9 +438,8 @@ try
 	initStatusBar();
 	resetRandW();
 
-#if ALLOW_FILE
 	gameName = getNumberedString(1);
-#endif
+
 #if 0
 	SDL_WM_SetCaption(gameName, gameName);
 
diff --git a/engines/sludge/memwatch.cpp b/engines/sludge/memwatch.cpp
index d316687..34e8605 100644
--- a/engines/sludge/memwatch.cpp
+++ b/engines/sludge/memwatch.cpp
@@ -21,12 +21,15 @@
  */
 #include "allfiles.h"
 
+#include "common/debug.h"
+
 namespace Sludge {
 
 void *allKnownMem[3000];
 int allKnownNum = 0;
 
 void outputKnownMem() {
+#if 0
 	FILE *debu = fopen("debuTURN.txt", "at");
 
 	fprintf(debu, "%i lumps:", allKnownNum);
@@ -35,6 +38,7 @@ void outputKnownMem() {
 	}
 	fprintf(debu, "\n");
 	fclose(debu);
+#endif
 }
 
 void adding(void *mem) {
@@ -43,8 +47,10 @@ void adding(void *mem) {
 
 	outputKnownMem();
 	if (allKnownNum == 3000) {
-		//db ("Error! Array too full!");
+		debug("Error! Array too full!");
+#if 0
 		exit(1);
+#endif
 	}
 }
 
@@ -57,8 +63,10 @@ void deleting(void *mem) {
 			return;
 		}
 	}
+#if 0
 	//db ("Error! Deleted a block which hasn't been allocated!");
 	exit(1);
+#endif
 }
 
 } // End of namespace Sludge
diff --git a/engines/sludge/module.mk b/engines/sludge/module.mk
index 78f41dd..bad7f35 100644
--- a/engines/sludge/module.mk
+++ b/engines/sludge/module.mk
@@ -8,6 +8,7 @@ MODULE_OBJS := \
 	cursors.o \
 	debug.o \
 	detection.o \
+	fileset.o \
 	floor.o \
 	freeze.o \
 	fonttext.o \
@@ -17,6 +18,7 @@ MODULE_OBJS := \
 	line.o \
 	loadsave.o \
 	main_loop.o \
+	memwatch.o \
 	moreio.o \
 	movie.o \
 	newfatal.o \
@@ -33,15 +35,13 @@ MODULE_OBJS := \
 	stringy.o \
 	talk.o \
 	thumbnail.o \
+	timing.o \
 	transition.o \
 	variable.o \
 	zbuffer.o \
 	CommonCode/utf8.o \
-#	fileset.o \
-	linuxstuff.o \
-	memwatch.o \
+#	linuxstuff.o \
 	shaders.o \
-	timing.o \
 	libwebm/mkvparser.o \
 	libwebm/mkvreader.o \
  
diff --git a/engines/sludge/moreio.cpp b/engines/sludge/moreio.cpp
index b8dc3f9..8bb0d77 100644
--- a/engines/sludge/moreio.cpp
+++ b/engines/sludge/moreio.cpp
@@ -24,7 +24,10 @@
 #include "newfatal.h"
 #include "stringy.h"
 
-#include "debug.h"
+#include "sludge.h"
+
+#include "common/debug.h"
+#include "common/file.h"
 
 #if defined __unix__ && !(defined __APPLE__)
 #include <endian.h>
@@ -37,43 +40,48 @@ namespace Sludge {
 
 bool allowAnyFilename = true;
 
-#if ALLOW_FILE
-int get2bytes(FILE *fp) {
+int getch(Common::SeekableReadStream *stream) {
+	return stream->readByte();
+}
+
+void putch(int c, Common::WriteStream *stream) {
+	stream->writeByte(c);
+}
+
+int get2bytes(Common::SeekableReadStream *stream) {
 	int f1, f2;
 
-	f1 = fgetc(fp);
-	f2 = fgetc(fp);
+	f1 = getch(stream);
+	f2 = getch(stream);
 
 	return (f1 * 256 + f2);
 }
 
-void put2bytes(int numtoput, FILE *fp) {
-	fputc((char)(numtoput / 256), fp);
-	fputc((char)(numtoput % 256), fp);
+void put2bytes(int numtoput, Common::WriteStream *stream) {
+	putch((char)(numtoput / 256), stream);
+	putch((char)(numtoput % 256), stream);
 }
 
-void writeString(char *s, FILE *fp) {
+void writeString(char *s, Common::WriteStream *stream) {
 	int a, len = strlen(s);
-	put2bytes(len, fp);
-	for (a = 0; a < len; a ++) {
-		fputc(s[a] + 1, fp);
+	put2bytes(len, stream);
+	for (a = 0; a < len; ++a) {
+		putch(s[a] + 1, stream);
 	}
 }
 
 
-char *readString(FILE *fp) {
-
-	int a, len = get2bytes(fp);
-	//debugOut ("MOREIO: readString - len %i\n", len);
+char *readString(Common::SeekableReadStream *stream) {
+	int a, len = get2bytes(stream);
 	char *s = new char[len + 1];
-	if (! checkNew(s)) {
+	if (!checkNew(s)) {
 		return NULL;
 	}
-	for (a = 0; a < len; a ++) {
-		s[a] = (char)(fgetc(fp) - 1);
+	for (a = 0; a < len; ++a) {
+		s[a] = (char)(getch(stream) - 1);
 	}
 	s[len] = 0;
-	//debugOut ("MOREIO: readString: %s\n", s);
+	debug(kSludgeDebugDataLoad, "Read string of length %i: %s", len, s);
 	return s;
 }
 
@@ -92,11 +100,12 @@ float floatSwap(float f) {
 }
 
 
-float getFloat(FILE *fp) {
+float getFloat(Common::SeekableReadStream *stream) {
 	float f;
-	size_t bytes_read = fread(& f, sizeof(float), 1, fp);
-	if (bytes_read != sizeof(float) && ferror(fp)) {
-		debugOut("Reading error in getFloat.\n");
+	size_t bytes_read = stream->read(&f, sizeof(float));
+			//fread(& f, sizeof(float), 1, fp);
+	if (bytes_read != sizeof(float) && stream->err()) {
+		debug("Reading error in getFloat.\n");
 	}
 
 #ifdef  __BIG_ENDIAN__
@@ -106,11 +115,12 @@ float getFloat(FILE *fp) {
 #endif
 }
 
-void putFloat(float f, FILE *fp) {
+void putFloat(float f, Common::WriteStream *stream) {
 #ifdef  __BIG_ENDIAN__
 	f = floatSwap(f);
 #endif
-	fwrite(& f, sizeof(float), 1, fp);
+	stream->write(&f,sizeof(float));
+	//fwrite(& f, sizeof(float), 1, fp);
 }
 
 short shortSwap(short s) {
@@ -123,11 +133,11 @@ short shortSwap(short s) {
 }
 
 
-short getSigned(FILE *fp) {
+short getSigned(Common::SeekableReadStream *stream) {
 	short f;
-	size_t bytes_read = fread(& f, sizeof(short), 1, fp);
-	if (bytes_read != sizeof(short) && ferror(fp)) {
-		debugOut("Reading error in getSigned.\n");
+	size_t bytes_read = stream->read(&f, sizeof(short));
+	if (bytes_read != sizeof(short) && stream->err()) {
+		debug("Reading error in getSigned.\n");
 	}
 #ifdef  __BIG_ENDIAN__
 	f = shortSwap(f);
@@ -135,39 +145,32 @@ short getSigned(FILE *fp) {
 	return f;
 }
 
-void putSigned(short f, FILE *fp) {
+void putSigned(short f, Common::WriteStream *stream) {
 #ifdef  __BIG_ENDIAN__
 	f = shortSwap(f);
 #endif
-	fwrite(& f, sizeof(short), 1, fp);
+	stream->write(&f, sizeof(short));
 }
 
 
 // The following two functions treat signed integers as unsigned.
 // That's done on purpose.
 
-int32_t get4bytes(FILE *fp) {
+int32_t get4bytes(Common::SeekableReadStream *stream) {
 	int f1, f2, f3, f4;
 
-	f1 = fgetc(fp);
-	f2 = fgetc(fp);
-	f3 = fgetc(fp);
-	f4 = fgetc(fp);
+	f1 = getch(stream);
+	f2 = getch(stream);
+	f3 = getch(stream);
+	f4 = getch(stream);
 
 	unsigned int x = f1 + f2 * 256 + f3 * 256 * 256 + f4 * 256 * 256 * 256;
 
 	return x;
-
-	/*
-
-	    int32_t f;
-	    fread (& f, sizeof (int32_t), 1, fp);
-	    return f;*/
 }
 
 
-void put4bytes(unsigned int i, FILE *fp) {
-	//  fwrite (&i, sizeof (long int), 1, fp);
+void put4bytes(unsigned int i, Common::WriteStream *stream) {
 	unsigned char f1, f2, f3, f4;
 
 	f4 = i / (256 * 256 * 256);
@@ -177,17 +180,17 @@ void put4bytes(unsigned int i, FILE *fp) {
 	f2 = i / 256;
 	f1 = i % 256;
 
-	fputc(f1, fp);
-	fputc(f2, fp);
-	fputc(f3, fp);
-	fputc(f4, fp);
+	putch(f1, stream);
+	putch(f2, stream);
+	putch(f3, stream);
+	putch(f4, stream);
 }
-#endif
+
 char *encodeFilename(char *nameIn) {
-	if (! nameIn) return NULL;
+	if (!nameIn) return NULL;
 	if (allowAnyFilename) {
 		char *newName = new char[strlen(nameIn) * 2 + 1];
-		if (! checkNew(newName)) return NULL;
+		if (!checkNew(newName)) return NULL;
 
 		int i = 0;
 		while (*nameIn) {
@@ -243,7 +246,7 @@ char *encodeFilename(char *nameIn) {
 		return newName;
 	} else {
 		int a;
-		for (a = 0; nameIn[a]; a ++) {
+		for (a = 0; nameIn[a]; ++a) {
 #ifdef _WIN32
 			if (nameIn[a] == '/') nameIn[a] = '\\';
 #else
@@ -258,7 +261,7 @@ char *encodeFilename(char *nameIn) {
 char *decodeFilename(char *nameIn) {
 	if (allowAnyFilename) {
 		char *newName = new char[strlen(nameIn) + 1];
-		if (! checkNew(newName)) return NULL;
+		if (!checkNew(newName)) return NULL;
 
 		int i = 0;
 		while (* nameIn) {
diff --git a/engines/sludge/moreio.h b/engines/sludge/moreio.h
index 5d107a8..9c2287b 100644
--- a/engines/sludge/moreio.h
+++ b/engines/sludge/moreio.h
@@ -26,18 +26,22 @@
 
 namespace Sludge {
 
-#if ALLOW_FILE
-int get2bytes(FILE *fp);
-void put2bytes(int numtoput, FILE *fp);
-char *readString(FILE *fp);
-void writeString(char *s, FILE *fp);
-void putFloat(float f, FILE *fp);
-float getFloat(FILE *fp);
-void putSigned(short f, FILE *fp);
-short getSigned(FILE *fp);
-int32_t get4bytes(FILE *fp);
-void put4bytes(uint32_t f, FILE *fp);
-#endif
+// Read
+int getch(Common::SeekableReadStream *stream);
+int get2bytes(Common::SeekableReadStream *stream);
+char *readString(Common::SeekableReadStream *stream);
+float getFloat(Common::SeekableReadStream *stream);
+short getSigned(Common::SeekableReadStream *stream);
+int32_t get4bytes(Common::SeekableReadStream *stream);
+
+// Write
+void putch(int c, Common::WriteStream *stream);
+void put2bytes(int numtoput, Common::WriteStream *stream);
+void writeString(char *s, Common::WriteStream *stream);
+void putFloat(float f, Common::WriteStream *stream);
+void putSigned(short f, Common::WriteStream *stream);
+void put4bytes(uint32_t f, Common::WriteStream *stream);
+
 char *encodeFilename(char *nameIn);
 char *decodeFilename(char *nameIn);
 
diff --git a/engines/sludge/newfatal.cpp b/engines/sludge/newfatal.cpp
index f05de5c..5c8a36d 100644
--- a/engines/sludge/newfatal.cpp
+++ b/engines/sludge/newfatal.cpp
@@ -95,9 +95,8 @@ int inFatal(const char *str) {
 	fatalMessage = copyString(str);
 	if (fatalMessage == NULL) fatalMessage = copyString("Out of memory");
 
-#if 0
+
 	killSoundStuff();
-#endif
 
 #if defined(HAVE_GLES2)
 	EGL_Close();
@@ -123,7 +122,7 @@ void setFatalInfo(const char *userFunc, const char *BIF) {
 	delete fatalInfo;
 	fatalInfo = new char [strlen(userFunc) + strlen(BIF) + 38];
 	if (fatalInfo) sprintf(fatalInfo, "Currently in this sub: %s\nCalling: %s", userFunc, BIF);
-	debug("%s\n", fatalInfo);
+	debug("%s", fatalInfo);
 }
 
 void setResourceForFatal(int n) {
diff --git a/engines/sludge/objtypes.cpp b/engines/sludge/objtypes.cpp
index 58572b0..ba70977 100644
--- a/engines/sludge/objtypes.cpp
+++ b/engines/sludge/objtypes.cpp
@@ -50,24 +50,23 @@ objectType *findObjectType(int i) {
 }
 
 objectType *loadObjectType(int i) {
-#if ALLOW_FILE
 	int a, nameNum;
 	objectType *newType = new objectType;
 
 	if (checkNew(newType)) {
 		if (openObjectSlice(i)) {
 			nameNum = get2bytes(bigDataFile);
-			newType -> r = (byte) fgetc(bigDataFile);
-			newType -> g = (byte) fgetc(bigDataFile);
-			newType -> b = (byte) fgetc(bigDataFile);
-			newType -> speechGap = fgetc(bigDataFile);
-			newType -> walkSpeed = fgetc(bigDataFile);
+			newType -> r = (byte) getch(bigDataFile);
+			newType -> g = (byte) getch(bigDataFile);
+			newType -> b = (byte) getch(bigDataFile);
+			newType -> speechGap = getch(bigDataFile);
+			newType -> walkSpeed = getch(bigDataFile);
 			newType -> wrapSpeech = get4bytes(bigDataFile);
 			newType -> spinSpeed = get2bytes(bigDataFile);
 
 			if (gameVersion >= VERSION(1, 6)) {
 				// aaLoad
-				fgetc(bigDataFile);
+				getch(bigDataFile);
 				getFloat(bigDataFile);
 				getFloat(bigDataFile);
 			}
@@ -111,23 +110,21 @@ objectType *loadObjectType(int i) {
 			return newType;
 		}
 	}
-#endif
+
 	return NULL;
 }
 
-#if ALLOW_FILE
-objectType *loadObjectRef(FILE *fp) {
-	objectType *r = loadObjectType(get2bytes(fp));
+objectType *loadObjectRef(Common::SeekableReadStream *stream) {
+	objectType *r = loadObjectType(get2bytes(stream));
 	delete r -> screenName;
-	r -> screenName = readString(fp);
+	r -> screenName = readString(stream);
 	return r;
 }
 
-void saveObjectRef(objectType *r, FILE *fp) {
-	put2bytes(r -> objectNum, fp);
-	writeString(r -> screenName, fp);
+void saveObjectRef(objectType *r, Common::WriteStream *stream) {
+	put2bytes(r -> objectNum, stream);
+	writeString(r -> screenName, stream);
 }
-#endif
 
 int getCombinationFunction(int withThis, int thisObject) {
 	int i, num = 0;
diff --git a/engines/sludge/objtypes.h b/engines/sludge/objtypes.h
index f61c845..0bd785a 100644
--- a/engines/sludge/objtypes.h
+++ b/engines/sludge/objtypes.h
@@ -44,10 +44,8 @@ objectType *findObjectType(int i);
 objectType *loadObjectType(int i);
 int getCombinationFunction(int a, int b);
 void removeObjectType(objectType *oT);
-#if ALLOW_FILE
-void saveObjectRef(objectType *r, FILE *fp);
-objectType *loadObjectRef(FILE *fp);
-#endif
+void saveObjectRef(objectType *r, Common::WriteStream *stream);
+objectType *loadObjectRef(Common::SeekableReadStream *stream);
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index f54b1ff..6430d35 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -71,36 +71,36 @@ inline int TF_abs(int a) {
 }
 
 void setFrames(onScreenPerson &m, int a) {
-	m.myAnim = m.myPersona -> animation[(a * m.myPersona -> numDirections) + m.direction];
+	m.myAnim = m.myPersona->animation[(a * m.myPersona->numDirections) + m.direction];
 }
 
 personaAnimation *createPersonaAnim(int num, variableStack *&stacky) {
 	personaAnimation *newP = new personaAnimation;
 	checkNew(newP);
 
-	newP -> numFrames = num;
-	newP -> frames = new animFrame[num];
-	checkNew(newP -> frames);
+	newP->numFrames = num;
+	newP->frames = new animFrame[num];
+	checkNew(newP->frames);
 
 	int a = num, frameNum, howMany;
 
 	while (a) {
 		a --;
-		newP -> frames[a].noise = 0;
-		if (stacky -> thisVar.varType == SVT_FILE) {
-			newP -> frames[a].noise = stacky -> thisVar.varData.intValue;
-		} else if (stacky -> thisVar.varType == SVT_FUNC) {
-			newP -> frames[a].noise = - stacky -> thisVar.varData.intValue;
-		} else if (stacky -> thisVar.varType == SVT_STACK) {
-			getValueType(frameNum, SVT_INT, stacky -> thisVar.varData.theStack -> first -> thisVar);
-			getValueType(howMany, SVT_INT, stacky -> thisVar.varData.theStack -> first -> next -> thisVar);
+		newP->frames[a].noise = 0;
+		if (stacky->thisVar.varType == SVT_FILE) {
+			newP->frames[a].noise = stacky->thisVar.varData.intValue;
+		} else if (stacky->thisVar.varType == SVT_FUNC) {
+			newP->frames[a].noise = - stacky->thisVar.varData.intValue;
+		} else if (stacky->thisVar.varType == SVT_STACK) {
+			getValueType(frameNum, SVT_INT, stacky->thisVar.varData.theStack->first->thisVar);
+			getValueType(howMany, SVT_INT, stacky->thisVar.varData.theStack->first->next->thisVar);
 		} else {
-			getValueType(frameNum, SVT_INT, stacky -> thisVar);
+			getValueType(frameNum, SVT_INT, stacky->thisVar);
 			howMany = 1;
 		}
 		trimStack(stacky);
-		newP -> frames[a].frameNum = frameNum;
-		newP -> frames[a].howMany = howMany;
+		newP->frames[a].frameNum = frameNum;
+		newP->frames[a].howMany = howMany;
 	}
 
 	return newP;
@@ -108,39 +108,39 @@ personaAnimation *createPersonaAnim(int num, variableStack *&stacky) {
 
 personaAnimation *makeNullAnim() {
 	personaAnimation *newAnim  = new personaAnimation;
-	if (! checkNew(newAnim)) return NULL;
+	if (!checkNew(newAnim)) return NULL;
 
 
-	newAnim -> theSprites       = NULL;
-	newAnim -> numFrames        = 0;
-	newAnim -> frames           = NULL;
+	newAnim->theSprites       = NULL;
+	newAnim->numFrames        = 0;
+	newAnim->frames           = NULL;
 	return newAnim;
 }
 
 personaAnimation *copyAnim(personaAnimation *orig) {
-	int num = orig -> numFrames;
+	int num = orig->numFrames;
 
 	personaAnimation *newAnim  = new personaAnimation;
-	if (! checkNew(newAnim)) return NULL;
+	if (!checkNew(newAnim)) return NULL;
 
 	// Copy the easy bits...
-	newAnim -> theSprites       = orig -> theSprites;
-	newAnim -> numFrames        = num;
+	newAnim->theSprites       = orig->theSprites;
+	newAnim->numFrames        = num;
 
 	if (num) {
 
-		// Argh! Frames! We need a whole NEW array of animFrame structures...
+		// Argh!Frames!We need a whole NEW array of animFrame structures...
 
 		newAnim->frames = new animFrame[num];
-		if (! checkNew(newAnim->frames)) return NULL;
+		if (!checkNew(newAnim->frames)) return NULL;
 
-		for (int a = 0; a < num; a ++) {
-			newAnim -> frames[a].frameNum = orig -> frames[a].frameNum;
-			newAnim -> frames[a].howMany = orig -> frames[a].howMany;
-			newAnim -> frames[a].noise = orig -> frames[a].noise;
+		for (int a = 0; a < num; ++a) {
+			newAnim->frames[a].frameNum = orig->frames[a].frameNum;
+			newAnim->frames[a].howMany = orig->frames[a].howMany;
+			newAnim->frames[a].noise = orig->frames[a].noise;
 		}
 	} else {
-		newAnim -> frames = NULL;
+		newAnim->frames = NULL;
 	}
 
 	return newAnim;
@@ -149,8 +149,8 @@ personaAnimation *copyAnim(personaAnimation *orig) {
 void deleteAnim(personaAnimation *orig) {
 
 	if (orig) {
-		if (orig -> numFrames) {
-			delete[] orig -> frames;
+		if (orig->numFrames) {
+			delete[] orig->frames;
 		}
 		delete orig;
 		orig = NULL;
@@ -158,11 +158,11 @@ void deleteAnim(personaAnimation *orig) {
 }
 
 void turnMeAngle(onScreenPerson *thisPerson, int direc) {
-	int d = thisPerson -> myPersona -> numDirections;
-	thisPerson -> angle = direc;
-	direc += (180 / d) + 180 + thisPerson -> angleOffset;
+	int d = thisPerson->myPersona->numDirections;
+	thisPerson->angle = direc;
+	direc += (180 / d) + 180 + thisPerson->angleOffset;
 	while (direc >= 360) direc -= 360;
-	thisPerson -> direction = (direc * d) / 360;
+	thisPerson->direction = (direc * d) / 360;
 }
 
 bool initPeople() {
@@ -175,36 +175,36 @@ bool initPeople() {
 }
 
 void spinStep(onScreenPerson *thisPerson) {
-	int diff = (thisPerson -> angle + 360) - thisPerson -> wantAngle;
-	int eachSlice = thisPerson -> spinSpeed ? thisPerson -> spinSpeed : (360 / thisPerson -> myPersona -> numDirections);
+	int diff = (thisPerson->angle + 360) - thisPerson->wantAngle;
+	int eachSlice = thisPerson->spinSpeed ? thisPerson->spinSpeed : (360 / thisPerson->myPersona->numDirections);
 	while (diff > 180) {
 		diff -= 360;
 	}
 
 	if (diff >= eachSlice) {
-		turnMeAngle(thisPerson, thisPerson -> angle - eachSlice);
+		turnMeAngle(thisPerson, thisPerson->angle - eachSlice);
 	} else if (diff <= - eachSlice) {
-		turnMeAngle(thisPerson, thisPerson -> angle + eachSlice);
+		turnMeAngle(thisPerson, thisPerson->angle + eachSlice);
 	} else {
-		turnMeAngle(thisPerson, thisPerson -> wantAngle);
-		thisPerson -> spinning = false;
+		turnMeAngle(thisPerson, thisPerson->wantAngle);
+		thisPerson->spinning = false;
 	}
 }
 
 void rethinkAngle(onScreenPerson *thisPerson) {
-	int d = thisPerson -> myPersona -> numDirections;
-	int direc = thisPerson -> angle + (180 / d) + 180 + thisPerson -> angleOffset;
+	int d = thisPerson->myPersona->numDirections;
+	int direc = thisPerson->angle + (180 / d) + 180 + thisPerson->angleOffset;
 	while (direc >= 360) direc -= 360;
-	thisPerson -> direction = (direc * d) / 360;
+	thisPerson->direction = (direc * d) / 360;
 }
 
 bool turnPersonToFace(int thisNum, int direc) {
 	onScreenPerson *thisPerson = findPerson(thisNum);
 	if (thisPerson) {
-		if (thisPerson -> continueAfterWalking) abortFunction(thisPerson -> continueAfterWalking);
-		thisPerson -> continueAfterWalking = NULL;
-		thisPerson -> walking = false;
-		thisPerson -> spinning = false;
+		if (thisPerson->continueAfterWalking) abortFunction(thisPerson->continueAfterWalking);
+		thisPerson->continueAfterWalking = NULL;
+		thisPerson->walking = false;
+		thisPerson->spinning = false;
 		turnMeAngle(thisPerson, direc);
 		setFrames(* thisPerson, (thisPerson == speech->currentTalker) ? ANI_TALK : ANI_STAND);
 		return true;
@@ -215,8 +215,8 @@ bool turnPersonToFace(int thisNum, int direc) {
 bool setPersonExtra(int thisNum, int extra) {
 	onScreenPerson *thisPerson = findPerson(thisNum);
 	if (thisPerson) {
-		thisPerson -> extra = extra;
-		if (extra & EXTRA_NOSCALE) thisPerson -> scale = 1;
+		thisPerson->extra = extra;
+		if (extra & EXTRA_NOSCALE) thisPerson->scale = 1;
 		return true;
 	}
 	return false;
@@ -236,8 +236,8 @@ void moveAndScale(onScreenPerson &me, float x, float y) {
 onScreenPerson *findPerson(int v) {
 	onScreenPerson *thisPerson = allPeople;
 	while (thisPerson) {
-		if (v == thisPerson -> thisType -> objectNum) break;
-		thisPerson = thisPerson -> next;
+		if (v == thisPerson->thisType->objectNum) break;
+		thisPerson = thisPerson->next;
 	}
 	return thisPerson;
 }
@@ -249,7 +249,7 @@ void movePerson(int x, int y, int objNum) {
 
 void setShown(bool h, int ob) {
 	onScreenPerson *moveMe = findPerson(ob);
-	if (moveMe) moveMe -> show = h;
+	if (moveMe) moveMe->show = h;
 }
 
 enum drawModes {
@@ -384,14 +384,14 @@ void setMyDrawMode(onScreenPerson *moveMe, int h) {
 
 void setDrawMode(int h, int ob) {
 	onScreenPerson *moveMe = findPerson(ob);
-	if (! moveMe) return;
+	if (!moveMe) return;
 
 	setMyDrawMode(moveMe, h);
 }
 
 void setPersonTransparency(int ob, unsigned char x) {
 	onScreenPerson *moveMe = findPerson(ob);
-	if (! moveMe) return;
+	if (!moveMe) return;
 
 	if (x > 254) x = 254;
 	moveMe->transparency = x;
@@ -399,7 +399,7 @@ void setPersonTransparency(int ob, unsigned char x) {
 
 void setPersonColourise(int ob, unsigned char r, unsigned char g, unsigned char b, unsigned char colourmix) {
 	onScreenPerson *moveMe = findPerson(ob);
-	if (! moveMe) return;
+	if (!moveMe) return;
 
 	moveMe->r = r;
 	moveMe->g = g;
@@ -415,23 +415,23 @@ void shufflePeople() {
 	onScreenPerson * * thisReference = & allPeople;
 	onScreenPerson *A, * B;
 
-	if (! allPeople) return;
+	if (!allPeople) return;
 
-	while ((* thisReference) -> next) {
-		float y1 = (* thisReference) -> y;
-		if ((* thisReference) -> extra & EXTRA_FRONT) y1 += 1000;
+	while ((* thisReference)->next) {
+		float y1 = (* thisReference)->y;
+		if ((* thisReference)->extra & EXTRA_FRONT) y1 += 1000;
 
-		float y2 = (* thisReference) -> next -> y;
-		if ((* thisReference) -> next -> extra & EXTRA_FRONT) y2 += 1000;
+		float y2 = (* thisReference)->next->y;
+		if ((* thisReference)->next->extra & EXTRA_FRONT) y2 += 1000;
 
 		if (y1 > y2) {
 			A = (* thisReference);
-			B = (* thisReference) -> next;
-			A -> next = B -> next;
-			B -> next = A;
+			B = (* thisReference)->next;
+			A->next = B->next;
+			B->next = A;
 			(* thisReference) = B;
 		} else {
-			thisReference = & ((* thisReference) -> next);
+			thisReference = & ((* thisReference)->next);
 		}
 	}
 }
@@ -446,62 +446,62 @@ void drawPeople() {
 	overRegion = NULL;
 
 	while (thisPerson) {
-		if (thisPerson -> show) {
-			myAnim = thisPerson -> myAnim;
-			if (myAnim != thisPerson -> lastUsedAnim) {
-				thisPerson -> lastUsedAnim = myAnim;
-				thisPerson -> frameNum = 0;
-				thisPerson -> frameTick = myAnim -> frames[0].howMany;
-				if (myAnim -> frames[thisPerson -> frameNum].noise > 0) {
-					startSound(myAnim -> frames[thisPerson -> frameNum].noise, false);
-					thisPerson -> frameNum ++;
-					thisPerson -> frameNum %= thisPerson -> myAnim -> numFrames;
-					thisPerson -> frameTick = thisPerson -> myAnim -> frames[thisPerson -> frameNum].howMany;
-				} else if (myAnim -> frames[thisPerson -> frameNum].noise) {
-					startNewFunctionNum(- myAnim -> frames[thisPerson -> frameNum].noise, 0, NULL, noStack);
-					thisPerson -> frameNum ++;
-					thisPerson -> frameNum %= thisPerson -> myAnim -> numFrames;
-					thisPerson -> frameTick = thisPerson -> myAnim -> frames[thisPerson -> frameNum].howMany;
+		if (thisPerson->show) {
+			myAnim = thisPerson->myAnim;
+			if (myAnim != thisPerson->lastUsedAnim) {
+				thisPerson->lastUsedAnim = myAnim;
+				thisPerson->frameNum = 0;
+				thisPerson->frameTick = myAnim->frames[0].howMany;
+				if (myAnim->frames[thisPerson->frameNum].noise > 0) {
+					startSound(myAnim->frames[thisPerson->frameNum].noise, false);
+					thisPerson->frameNum ++;
+					thisPerson->frameNum %= thisPerson->myAnim->numFrames;
+					thisPerson->frameTick = thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
+				} else if (myAnim->frames[thisPerson->frameNum].noise) {
+					startNewFunctionNum(- myAnim->frames[thisPerson->frameNum].noise, 0, NULL, noStack);
+					thisPerson->frameNum ++;
+					thisPerson->frameNum %= thisPerson->myAnim->numFrames;
+					thisPerson->frameTick = thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
 				}
 			}
-			int fNumSign = myAnim -> frames[thisPerson -> frameNum].frameNum;
+			int fNumSign = myAnim->frames[thisPerson->frameNum].frameNum;
 			int m = fNumSign < 0;
 			int fNum = abs(fNumSign);
-			if (fNum >= myAnim -> theSprites -> bank.total) {
+			if (fNum >= myAnim->theSprites->bank.total) {
 				fNum = 0;
 				m = 2 - m;
 			}
 			if (m != 2) {
 				bool r = false;
-				r = scaleSprite(myAnim->theSprites->bank.sprites[fNum], myAnim -> theSprites -> bank.myPalette, thisPerson, m);
+				r = scaleSprite(myAnim->theSprites->bank.sprites[fNum], myAnim->theSprites->bank.myPalette, thisPerson, m);
 				if (r) {
-					if (thisPerson -> thisType -> screenName[0]) {
-						if (personRegion.thisType != thisPerson -> thisType) lastRegion = NULL;
-						personRegion.thisType = thisPerson -> thisType;
+					if (thisPerson->thisType->screenName[0]) {
+						if (personRegion.thisType != thisPerson->thisType) lastRegion = NULL;
+						personRegion.thisType = thisPerson->thisType;
 						overRegion = & personRegion;
 					}
 				}
 			}
 		}
-		if (! -- thisPerson -> frameTick) {
-			thisPerson -> frameNum ++;
-			thisPerson -> frameNum %= thisPerson -> myAnim -> numFrames;
-			thisPerson -> frameTick = thisPerson -> myAnim -> frames[thisPerson -> frameNum].howMany;
-			if (thisPerson -> show && myAnim && myAnim -> frames) {
-				if (myAnim -> frames[thisPerson -> frameNum].noise > 0) {
-					startSound(myAnim -> frames[thisPerson -> frameNum].noise, false);
-					thisPerson -> frameNum ++;
-					thisPerson -> frameNum %= thisPerson -> myAnim -> numFrames;
-					thisPerson -> frameTick = thisPerson -> myAnim -> frames[thisPerson -> frameNum].howMany;
-				} else if (myAnim -> frames[thisPerson -> frameNum].noise) {
-					startNewFunctionNum(- myAnim -> frames[thisPerson -> frameNum].noise, 0, NULL, noStack);
-					thisPerson -> frameNum ++;
-					thisPerson -> frameNum %= thisPerson -> myAnim -> numFrames;
-					thisPerson -> frameTick = thisPerson -> myAnim -> frames[thisPerson -> frameNum].howMany;
+		if (!-- thisPerson->frameTick) {
+			thisPerson->frameNum ++;
+			thisPerson->frameNum %= thisPerson->myAnim->numFrames;
+			thisPerson->frameTick = thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
+			if (thisPerson->show && myAnim && myAnim->frames) {
+				if (myAnim->frames[thisPerson->frameNum].noise > 0) {
+					startSound(myAnim->frames[thisPerson->frameNum].noise, false);
+					thisPerson->frameNum ++;
+					thisPerson->frameNum %= thisPerson->myAnim->numFrames;
+					thisPerson->frameTick = thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
+				} else if (myAnim->frames[thisPerson->frameNum].noise) {
+					startNewFunctionNum(- myAnim->frames[thisPerson->frameNum].noise, 0, NULL, noStack);
+					thisPerson->frameNum ++;
+					thisPerson->frameNum %= thisPerson->myAnim->numFrames;
+					thisPerson->frameTick = thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
 				}
 			}
 		}
-		thisPerson = thisPerson -> next;
+		thisPerson = thisPerson->next;
 	}
 }
 
@@ -521,14 +521,14 @@ bool handleClosestPoint(int &setX, int &setY, int &setPoly) {
 //	FILE * dbug = fopen ("debug_closest.txt", "at");
 //	fprintf (dbug, "\nGetting closest point to %i, %i\n", setX, setY);
 
-	for (i = 0; i < currentFloor -> numPolygons; i ++) {
-		oldJ = currentFloor -> polygon[i].numVertices - 1;
-		for (j = 0; j < currentFloor -> polygon[i].numVertices; j ++) {
+	for (i = 0; i < currentFloor->numPolygons; i ++) {
+		oldJ = currentFloor->polygon[i].numVertices - 1;
+		for (j = 0; j < currentFloor->polygon[i].numVertices; j ++) {
 //			fprintf (dbug, "Polygon %i, line %i... ", i, j);
-			xTest1 = currentFloor -> vertex[currentFloor -> polygon[i].vertexID[j]].x;
-			yTest1 = currentFloor -> vertex[currentFloor -> polygon[i].vertexID[j]].y;
-			xTest2 = currentFloor -> vertex[currentFloor -> polygon[i].vertexID[oldJ]].x;
-			yTest2 = currentFloor -> vertex[currentFloor -> polygon[i].vertexID[oldJ]].y;
+			xTest1 = currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].x;
+			yTest1 = currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].y;
+			xTest2 = currentFloor->vertex[currentFloor->polygon[i].vertexID[oldJ]].x;
+			yTest2 = currentFloor->vertex[currentFloor->polygon[i].vertexID[oldJ]].y;
 			closestPointOnLine(closestX, closestY, xTest1, yTest1, xTest2, yTest2, setX, setY);
 //			fprintf (dbug, "closest point is %i, %i... ", closestX, closestY);
 			xTest1 = setX - closestX;
@@ -537,7 +537,7 @@ bool handleClosestPoint(int &setX, int &setY, int &setPoly) {
 //			fprintf (dbug, "Distance squared %i\n", thisDistance);
 
 			if (thisDistance < currentDistance) {
-//				fprintf (dbug, "** We have a new winner! **\n");
+//				fprintf (dbug, "** We have a new winner!**\n");
 
 				currentDistance = thisDistance;
 				gotX = closestX;
@@ -558,28 +558,28 @@ bool handleClosestPoint(int &setX, int &setY, int &setPoly) {
 }
 
 bool doBorderStuff(onScreenPerson *moveMe) {
-	if (moveMe -> inPoly == moveMe -> walkToPoly) {
-		moveMe -> inPoly = -1;
-		moveMe -> thisStepX = moveMe -> walkToX;
-		moveMe -> thisStepY = moveMe -> walkToY;
+	if (moveMe->inPoly == moveMe->walkToPoly) {
+		moveMe->inPoly = -1;
+		moveMe->thisStepX = moveMe->walkToX;
+		moveMe->thisStepY = moveMe->walkToY;
 	} else {
 		// The section in which we need to be next...
-		int newPoly = currentFloor -> matrix[moveMe -> inPoly][moveMe -> walkToPoly];
+		int newPoly = currentFloor->matrix[moveMe->inPoly][moveMe->walkToPoly];
 		if (newPoly == -1) return false;
 
 		// Grab the index of the second matching corner...
 		int ID, ID2;
-		if (! getMatchingCorners(currentFloor -> polygon[moveMe -> inPoly], currentFloor -> polygon[newPoly], ID, ID2))
+		if (!getMatchingCorners(currentFloor->polygon[moveMe->inPoly], currentFloor->polygon[newPoly], ID, ID2))
 			return fatal("Not a valid floor plan!");
 
 		// Remember that we're walking to the new polygon...
-		moveMe -> inPoly = newPoly;
+		moveMe->inPoly = newPoly;
 
 		// Calculate the destination position on the coincidantal line...
-		int x1 = moveMe -> x, y1 = moveMe -> y;
-		int x2 = moveMe -> walkToX, y2 = moveMe -> walkToY;
-		int x3 = currentFloor -> vertex[ID].x, y3 = currentFloor -> vertex[ID].y;
-		int x4 = currentFloor -> vertex[ID2].x, y4 = currentFloor -> vertex[ID2].y;
+		int x1 = moveMe->x, y1 = moveMe->y;
+		int x2 = moveMe->walkToX, y2 = moveMe->walkToY;
+		int x3 = currentFloor->vertex[ID].x, y3 = currentFloor->vertex[ID].y;
+		int x4 = currentFloor->vertex[ID2].x, y4 = currentFloor->vertex[ID2].y;
 
 		int xAB = x1 - x2;
 		int yAB = y1 - y2;
@@ -590,8 +590,8 @@ bool doBorderStuff(onScreenPerson *moveMe) {
 		m /= ((xAB * yCD) - (yAB * xCD));
 
 		if (m > 0 && m < 1) {
-			moveMe -> thisStepX = x3 + m * xCD;
-			moveMe -> thisStepY = y3 + m * yCD;
+			moveMe->thisStepX = x3 + m * xCD;
+			moveMe->thisStepY = y3 + m * yCD;
 		} else {
 			int dx13 = x1 - x3, dx14 = x1 - x4, dx23 = x2 - x3, dx24 = x2 - x4;
 			int dy13 = y1 - y3, dy14 = y1 - y4, dy23 = y2 - y3, dy24 = y2 - y4;
@@ -607,20 +607,20 @@ bool doBorderStuff(onScreenPerson *moveMe) {
 
 			if (sqrt((double) dx13 + dy13) + sqrt((double) dx23 + dy23) <
 			        sqrt((double) dx14 + dy14) + sqrt((double) dx24 + dy24)) {
-				moveMe -> thisStepX = x3;
-				moveMe -> thisStepY = y3;
+				moveMe->thisStepX = x3;
+				moveMe->thisStepY = y3;
 			} else {
-				moveMe -> thisStepX = x4;
-				moveMe -> thisStepY = y4;
+				moveMe->thisStepX = x4;
+				moveMe->thisStepY = y4;
 			}
 		}
 	}
 
-	float yDiff = moveMe -> thisStepY - moveMe -> y;
-	float xDiff = moveMe -> x - moveMe -> thisStepX;
+	float yDiff = moveMe->thisStepY - moveMe->y;
+	float xDiff = moveMe->x - moveMe->thisStepX;
 	if (xDiff || yDiff) {
-		moveMe -> wantAngle = 180 + ANGLEFIX * atan2(xDiff, yDiff * 2);
-		moveMe -> spinning = true;
+		moveMe->wantAngle = 180 + ANGLEFIX * atan2(xDiff, yDiff * 2);
+		moveMe->spinning = true;
 	}
 
 	setFrames(* moveMe, ANI_WALK);
@@ -631,72 +631,72 @@ bool walkMe(onScreenPerson *thisPerson, bool move = true) {
 	float xDiff, yDiff, maxDiff, s;
 
 	for (;;) {
-		xDiff = thisPerson -> thisStepX - thisPerson -> x;
-		yDiff = (thisPerson -> thisStepY - thisPerson -> y) * 2;
-		s = thisPerson -> scale * thisPerson -> walkSpeed;
+		xDiff = thisPerson->thisStepX - thisPerson->x;
+		yDiff = (thisPerson->thisStepY - thisPerson->y) * 2;
+		s = thisPerson->scale * thisPerson->walkSpeed;
 		if (s < 0.2) s = 0.2;
 
 		maxDiff = (TF_abs(xDiff) >= TF_abs(yDiff)) ? TF_abs(xDiff) : TF_abs(yDiff);
 
 		if (TF_abs(maxDiff) > s) {
-			if (thisPerson -> spinning) {
+			if (thisPerson->spinning) {
 				spinStep(thisPerson);
 				setFrames(* thisPerson, ANI_WALK);
 			}
 			s = maxDiff / s;
 			if (move)
 				moveAndScale(* thisPerson,
-				             thisPerson -> x + xDiff / s,
-				             thisPerson -> y + yDiff / (s * 2));
+				             thisPerson->x + xDiff / s,
+				             thisPerson->y + yDiff / (s * 2));
 			return true;
 		}
 
-		if (thisPerson -> inPoly == -1) {
-			if (thisPerson -> directionWhenDoneWalking != -1) {
-				thisPerson -> wantAngle = thisPerson -> directionWhenDoneWalking;
-				thisPerson -> spinning = true;
+		if (thisPerson->inPoly == -1) {
+			if (thisPerson->directionWhenDoneWalking != -1) {
+				thisPerson->wantAngle = thisPerson->directionWhenDoneWalking;
+				thisPerson->spinning = true;
 				spinStep(thisPerson);
 			}
 			break;
 		}
-		if (! doBorderStuff(thisPerson)) break;
+		if (!doBorderStuff(thisPerson)) break;
 	}
 
-	thisPerson -> walking = false;
+	thisPerson->walking = false;
 	setFrames(* thisPerson, ANI_STAND);
 	moveAndScale(* thisPerson,
-	             thisPerson -> walkToX,
-	             thisPerson -> walkToY);
+	             thisPerson->walkToX,
+	             thisPerson->walkToY);
 	return false;
 }
 
 bool makeWalkingPerson(int x, int y, int objNum, loadedFunction *func, int di) {
 	if (x == 0 && y == 0) return false;
-	if (currentFloor -> numPolygons == 0) return false;
+	if (currentFloor->numPolygons == 0) return false;
 	onScreenPerson *moveMe = findPerson(objNum);
-	if (! moveMe) return false;
-
-	if (moveMe -> continueAfterWalking) abortFunction(moveMe -> continueAfterWalking);
-	moveMe -> continueAfterWalking = NULL;
-	moveMe -> walking = true;
-	moveMe -> directionWhenDoneWalking = di;
-
-	moveMe -> walkToX = x;
-	moveMe -> walkToY = y;
-	moveMe -> walkToPoly = inFloor(x, y);
-	if (moveMe -> walkToPoly == -1) {
-		if (! handleClosestPoint(moveMe -> walkToX, moveMe -> walkToY, moveMe -> walkToPoly)) return false;
+	if (!moveMe) return false;
+
+	if (moveMe->continueAfterWalking) abortFunction(moveMe->continueAfterWalking);
+	moveMe->continueAfterWalking = NULL;
+	moveMe->walking = true;
+	moveMe->directionWhenDoneWalking = di;
+
+	moveMe->walkToX = x;
+	moveMe->walkToY = y;
+	moveMe->walkToPoly = inFloor(x, y);
+	if (moveMe->walkToPoly == -1) {
+		if (!handleClosestPoint(moveMe->walkToX, moveMe->walkToY, moveMe->walkToPoly)) return false;
 	}
 
-	moveMe -> inPoly = inFloor(moveMe -> x, moveMe -> y);
-	if (moveMe -> inPoly == -1) {
-		int xxx = moveMe -> x, yyy = moveMe -> y;
-		if (! handleClosestPoint(xxx, yyy, moveMe -> inPoly)) return false;
+	moveMe->inPoly = inFloor(moveMe->x, moveMe->y);
+	if (moveMe->inPoly == -1) {
+		int xxx = moveMe->x, yyy = moveMe->y;
+		if (!handleClosestPoint(xxx, yyy, moveMe->inPoly)) return false;
 	}
 
 	doBorderStuff(moveMe);
-	if (walkMe(moveMe, false) || moveMe -> spinning) {
-		moveMe -> continueAfterWalking = func;
+	if (walkMe(moveMe, false) || moveMe->spinning) {
+		moveMe->continueAfterWalking = func;
 		return true;
 	} else {
 		return false;
@@ -706,11 +706,11 @@ bool makeWalkingPerson(int x, int y, int objNum, loadedFunction *func, int di) {
 bool stopPerson(int o) {
 	onScreenPerson *moveMe = findPerson(o);
 	if (moveMe)
-		if (moveMe -> continueAfterWalking) {
-			abortFunction(moveMe -> continueAfterWalking);
-			moveMe -> continueAfterWalking = NULL;
-			moveMe -> walking = false;
-			moveMe -> spinning = false;
+		if (moveMe->continueAfterWalking) {
+			abortFunction(moveMe->continueAfterWalking);
+			moveMe->continueAfterWalking = NULL;
+			moveMe->walking = false;
+			moveMe->spinning = false;
 			setFrames(* moveMe, ANI_STAND);
 			return true;
 		}
@@ -720,24 +720,24 @@ bool stopPerson(int o) {
 bool forceWalkingPerson(int x, int y, int objNum, loadedFunction *func, int di) {
 	if (x == 0 && y == 0) return false;
 	onScreenPerson *moveMe = findPerson(objNum);
-	if (! moveMe) return false;
+	if (!moveMe) return false;
 
-	if (moveMe -> continueAfterWalking) abortFunction(moveMe -> continueAfterWalking);
-	moveMe -> walking = true;
-	moveMe -> continueAfterWalking = NULL;
-	moveMe -> directionWhenDoneWalking = di;
+	if (moveMe->continueAfterWalking) abortFunction(moveMe->continueAfterWalking);
+	moveMe->walking = true;
+	moveMe->continueAfterWalking = NULL;
+	moveMe->directionWhenDoneWalking = di;
 
-	moveMe -> walkToX = x;
-	moveMe -> walkToY = y;
+	moveMe->walkToX = x;
+	moveMe->walkToY = y;
 
 	// Let's pretend the start and end points are both in the same
 	// polygon (which one isn't important)
-	moveMe -> inPoly = 0;
-	moveMe -> walkToPoly = 0;
+	moveMe->inPoly = 0;
+	moveMe->walkToPoly = 0;
 
 	doBorderStuff(moveMe);
-	if (walkMe(moveMe) || moveMe -> spinning) {
-		moveMe -> continueAfterWalking = func;
+	if (walkMe(moveMe) || moveMe->spinning) {
+		moveMe->continueAfterWalking = func;
 		return true;
 	} else {
 		return false;
@@ -747,26 +747,26 @@ bool forceWalkingPerson(int x, int y, int objNum, loadedFunction *func, int di)
 void jumpPerson(int x, int y, int objNum) {
 	if (x == 0 && y == 0) return;
 	onScreenPerson *moveMe = findPerson(objNum);
-	if (! moveMe) return;
-	if (moveMe -> continueAfterWalking) abortFunction(moveMe -> continueAfterWalking);
-	moveMe -> continueAfterWalking = NULL;
-	moveMe -> walking = false;
-	moveMe -> spinning = false;
+	if (!moveMe) return;
+	if (moveMe->continueAfterWalking) abortFunction(moveMe->continueAfterWalking);
+	moveMe->continueAfterWalking = NULL;
+	moveMe->walking = false;
+	moveMe->spinning = false;
 	moveAndScale(* moveMe, x, y);
 }
 
 bool floatCharacter(int f, int objNum) {
 	onScreenPerson *moveMe = findPerson(objNum);
-	if (! moveMe) return false;
-	moveMe -> floaty = f;
+	if (!moveMe) return false;
+	moveMe->floaty = f;
 	return true;
 }
 
 bool setCharacterWalkSpeed(int f, int objNum) {
 	if (f <= 0) return false;
 	onScreenPerson *moveMe = findPerson(objNum);
-	if (! moveMe) return false;
-	moveMe -> walkSpeed = f;
+	if (!moveMe) return false;
+	moveMe->walkSpeed = f;
 	return true;
 }
 
@@ -774,82 +774,82 @@ void walkAllPeople() {
 	onScreenPerson *thisPerson = allPeople;
 
 	while (thisPerson) {
-		if (thisPerson -> walking) {
+		if (thisPerson->walking) {
 			walkMe(thisPerson);
-		} else if (thisPerson -> spinning) {
+		} else if (thisPerson->spinning) {
 			spinStep(thisPerson);
 			setFrames(* thisPerson, ANI_STAND);
 		}
-		if ((! thisPerson -> walking) && (! thisPerson -> spinning) && thisPerson -> continueAfterWalking) {
-			restartFunction(thisPerson -> continueAfterWalking);
-			thisPerson -> continueAfterWalking = NULL;
+		if ((!thisPerson->walking) && (!thisPerson->spinning) && thisPerson->continueAfterWalking) {
+			restartFunction(thisPerson->continueAfterWalking);
+			thisPerson->continueAfterWalking = NULL;
 		}
-		thisPerson = thisPerson -> next;
+		thisPerson = thisPerson->next;
 	}
 }
 
 bool addPerson(int x, int y, int objNum, persona *p) {
 	onScreenPerson *newPerson = new onScreenPerson;
-	if (! checkNew(newPerson)) return false;
+	if (!checkNew(newPerson)) return false;
 
 	// EASY STUFF
-	newPerson -> thisType = loadObjectType(objNum);
-	newPerson -> scale = 1;
-	newPerson -> extra = 0;
-	newPerson -> continueAfterWalking = NULL;
+	newPerson->thisType = loadObjectType(objNum);
+	newPerson->scale = 1;
+	newPerson->extra = 0;
+	newPerson->continueAfterWalking = NULL;
 	moveAndScale(* newPerson, x, y);
-	newPerson -> frameNum = 0;
-	newPerson -> walkToX = x;
-	newPerson -> walkToY = y;
-	newPerson -> walking = false;
-	newPerson -> spinning = false;
-	newPerson -> show = true;
-	newPerson -> direction = 0;
-	newPerson -> angle = 180;
-	newPerson -> wantAngle = 180;
-	newPerson -> angleOffset = 0;
-	newPerson -> floaty = 0;
-	newPerson -> walkSpeed = newPerson -> thisType -> walkSpeed;
-	newPerson -> myAnim = NULL;
-	newPerson -> spinSpeed = newPerson -> thisType -> spinSpeed;
-	newPerson -> r = 0;
-	newPerson -> g = 0;
-	newPerson -> b = 0;
-	newPerson -> colourmix = 0;
-	newPerson -> transparency = 0;
-	newPerson -> myPersona = p;
+	newPerson->frameNum = 0;
+	newPerson->walkToX = x;
+	newPerson->walkToY = y;
+	newPerson->walking = false;
+	newPerson->spinning = false;
+	newPerson->show = true;
+	newPerson->direction = 0;
+	newPerson->angle = 180;
+	newPerson->wantAngle = 180;
+	newPerson->angleOffset = 0;
+	newPerson->floaty = 0;
+	newPerson->walkSpeed = newPerson->thisType->walkSpeed;
+	newPerson->myAnim = NULL;
+	newPerson->spinSpeed = newPerson->thisType->spinSpeed;
+	newPerson->r = 0;
+	newPerson->g = 0;
+	newPerson->b = 0;
+	newPerson->colourmix = 0;
+	newPerson->transparency = 0;
+	newPerson->myPersona = p;
 
 	setFrames(* newPerson, ANI_STAND);
 
 	// HEIGHT (BASED ON 1st FRAME OF 1st ANIMATION... INC. SPECIAL CASES)
-	int fNumSigned = p -> animation[0] -> frames[0].frameNum;
+	int fNumSigned = p->animation[0]->frames[0].frameNum;
 	int fNum = abs(fNumSigned);
-	if (fNum >= p -> animation[0] -> theSprites -> bank.total) {
+	if (fNum >= p->animation[0]->theSprites->bank.total) {
 		if (fNumSigned < 0) {
-			newPerson -> height = 5;
+			newPerson->height = 5;
 		} else {
-			newPerson -> height = p -> animation[0] -> theSprites -> bank.sprites[0].yhot + 5;
+			newPerson->height = p->animation[0]->theSprites->bank.sprites[0].yhot + 5;
 		}
 	} else {
-		newPerson -> height = p -> animation[0] -> theSprites -> bank.sprites[fNum].yhot + 5;
+		newPerson->height = p->animation[0]->theSprites->bank.sprites[fNum].yhot + 5;
 	}
 
 	// NOW ADD IT IN THE RIGHT PLACE
 	onScreenPerson * * changethat = & allPeople;
 
-	while (((* changethat) != NULL) && ((* changethat) -> y < y))
-		changethat = & ((* changethat) -> next);
+	while (((* changethat) != NULL) && ((* changethat)->y < y))
+		changethat = & ((* changethat)->next);
 
-	newPerson -> next = (* changethat);
+	newPerson->next = (* changethat);
 	(* changethat) = newPerson;
 
-	return (bool)(newPerson -> thisType != NULL);
+	return (bool)(newPerson->thisType != NULL);
 }
 
 int timeForAnim(personaAnimation *fram) {
 	int total = 0;
-	for (int a = 0; a < fram -> numFrames; a ++) {
-		total += fram -> frames[a].howMany;
+	for (int a = 0; a < fram->numFrames; ++a) {
+		total += fram->frames[a].howMany;
 	}
 	return total;
 }
@@ -857,22 +857,22 @@ int timeForAnim(personaAnimation *fram) {
 void animatePerson(int obj, personaAnimation *fram) {   // Set a new SINGLE animation
 	onScreenPerson *moveMe = findPerson(obj);
 	if (moveMe) {
-		if (moveMe -> continueAfterWalking) abortFunction(moveMe -> continueAfterWalking);
-		moveMe -> continueAfterWalking = NULL;
-		moveMe -> walking = false;
-		moveMe -> spinning = false;
-		moveMe -> myAnim = fram;
+		if (moveMe->continueAfterWalking) abortFunction(moveMe->continueAfterWalking);
+		moveMe->continueAfterWalking = NULL;
+		moveMe->walking = false;
+		moveMe->spinning = false;
+		moveMe->myAnim = fram;
 	}
 }
 
 void animatePerson(int obj, persona *per) {             // Set a new costume
 	onScreenPerson *moveMe = findPerson(obj);
 	if (moveMe) {
-		//  if (moveMe -> continueAfterWalking) abortFunction (moveMe -> continueAfterWalking);
-		//  moveMe -> continueAfterWalking = NULL;
-		//  moveMe -> walking = false;
-		moveMe -> spinning = false;
-		moveMe -> myPersona = per;
+		//  if (moveMe->continueAfterWalking) abortFunction (moveMe->continueAfterWalking);
+		//  moveMe->continueAfterWalking = NULL;
+		//  moveMe->walking = false;
+		moveMe->spinning = false;
+		moveMe->myPersona = per;
 		rethinkAngle(moveMe);
 		if (moveMe-> walking) {
 			setFrames(* moveMe, ANI_WALK);
@@ -885,11 +885,11 @@ void animatePerson(int obj, persona *per) {             // Set a new costume
 void killAllPeople() {
 	onScreenPerson *killPeople;
 	while (allPeople) {
-		if (allPeople -> continueAfterWalking) abortFunction(allPeople -> continueAfterWalking);
-		allPeople -> continueAfterWalking = NULL;
+		if (allPeople->continueAfterWalking) abortFunction(allPeople->continueAfterWalking);
+		allPeople->continueAfterWalking = NULL;
 		killPeople = allPeople;
-		allPeople = allPeople -> next;
-		removeObjectType(killPeople -> thisType);
+		allPeople = allPeople->next;
+		removeObjectType(killPeople->thisType);
 		delete killPeople;
 	}
 }
@@ -899,18 +899,18 @@ void killMostPeople() {
 	onScreenPerson * * lookyHere = & allPeople;
 
 	while (* lookyHere) {
-		if ((* lookyHere) -> extra & EXTRA_NOREMOVE) {
-			lookyHere = & (* lookyHere) -> next;
+		if ((* lookyHere)->extra & EXTRA_NOREMOVE) {
+			lookyHere = & (* lookyHere)->next;
 		} else {
 			killPeople = (* lookyHere);
 
 			// Change last pointer to NEXT in the list instead
-			(* lookyHere) = killPeople -> next;
+			(* lookyHere) = killPeople->next;
 
 			// Gone from the list... now free some memory
-			if (killPeople -> continueAfterWalking) abortFunction(killPeople -> continueAfterWalking);
-			killPeople -> continueAfterWalking = NULL;
-			removeObjectType(killPeople -> thisType);
+			if (killPeople->continueAfterWalking) abortFunction(killPeople->continueAfterWalking);
+			killPeople->continueAfterWalking = NULL;
+			removeObjectType(killPeople->thisType);
 			delete killPeople;
 		}
 	}
@@ -924,69 +924,68 @@ void removeOneCharacter(int i) {
 			overRegion = NULL;
 		}
 
-		if (p -> continueAfterWalking) abortFunction(p -> continueAfterWalking);
-		p -> continueAfterWalking = NULL;
+		if (p->continueAfterWalking) abortFunction(p->continueAfterWalking);
+		p->continueAfterWalking = NULL;
 		onScreenPerson * * killPeople;
 
 		for (killPeople = & allPeople;
 		        * killPeople != p;
-		        killPeople = & ((* killPeople) -> next)) {
+		        killPeople = & ((* killPeople)->next)) {
 			;
 		}
 
-		* killPeople = p -> next;
-		removeObjectType(p -> thisType);
+		* killPeople = p->next;
+		removeObjectType(p->thisType);
 		delete p;
 	}
 }
 
-#if ALLOW_FILE
-bool saveAnim(personaAnimation *p, FILE *fp) {
-	put2bytes(p -> numFrames, fp);
-	if (p -> numFrames) {
-		put4bytes(p -> theSprites -> ID, fp);
+bool saveAnim(personaAnimation *p, Common::WriteStream *stream) {
+	put2bytes(p->numFrames, stream);
+	if (p->numFrames) {
+		put4bytes(p->theSprites->ID, stream);
 
-		for (int a = 0; a < p -> numFrames; a ++) {
-			put4bytes(p -> frames[a].frameNum, fp);
-			put4bytes(p -> frames[a].howMany, fp);
-			put4bytes(p -> frames[a].noise, fp);
+		for (int a = 0; a < p->numFrames; ++a) {
+			put4bytes(p->frames[a].frameNum, stream);
+			put4bytes(p->frames[a].howMany, stream);
+			put4bytes(p->frames[a].noise, stream);
 		}
 	}
 	return true;
 }
 
-bool loadAnim(personaAnimation *p, FILE *fp) {
-	p -> numFrames = get2bytes(fp);
+bool loadAnim(personaAnimation *p, Common::SeekableReadStream *stream) {
+	p->numFrames = get2bytes(stream);
 
-	if (p -> numFrames) {
-		int a = get4bytes(fp);
-		p -> frames = new animFrame[p -> numFrames];
-		if (! checkNew(p -> frames)) return false;
-		p -> theSprites = loadBankForAnim(a);
+	if (p->numFrames) {
+		int a = get4bytes(stream);
+		p->frames = new animFrame[p->numFrames];
+		if (!checkNew(p->frames)) return false;
+		p->theSprites = loadBankForAnim(a);
 
-		for (a = 0; a < p -> numFrames; a ++) {
-			p -> frames[a].frameNum = get4bytes(fp);
-			p -> frames[a].howMany = get4bytes(fp);
+		for (a = 0; a < p->numFrames; ++a) {
+			p->frames[a].frameNum = get4bytes(stream);
+			p->frames[a].howMany = get4bytes(stream);
 			if (ssgVersion >= VERSION(2, 0)) {
-				p -> frames[a].noise = get4bytes(fp);
+				p->frames[a].noise = get4bytes(stream);
 			} else {
-				p -> frames[a].noise = 0;
+				p->frames[a].noise = 0;
 			}
 		}
 	} else {
-		p -> theSprites = NULL;
-		p -> frames = NULL;
+		p->theSprites = NULL;
+		p->frames = NULL;
 	}
 	return true;
 }
 /*
 void debugCostume (char * message, persona * cossy) {
     FILE * db = fopen ("debuTURN.txt", "at");
-    fprintf (db, "  %s costume with %i directions...\n", message, cossy -> numDirections);
-    for (int a = 0; a < cossy -> numDirections * 3; a ++) {
-        fprintf (db, "      %i frames:", cossy -> animation[a] -> numFrames);
-        for (int b = 0; b < cossy -> animation[a] -> numFrames; b ++) {
-            fprintf (db, " %i", cossy -> animation[a] -> frames[b]);
+    fprintf (db, "  %s costume with %i directions...\n", message, cossy->numDirections);
+    for (int a = 0; a < cossy->numDirections * 3; ++a) {
+        fprintf (db, "      %i frames:", cossy->animation[a]->numFrames);
+        for (int b = 0; b < cossy->animation[a]->numFrames; b ++) {
+            fprintf (db, " %i", cossy->animation[a]->frames[b]);
         }
         fprintf (db, "\n");
 
@@ -994,188 +993,187 @@ void debugCostume (char * message, persona * cossy) {
     fclose (db);
 }
 */
-bool saveCostume(persona *cossy, FILE *fp) {
+bool saveCostume(persona *cossy, Common::WriteStream *stream) {
 	int a;
-	put2bytes(cossy -> numDirections, fp);
-	for (a = 0; a < cossy -> numDirections * 3; a ++) {
-		if (! saveAnim(cossy -> animation[a], fp)) return false;
+	put2bytes(cossy->numDirections, stream);
+	for (a = 0; a < cossy->numDirections * 3; ++a) {
+		if (!saveAnim(cossy->animation[a], stream)) return false;
 	}
 //	debugCostume ("Saved", cossy);
 	return true;
 }
 
-bool loadCostume(persona *cossy, FILE *fp) {
+bool loadCostume(persona *cossy, Common::SeekableReadStream *stream) {
 	int a;
-	cossy -> numDirections = get2bytes(fp);
-	cossy -> animation = new personaAnimation * [cossy -> numDirections * 3];
-	if (! checkNew(cossy -> animation)) return false;
-	for (a = 0; a < cossy -> numDirections * 3; a ++) {
-		cossy -> animation[a] = new personaAnimation;
-		if (! checkNew(cossy -> animation[a])) return false;
-
-		if (! loadAnim(cossy -> animation[a], fp)) return false;
+	cossy->numDirections = get2bytes(stream);
+	cossy->animation = new personaAnimation * [cossy->numDirections * 3];
+	if (!checkNew(cossy->animation)) return false;
+	for (a = 0; a < cossy->numDirections * 3; ++a) {
+		cossy->animation[a] = new personaAnimation;
+		if (!checkNew(cossy->animation[a])) return false;
+
+		if (!loadAnim(cossy->animation[a], stream)) return false;
 	}
 //	debugCostume ("Loaded", cossy);
 	return true;
 }
 
-bool savePeople(FILE *fp) {
+bool savePeople(Common::WriteStream *stream) {
 	onScreenPerson *me = allPeople;
 	int countPeople = 0, a;
 
-	putSigned(scaleHorizon, fp);
-	putSigned(scaleDivide, fp);
+	putSigned(scaleHorizon, stream);
+	putSigned(scaleDivide, stream);
 
 	while (me) {
 		countPeople ++;
-		me = me -> next;
+		me = me->next;
 	}
 
-	put2bytes(countPeople, fp);
+	put2bytes(countPeople, stream);
 
 	me = allPeople;
-	for (a = 0; a < countPeople; a ++) {
-
-		putFloat(me -> x, fp);
-		putFloat(me -> y, fp);
-
-		saveCostume(me -> myPersona, fp);
-		saveAnim(me -> myAnim, fp);
-		fputc(me -> myAnim == me -> lastUsedAnim, fp);
-
-		putFloat(me -> scale, fp);
-
-		put2bytes(me -> extra, fp);
-		put2bytes(me -> height, fp);
-		put2bytes(me -> walkToX, fp);
-		put2bytes(me -> walkToY, fp);
-		put2bytes(me -> thisStepX, fp);
-		put2bytes(me -> thisStepY, fp);
-		put2bytes(me -> frameNum, fp);
-		put2bytes(me -> frameTick, fp);
-		put2bytes(me -> walkSpeed, fp);
-		put2bytes(me -> spinSpeed, fp);
-		putSigned(me -> floaty, fp);
-		fputc(me -> show, fp);
-		fputc(me -> walking, fp);
-		fputc(me -> spinning, fp);
-		if (me -> continueAfterWalking) {
-			fputc(1, fp);
-			saveFunction(me -> continueAfterWalking, fp);
+	for (a = 0; a < countPeople; ++a) {
+
+		putFloat(me->x, stream);
+		putFloat(me->y, stream);
+
+		saveCostume(me->myPersona, stream);
+		saveAnim(me->myAnim, stream);
+		putch(me->myAnim == me->lastUsedAnim, stream);
+
+		putFloat(me->scale, stream);
+
+		put2bytes(me->extra, stream);
+		put2bytes(me->height, stream);
+		put2bytes(me->walkToX, stream);
+		put2bytes(me->walkToY, stream);
+		put2bytes(me->thisStepX, stream);
+		put2bytes(me->thisStepY, stream);
+		put2bytes(me->frameNum, stream);
+		put2bytes(me->frameTick, stream);
+		put2bytes(me->walkSpeed, stream);
+		put2bytes(me->spinSpeed, stream);
+		putSigned(me->floaty, stream);
+		putch(me->show, stream);
+		putch(me->walking, stream);
+		putch(me->spinning, stream);
+		if (me->continueAfterWalking) {
+			putch(1, stream);
+			saveFunction(me->continueAfterWalking, stream);
 		} else {
-			fputc(0, fp);
+			putch(0, stream);
 		}
-		put2bytes(me -> direction, fp);
-		put2bytes(me -> angle, fp);
-		put2bytes(me -> angleOffset, fp);
-		put2bytes(me -> wantAngle, fp);
-		putSigned(me -> directionWhenDoneWalking, fp);
-		putSigned(me -> inPoly, fp);
-		putSigned(me -> walkToPoly, fp);
-
-		fputc(me -> r, fp);
-		fputc(me -> g, fp);
-		fputc(me -> b, fp);
-		fputc(me -> colourmix, fp);
-		fputc(me -> transparency, fp);
-
-		saveObjectRef(me -> thisType, fp);
-
-		me = me -> next;
+		put2bytes(me->direction, stream);
+		put2bytes(me->angle, stream);
+		put2bytes(me->angleOffset, stream);
+		put2bytes(me->wantAngle, stream);
+		putSigned(me->directionWhenDoneWalking, stream);
+		putSigned(me->inPoly, stream);
+		putSigned(me->walkToPoly, stream);
+
+		putch(me->r, stream);
+		putch(me->g, stream);
+		putch(me->b, stream);
+		putch(me->colourmix, stream);
+		putch(me->transparency, stream);
+
+		saveObjectRef(me->thisType, stream);
+
+		me = me->next;
 	}
 	return true;
 }
 
-bool loadPeople(FILE *fp) {
+bool loadPeople(Common::SeekableReadStream *stream) {
 	onScreenPerson * * pointy = & allPeople;
 	onScreenPerson *me;
 
-	scaleHorizon = getSigned(fp);
-	scaleDivide = getSigned(fp);
+	scaleHorizon = getSigned(stream);
+	scaleDivide = getSigned(stream);
 
-	int countPeople = get2bytes(fp);
+	int countPeople = get2bytes(stream);
 	int a;
 
 	allPeople = NULL;
-	for (a = 0; a < countPeople; a ++) {
+	for (a = 0; a < countPeople; ++a) {
 		me = new onScreenPerson;
-		if (! checkNew(me)) return false;
-
-		me -> myPersona = new persona;
-		if (! checkNew(me -> myPersona)) return false;
-
-		me -> myAnim = new personaAnimation;
-		if (! checkNew(me -> myAnim)) return false;
-
-		me -> x = getFloat(fp);
-		me -> y = getFloat(fp);
-
-		loadCostume(me -> myPersona, fp);
-		loadAnim(me -> myAnim, fp);
-
-		me -> lastUsedAnim = fgetc(fp) ? me -> myAnim : NULL;
-
-		me -> scale = getFloat(fp);
-
-		me -> extra = get2bytes(fp);
-		me -> height = get2bytes(fp);
-		me -> walkToX = get2bytes(fp);
-		me -> walkToY = get2bytes(fp);
-		me -> thisStepX = get2bytes(fp);
-		me -> thisStepY = get2bytes(fp);
-		me -> frameNum = get2bytes(fp);
-		me -> frameTick = get2bytes(fp);
-		me -> walkSpeed = get2bytes(fp);
-		me -> spinSpeed = get2bytes(fp);
-		me -> floaty = getSigned(fp);
-		me -> show = fgetc(fp);
-		me -> walking = fgetc(fp);
-		me -> spinning = fgetc(fp);
-		if (fgetc(fp)) {
-			me -> continueAfterWalking = loadFunction(fp);
-			if (! me -> continueAfterWalking) return false;
+		if (!checkNew(me)) return false;
+
+		me->myPersona = new persona;
+		if (!checkNew(me->myPersona)) return false;
+
+		me->myAnim = new personaAnimation;
+		if (!checkNew(me->myAnim)) return false;
+
+		me->x = getFloat(stream);
+		me->y = getFloat(stream);
+
+		loadCostume(me->myPersona, stream);
+		loadAnim(me->myAnim, stream);
+
+		me->lastUsedAnim = getch(stream) ? me->myAnim : NULL;
+
+		me->scale = getFloat(stream);
+
+		me->extra = get2bytes(stream);
+		me->height = get2bytes(stream);
+		me->walkToX = get2bytes(stream);
+		me->walkToY = get2bytes(stream);
+		me->thisStepX = get2bytes(stream);
+		me->thisStepY = get2bytes(stream);
+		me->frameNum = get2bytes(stream);
+		me->frameTick = get2bytes(stream);
+		me->walkSpeed = get2bytes(stream);
+		me->spinSpeed = get2bytes(stream);
+		me->floaty = getSigned(stream);
+		me->show = getch(stream);
+		me->walking = getch(stream);
+		me->spinning = getch(stream);
+		if (getch(stream)) {
+			me->continueAfterWalking = loadFunction(stream);
+			if (!me->continueAfterWalking) return false;
 		} else {
-			me -> continueAfterWalking = NULL;
+			me->continueAfterWalking = NULL;
 		}
-		me -> direction = get2bytes(fp);
-		me -> angle = get2bytes(fp);
+		me->direction = get2bytes(stream);
+		me->angle = get2bytes(stream);
 		if (ssgVersion >= VERSION(2, 0)) {
-			me -> angleOffset = get2bytes(fp);
+			me->angleOffset = get2bytes(stream);
 		} else {
-			me -> angleOffset = 0;
+			me->angleOffset = 0;
 		}
-		me -> wantAngle = get2bytes(fp);
-		me -> directionWhenDoneWalking = getSigned(fp);
-		me -> inPoly = getSigned(fp);
-		me -> walkToPoly = getSigned(fp);
+		me->wantAngle = get2bytes(stream);
+		me->directionWhenDoneWalking = getSigned(stream);
+		me->inPoly = getSigned(stream);
+		me->walkToPoly = getSigned(stream);
 		if (ssgVersion >= VERSION(2, 0)) {
-			me -> r = fgetc(fp);
-			me -> g = fgetc(fp);
-			me -> b = fgetc(fp);
-			me -> colourmix = fgetc(fp);
-			me -> transparency = fgetc(fp);
+			me->r = getch(stream);
+			me->g = getch(stream);
+			me->b = getch(stream);
+			me->colourmix = getch(stream);
+			me->transparency = getch(stream);
 		} else {
-			setMyDrawMode(me, get2bytes(fp));
+			setMyDrawMode(me, get2bytes(stream));
 		}
-		me -> thisType = loadObjectRef(fp);
+		me->thisType = loadObjectRef(stream);
 
 		// Anti-aliasing settings
 		if (ssgVersion >= VERSION(1, 6)) {
 			if (ssgVersion < VERSION(2, 0)) {
 				// aaLoad
-				fgetc(fp);
-				getFloat(fp);
-				getFloat(fp);
+				getch(stream);
+				getFloat(stream);
+				getFloat(stream);
 			}
 		}
 
-		me -> next = NULL;
+		me->next = NULL;
 		* pointy = me;
-		pointy = & (me -> next);
+		pointy = & (me->next);
 	}
 //	db ("End of loadPeople");
 	return true;
 }
-#endif
 
 } // End of namespace Sludge
diff --git a/engines/sludge/people.h b/engines/sludge/people.h
index 11cf10b..ba726b0 100644
--- a/engines/sludge/people.h
+++ b/engines/sludge/people.h
@@ -125,14 +125,12 @@ personaAnimation *makeNullAnim();
 void deleteAnim(personaAnimation *orig);
 
 // Loading and saving
-#if ALLOW_FILE
-bool saveAnim(personaAnimation *p, FILE *fp);
-bool loadAnim(personaAnimation *p, FILE *fp);
-bool savePeople(FILE *fp);
-bool loadPeople(FILE *fp);
-bool saveCostume(persona *cossy, FILE *fp);
-bool loadCostume(persona *cossy, FILE *fp);
-#endif
+bool saveAnim(personaAnimation *p, Common::WriteStream *stream);
+bool loadAnim(personaAnimation *p, Common::SeekableReadStream *stream);
+bool savePeople(Common::WriteStream *stream);
+bool loadPeople(Common::SeekableReadStream *stream);
+bool saveCostume(persona *cossy, Common::WriteStream *stream);
+bool loadCostume(persona *cossy, Common::SeekableReadStream *stream);
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/region.cpp b/engines/sludge/region.cpp
index 8c55ece..eebcb57 100644
--- a/engines/sludge/region.cpp
+++ b/engines/sludge/region.cpp
@@ -38,11 +38,11 @@ void showBoxes() {
 	screenRegion *huntRegion = allScreenRegions;
 
 	while (huntRegion) {
-		drawVerticalLine(huntRegion -> x1, huntRegion -> y1, huntRegion -> y2);
-		drawVerticalLine(huntRegion -> x2, huntRegion -> y1, huntRegion -> y2);
-		drawHorizontalLine(huntRegion -> x1, huntRegion -> y1, huntRegion -> x2);
-		drawHorizontalLine(huntRegion -> x1, huntRegion -> y2, huntRegion -> x2);
-		huntRegion = huntRegion -> next;
+		drawVerticalLine(huntRegion->x1, huntRegion->y1, huntRegion->y2);
+		drawVerticalLine(huntRegion->x2, huntRegion->y1, huntRegion->y2);
+		drawHorizontalLine(huntRegion->x1, huntRegion->y1, huntRegion->x2);
+		drawHorizontalLine(huntRegion->x1, huntRegion->y2, huntRegion->x2);
+		huntRegion = huntRegion->next;
 	}
 }
 
@@ -51,45 +51,44 @@ void removeScreenRegion(int objectNum) {
 	screenRegion *killMe;
 
 	while (* huntRegion) {
-		if ((* huntRegion) -> thisType -> objectNum == objectNum) {
+		if ((* huntRegion)->thisType->objectNum == objectNum) {
 			killMe = * huntRegion;
-			* huntRegion = killMe -> next;
-			removeObjectType(killMe -> thisType);
+			* huntRegion = killMe->next;
+			removeObjectType(killMe->thisType);
 			if (killMe == overRegion) overRegion = NULL;
 			delete killMe;
 			killMe = NULL;
 		} else {
-			huntRegion = & ((* huntRegion) -> next);
+			huntRegion = & ((* huntRegion)->next);
 		}
 	}
 }
 
-#if ALLOW_FILE
-void saveRegions(FILE *fp) {
+void saveRegions(Common::WriteStream *stream) {
 	int numRegions = 0;
 	screenRegion *thisRegion = allScreenRegions;
 	while (thisRegion) {
-		thisRegion = thisRegion -> next;
+		thisRegion = thisRegion->next;
 		numRegions ++;
 	}
-	put2bytes(numRegions, fp);
+	put2bytes(numRegions, stream);
 	thisRegion = allScreenRegions;
 	while (thisRegion) {
-		put2bytes(thisRegion -> x1, fp);
-		put2bytes(thisRegion -> y1, fp);
-		put2bytes(thisRegion -> x2, fp);
-		put2bytes(thisRegion -> y2, fp);
-		put2bytes(thisRegion -> sX, fp);
-		put2bytes(thisRegion -> sY, fp);
-		put2bytes(thisRegion -> di, fp);
-		saveObjectRef(thisRegion -> thisType, fp);
-
-		thisRegion = thisRegion -> next;
+		put2bytes(thisRegion->x1, stream);
+		put2bytes(thisRegion->y1, stream);
+		put2bytes(thisRegion->x2, stream);
+		put2bytes(thisRegion->y2, stream);
+		put2bytes(thisRegion->sX, stream);
+		put2bytes(thisRegion->sY, stream);
+		put2bytes(thisRegion->di, stream);
+		saveObjectRef(thisRegion->thisType, stream);
+
+		thisRegion = thisRegion->next;
 	}
 }
 
-void loadRegions(FILE *fp) {
-	int numRegions = get2bytes(fp);
+void loadRegions(Common::SeekableReadStream *stream) {
+	int numRegions = get2bytes(stream);
 
 	screenRegion *newRegion;
 	screenRegion * * pointy = & allScreenRegions;
@@ -97,26 +96,26 @@ void loadRegions(FILE *fp) {
 	while (numRegions --) {
 		newRegion = new screenRegion;
 		* pointy = newRegion;
-		pointy = & (newRegion -> next);
-
-		newRegion -> x1 = get2bytes(fp);
-		newRegion -> y1 = get2bytes(fp);
-		newRegion -> x2 = get2bytes(fp);
-		newRegion -> y2 = get2bytes(fp);
-		newRegion -> sX = get2bytes(fp);
-		newRegion -> sY = get2bytes(fp);
-		newRegion -> di = get2bytes(fp);
-		newRegion -> thisType = loadObjectRef(fp);
+		pointy = & (newRegion->next);
+
+		newRegion->x1 = get2bytes(stream);
+		newRegion->y1 = get2bytes(stream);
+		newRegion->x2 = get2bytes(stream);
+		newRegion->y2 = get2bytes(stream);
+		newRegion->sX = get2bytes(stream);
+		newRegion->sY = get2bytes(stream);
+		newRegion->di = get2bytes(stream);
+		newRegion->thisType = loadObjectRef(stream);
 	}
 	* pointy = NULL;
 }
-#endif
+
 void killAllRegions() {
 	screenRegion *killRegion;
 	while (allScreenRegions) {
 		killRegion = allScreenRegions;
-		allScreenRegions = allScreenRegions -> next;
-		removeObjectType(killRegion -> thisType);
+		allScreenRegions = allScreenRegions->next;
+		removeObjectType(killRegion->thisType);
 		delete killRegion;
 	}
 	overRegion = NULL;
@@ -124,29 +123,29 @@ void killAllRegions() {
 
 bool addScreenRegion(int x1, int y1, int x2, int y2, int sX, int sY, int di, int objectNum) {
 	screenRegion *newRegion = new screenRegion;
-	if (! checkNew(newRegion)) return false;
-	newRegion -> di = di;
-	newRegion -> x1 = x1;
-	newRegion -> y1 = y1;
-	newRegion -> x2 = x2;
-	newRegion -> y2 = y2;
-	newRegion -> sX = sX;
-	newRegion -> sY = sY;
-	newRegion -> thisType = loadObjectType(objectNum);
-	newRegion -> next = allScreenRegions;
+	if (!checkNew(newRegion)) return false;
+	newRegion->di = di;
+	newRegion->x1 = x1;
+	newRegion->y1 = y1;
+	newRegion->x2 = x2;
+	newRegion->y2 = y2;
+	newRegion->sX = sX;
+	newRegion->sY = sY;
+	newRegion->thisType = loadObjectType(objectNum);
+	newRegion->next = allScreenRegions;
 	allScreenRegions = newRegion;
-	return (bool)(newRegion -> thisType != NULL);
+	return (bool)(newRegion->thisType != NULL);
 }
 
 void getOverRegion() {
 	screenRegion *thisRegion = allScreenRegions;
 	while (thisRegion) {
-		if ((input.mouseX >= thisRegion -> x1 - cameraX) && (input.mouseY >= thisRegion -> y1 - cameraY) &&
-		        (input.mouseX <= thisRegion -> x2 - cameraX) && (input.mouseY <= thisRegion -> y2 - cameraY)) {
+		if ((input.mouseX >= thisRegion->x1 - cameraX) && (input.mouseY >= thisRegion->y1 - cameraY) &&
+		        (input.mouseX <= thisRegion->x2 - cameraX) && (input.mouseY <= thisRegion->y2 - cameraY)) {
 			overRegion = thisRegion;
 			return;
 		}
-		thisRegion = thisRegion -> next;
+		thisRegion = thisRegion->next;
 	}
 	overRegion = NULL;
 	return;
@@ -156,10 +155,10 @@ screenRegion *getRegionForObject(int obj) {
 	screenRegion *thisRegion = allScreenRegions;
 
 	while (thisRegion) {
-		if (obj == thisRegion -> thisType -> objectNum) {
+		if (obj == thisRegion->thisType->objectNum) {
 			return thisRegion;
 		}
-		thisRegion = thisRegion -> next;
+		thisRegion = thisRegion->next;
 	}
 
 	return NULL;
diff --git a/engines/sludge/region.h b/engines/sludge/region.h
index 52c1c58..2bc4ab6 100644
--- a/engines/sludge/region.h
+++ b/engines/sludge/region.h
@@ -34,11 +34,10 @@ bool addScreenRegion(int x1, int y1, int x2, int y2, int, int, int, int objectNu
 void getOverRegion();
 screenRegion *getRegionForObject(int obj);
 void removeScreenRegion(int objectNum);
+void loadRegions(Common::SeekableReadStream *stream);
+void saveRegions(Common::WriteStream *stream);
 void killAllRegions();
-#if ALLOW_FILE
-void loadRegions(FILE *);
-void saveRegions(FILE *);
-#endif
+
 void showBoxes();
 
 } // End of namespace Sludge
diff --git a/engines/sludge/savedata.cpp b/engines/sludge/savedata.cpp
index 79e672b..dc061c6 100644
--- a/engines/sludge/savedata.cpp
+++ b/engines/sludge/savedata.cpp
@@ -29,6 +29,8 @@
 #include "newfatal.h"
 #include "moreio.h"
 
+#include "common/file.h"
+
 #define LOAD_ERROR "Can't load custom data...\n\n"
 
 namespace Sludge {
@@ -59,107 +61,109 @@ void loadSaveDebug (int com) {
 }
 */
 
-#if ALLOW_FILE
-void writeStringEncoded(const char *s, FILE *fp) {
+void writeStringEncoded(const char *s, Common::WriteStream *stream) {
 	int a, len = strlen(s);
 
-	put2bytes(len, fp);
+	put2bytes(len, stream);
 	for (a = 0; a < len; a ++) {
-		fputc(s[a] ^ encode1, fp);
+		putch(s[a] ^ encode1, stream);
 		encode1 += encode2;
 	}
 }
 
-char *readStringEncoded(FILE *fp) {
+char *readStringEncoded(Common::File *fp) {
 	int a, len = get2bytes(fp);
 	char *s = new char[len + 1];
-	if (! checkNew(s)) return NULL;
+	if (!checkNew(s)) return NULL;
 	for (a = 0; a < len; a ++) {
-		s[a] = (char)(fgetc(fp) ^ encode1);
+		s[a] = (char)(getch(fp) ^ encode1);
 		encode1 += encode2;
 	}
 	s[len] = 0;
 	return s;
 }
 
-char *readTextPlain(FILE *fp) {
+char *readTextPlain(Common::File *fp) {
 	int32_t startPos;
 
-	int stringSize = 0;
+	uint32 stringSize = 0;
 	bool keepGoing = true;
 	char gotChar;
 	char *reply;
 
-	startPos = ftell(fp);
+	startPos = fp->pos();
 
 	while (keepGoing) {
-		gotChar = (char) fgetc(fp);
-		if ((gotChar == '\n') || (feof(fp))) {
+		gotChar = (char) getch(fp);
+		if ((gotChar == '\n') || (fp->eos())) {
 			keepGoing = false;
 		} else {
 			stringSize ++;
 		}
 	}
 
-	if ((stringSize == 0) && (feof(fp))) {
+	if ((stringSize == 0) && (fp->eos())) {
 		return NULL;
 	} else {
-		fseek(fp, startPos, SEEK_SET);
+		fp->seek(startPos, SEEK_SET);
 		reply = new char[stringSize + 1];
 		if (reply == NULL) return NULL;
-		size_t bytes_read = fread(reply, stringSize, 1, fp);
-		if (bytes_read != stringSize && ferror(fp)) {
+		size_t bytes_read = fp->read(reply, stringSize);
+		if (bytes_read != stringSize && fp->err()) {
 			debugOut("Reading error in readTextPlain.\n");
 		}
-		fgetc(fp);  // Skip the newline character
+		getch(fp);  // Skip the newline character
 		reply[stringSize] = 0;
 	}
 
 	return reply;
 }
-#endif
 
 bool fileToStack(char *filename, stackHandler *sH) {
-#if ALLOW_FILE
+
 	variable stringVar;
 	stringVar.varType = SVT_NULL;
 	const char *checker = saveEncoding ? "[Custom data (encoded)]\r\n" : "[Custom data (ASCII)]\n";
 
-	FILE *fp = fopen(filename, "rb");
-	if (! fp) {
+	Common::File fd;
+
+	if (!fd.open(filename)) {
+#if 0
 		char currentDir[1000];
-		if (! getcwd(currentDir, 998)) {
+		if (!getcwd(currentDir, 998)) {
 			debugOut("Can't get current directory.\n");
 		}
 
 		if (chdir(gamePath)) {
 			debugOut("Error: Failed changing to directory %s\n", gamePath);
 		}
-		fp = fopen(filename, "rb");
+
 		if (chdir(currentDir)) {
 			debugOut("Error: Failed changing to directory %s\n", currentDir);
 		}
 
-		if (! fp) {
+		if (!fd.open(filename)) {
 			return fatal("No such file", filename);
 		}
+#endif
+		return fatal("No such file", filename); //TODO: false value
 	}
 
 	encode1 = (unsigned char) saveEncoding & 255;
 	encode2 = (unsigned char)(saveEncoding >> 8);
 
 	while (* checker) {
-		if (fgetc(fp) != * checker) {
-			fclose(fp);
+		if (getch(&fd) != * checker) {
+			fd.close();
 			return fatal(LOAD_ERROR "This isn't a SLUDGE custom data file:", filename);
 		}
 		checker ++;
 	}
 
 	if (saveEncoding) {
-		char *checker = readStringEncoded(fp);
+		char *checker = readStringEncoded(&fd);
 		if (strcmp(checker, "UN�LO�CKED")) {
-			fclose(fp);
+			fd.close();
 			return fatal(LOAD_ERROR "The current file encoding setting does not match the encoding setting used when this file was created:", filename);
 		}
 		delete checker;
@@ -169,55 +173,55 @@ bool fileToStack(char *filename, stackHandler *sH) {
 
 	for (;;) {
 		if (saveEncoding) {
-			char i = fgetc(fp) ^ encode1;
+			char i = getch(&fd) ^ encode1;
 
-			if (feof(fp)) break;
+			if (fd.eos()) break;
 			switch (i) {
 			case 0: {
-				char *g = readStringEncoded(fp);
+				char *g = readStringEncoded(&fd);
 				makeTextVar(stringVar, g);
 				delete g;
 			}
 			break;
 
 			case 1:
-				setVariable(stringVar, SVT_INT, get4bytes(fp));
+				setVariable(stringVar, SVT_INT, get4bytes(&fd));
 				break;
 
 			case 2:
-				setVariable(stringVar, SVT_INT, fgetc(fp));
+				setVariable(stringVar, SVT_INT, getch(&fd));
 				break;
 
 			default:
 				fatal(LOAD_ERROR "Corrupt custom data file:", filename);
-				fclose(fp);
+				fd.close();
 				return false;
 			}
 		} else {
-			char *line = readTextPlain(fp);
-			if (! line) break;
+			char *line = readTextPlain(&fd);
+			if (!line) break;
 			makeTextVar(stringVar, line);
 		}
 
 		if (sH -> first == NULL) {
 			// Adds to the TOP of the array... oops!
-			if (! addVarToStackQuick(stringVar, sH -> first)) return false;
+			if (!addVarToStackQuick(stringVar, sH -> first)) return false;
 			sH -> last = sH -> first;
 		} else {
 			// Adds to the END of the array... much better
-			if (! addVarToStackQuick(stringVar, sH -> last -> next)) return false;
+			if (!addVarToStackQuick(stringVar, sH -> last -> next)) return false;
 			sH -> last = sH -> last -> next;
 		}
 	}
-	fclose(fp);
-#endif
+	fd.close();
+
 	return true;
 }
 
 bool stackToFile(char *filename, const variable &from) {
-#if ALLOW_FILE
+#if 0
 	FILE *fp = fopen(filename, saveEncoding ? "wb" : "wt");
-	if (! fp) return fatal("Can't create file", filename);
+	if (!fp) return fatal("Can't create file", filename);
 
 	variableStack *hereWeAre = from.varData.theStack -> first;
 
diff --git a/engines/sludge/shaders.cpp b/engines/sludge/shaders.cpp
index e11a834..cd95079 100644
--- a/engines/sludge/shaders.cpp
+++ b/engines/sludge/shaders.cpp
@@ -33,37 +33,32 @@ extern char *bundleFolder;
 //Read in a textfile (GLSL program)
 // we need to pass it as a string to the GLSL driver
 char *shaderFileRead(const char *name) {
-	FILE *fp;
+	Common::File fd;
 	char *content = NULL;
 	char *fn = joinStrings(bundleFolder, name);
 
 	int count = 0;
 
 	if (fn != NULL) {
+		if (fd.open(fn)) {
 
-		fp = fopen(fn, "rt");
-
-		if (fp != NULL) {
-
-			fseek(fp, 0, SEEK_END);
-			count = ftell(fp);
-			rewind(fp);
+			fd.seek(0, SEEK_END);
+			count = fd.pos();
+			fd.seek(0);
 
 			if (count > 0) {
 				content = (char *)malloc(sizeof(char) * (count + 1));
-				count = fread(content, sizeof(char), count, fp);
+				count = fd.read(content, sizeof(char) * count);
 				content[count] = '\0';
 			}
-			fclose(fp);
-
+			fd.close();
 		}
 	}
-
 	delete fn;
-
 	return content;
 }
 
+#if 0
 static void
 printShaderInfoLog(GLuint shader) {
 	GLint     infologLength = 0;
@@ -116,12 +111,14 @@ printProgramInfoLog(GLuint program) {
 	}
 	printOpenGLError();   // Check for OpenGL errors
 }
+#endif
 
 int buildShaders(const char *vertexShader, const char *fragmentShader) {
+#if 0
 	GLuint VS, FS, prog;
 	GLint vertCompiled, fragCompiled;
 	GLint linked;
-#if 0
+
 	// Create Shader Objects
 	VS = glCreateShader(GL_VERTEX_SHADER);
 	FS = glCreateShader(GL_FRAGMENT_SHADER);
@@ -145,10 +142,10 @@ int buildShaders(const char *vertexShader, const char *fragmentShader) {
 	printOpenGLError();
 	glGetShaderiv(FS, GL_COMPILE_STATUS, &fragCompiled);
 	printShaderInfoLog(FS);
-#endif
+
 	if (!vertCompiled || !fragCompiled)
 		return 0;
-
+#endif
 	debugOut("\nShaders compiled. \n");
 
 #if 0
@@ -166,13 +163,15 @@ int buildShaders(const char *vertexShader, const char *fragmentShader) {
 	printOpenGLError();
 	glGetProgramiv(prog, GL_LINK_STATUS, &linked);
 	printProgramInfoLog(prog);
-#endif
+
 	if (!linked)
 		return 0;
 
 	debugOut("Shader program linked. \n");
 
 	return prog;
+#endif
+	return 0; //TODO: false value
 }
 
 } // End of namespace Sludge
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index 02a27f1..5202168 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -127,55 +127,55 @@ const char *sludgeText[] = { "?????", "RETURN", "BRANCH", "BR_ZERO", "SET_GLOBAL
                              "INC_LOCAL", "DEC_LOCAL", "INC_GLOBAL", "DEC_GLOBAL", "INDEXSET", "INDEXGET",
                              "INC_INDEX", "DEC_INDEX", "QUICK_PUSH"
                            };
-#if ALLOW_FILE
-void loadHandlers(FILE *fp) {
-	currentEvents -> leftMouseFunction      = get2bytes(fp);
-	currentEvents -> leftMouseUpFunction    = get2bytes(fp);
-	currentEvents -> rightMouseFunction     = get2bytes(fp);
-	currentEvents -> rightMouseUpFunction   = get2bytes(fp);
-	currentEvents -> moveMouseFunction      = get2bytes(fp);
-	currentEvents -> focusFunction          = get2bytes(fp);
-	currentEvents -> spaceFunction          = get2bytes(fp);
+
+void loadHandlers(Common::SeekableReadStream *stream) {
+	currentEvents->leftMouseFunction      = get2bytes(stream);
+	currentEvents->leftMouseUpFunction    = get2bytes(stream);
+	currentEvents->rightMouseFunction     = get2bytes(stream);
+	currentEvents->rightMouseUpFunction   = get2bytes(stream);
+	currentEvents->moveMouseFunction      = get2bytes(stream);
+	currentEvents->focusFunction          = get2bytes(stream);
+	currentEvents->spaceFunction          = get2bytes(stream);
 }
 
-void saveHandlers(FILE *fp) {
-	put2bytes(currentEvents -> leftMouseFunction,      fp);
-	put2bytes(currentEvents -> leftMouseUpFunction,    fp);
-	put2bytes(currentEvents -> rightMouseFunction,     fp);
-	put2bytes(currentEvents -> rightMouseUpFunction,   fp);
-	put2bytes(currentEvents -> moveMouseFunction,      fp);
-	put2bytes(currentEvents -> focusFunction,          fp);
-	put2bytes(currentEvents -> spaceFunction,          fp);
+void saveHandlers(Common::WriteStream *stream) {
+	put2bytes(currentEvents->leftMouseFunction,      stream);
+	put2bytes(currentEvents->leftMouseUpFunction,    stream);
+	put2bytes(currentEvents->rightMouseFunction,     stream);
+	put2bytes(currentEvents->rightMouseUpFunction,   stream);
+	put2bytes(currentEvents->moveMouseFunction,      stream);
+	put2bytes(currentEvents->focusFunction,          stream);
+	put2bytes(currentEvents->spaceFunction,          stream);
 }
 
-FILE *openAndVerify(char *filename, char extra1, char extra2, const char *er, int &fileVersion) {
-	FILE *fp = fopen(filename, "rb");
-	if (! fp) {
+Common::File *openAndVerify(char *filename, char extra1, char extra2, const char *er, int &fileVersion) {
+	Common::File *fp = new Common::File();
+	if (!fp->open(filename)) {
 		fatal("Can't open file", filename);
 		return NULL;
 	}
 	bool headerBad = false;
-	if (fgetc(fp) != 'S') headerBad = true;
-	if (fgetc(fp) != 'L') headerBad = true;
-	if (fgetc(fp) != 'U') headerBad = true;
-	if (fgetc(fp) != 'D') headerBad = true;
-	if (fgetc(fp) != extra1) headerBad = true;
-	if (fgetc(fp) != extra2) headerBad = true;
+	if (getch(fp) != 'S') headerBad = true;
+	if (getch(fp) != 'L') headerBad = true;
+	if (getch(fp) != 'U') headerBad = true;
+	if (getch(fp) != 'D') headerBad = true;
+	if (getch(fp) != extra1) headerBad = true;
+	if (getch(fp) != extra2) headerBad = true;
 	if (headerBad) {
 		fatal(er, filename);
 		return NULL;
 	}
 	char c;
-	c = fgetc(fp);
-	debug(c);
-	while (c = fgetc(fp)) {
-		putchar(c);
+	c = getch(fp);
+	debug("%c", c);
+	while ((c = getch(fp))) {
+		debug("%c", c);
 	}
 
-	int majVersion = fgetc(fp);
-	printf("$majVersion %i\n", majVersion);
-	int minVersion = fgetc(fp);
-	printf("$minVersion %i\n", minVersion);
+	int majVersion = getch(fp);
+	debug(kSludgeDebugDataLoad, "majVersion %i", majVersion);
+	int minVersion = getch(fp);
+	debug(kSludgeDebugDataLoad, "minVersion %i", minVersion);
 	fileVersion = majVersion * 256 + minVersion;
 
 	char txtVer[120];
@@ -191,89 +191,83 @@ FILE *openAndVerify(char *filename, char extra1, char extra2, const char *er, in
 	}
 	return fp;
 }
-#endif
 
 bool initSludge(char *filename) {
 	int a = 0;
 	mouseCursorAnim = makeNullAnim();
 
-#if ALLOW_FILE
-	FILE *fp = openAndVerify(filename, 'G', 'E', ERROR_BAD_HEADER, gameVersion);
-	if (! fp) return false;
+	Common::File *fp = openAndVerify(filename, 'G', 'E', ERROR_BAD_HEADER, gameVersion);
+	if (!fp) return false;
 
-	char c = fgetc(fp);
-	putchar(c);
+	char c = getch(fp);
 	if (c) {
 		numBIFNames = get2bytes(fp);
-		printf("numBIFNames %i\n", numBIFNames);
+		debug(kSludgeDebugDataLoad, "numBIFNames %i", numBIFNames);
 		allBIFNames = new char *[numBIFNames];
-		if (! checkNew(allBIFNames)) return false;
+		if (!checkNew(allBIFNames)) return false;
 
 		for (int fn = 0; fn < numBIFNames; fn ++) {
 			allBIFNames[fn] = readString(fp);
-			printf("%s\n", allBIFNames[fn]);
 		}
 		numUserFunc = get2bytes(fp);
-		printf("numUserFunc %i\n", numUserFunc);
+		debug(kSludgeDebugDataLoad, "numUserFunc %i", numUserFunc);
 		allUserFunc = new char *[numUserFunc];
-		if (! checkNew(allUserFunc)) return false;
+		if (!checkNew(allUserFunc)) return false;
 
 		for (int fn = 0; fn < numUserFunc; fn ++) {
 			allUserFunc[fn] = readString(fp);
-			printf("%s\n", allUserFunc[fn]);
 		}
 		if (gameVersion >= VERSION(1, 3)) {
 			numResourceNames = get2bytes(fp);
-			printf("numResourceNames %i\n", numResourceNames);
+			debug(kSludgeDebugDataLoad, "numResourceNames %i", numResourceNames);
 			allResourceNames = new char *[numResourceNames];
-			if (! checkNew(allResourceNames)) return false;
+			if (!checkNew(allResourceNames)) return false;
 
 			for (int fn = 0; fn < numResourceNames; fn ++) {
 				allResourceNames[fn] = readString(fp);
-				printf("%s\n", allResourceNames[fn]);
 			}
 		}
 	}
 
 	winWidth = get2bytes(fp);
-	printf("winWidth : %i\n", winWidth);
+	debug(kSludgeDebugDataLoad, "winWidth : %i", winWidth);
 	winHeight = get2bytes(fp);
-	printf("winHeight : %i\n", winHeight);
-	specialSettings = fgetc(fp);
-	printf("specialSettings : %i\n", specialSettings);
-	desiredfps = 1000 / fgetc(fp);
+	debug(kSludgeDebugDataLoad, "winHeight : %i", winHeight);
+	specialSettings = getch(fp);
+	debug(kSludgeDebugDataLoad, "specialSettings : %i", specialSettings);
+	desiredfps = 1000 / getch(fp);
 
 	delete[] readString(fp);  // Unused - was used for registration purposes.
 
-	size_t bytes_read = fread(& fileTime, sizeof(FILETIME), 1, fp);
-	if (bytes_read != sizeof(FILETIME) && ferror(fp)) {
-		debugOut("Reading error in initSludge.\n");
+	size_t bytes_read = fp->read(&fileTime, sizeof(FILETIME));
+	if (bytes_read != sizeof(FILETIME) && fp->err()) {
+		debug("Reading error in initSludge.");
 	}
 
 	char *dataFol = (gameVersion >= VERSION(1, 3)) ? readString(fp) : joinStrings("", "");
-	printf("dataFol : %s\n", dataFol);
+	debug(kSludgeDebugDataLoad, "dataFol : %s", dataFol);
 
-	gameSettings.numLanguages = (gameVersion >= VERSION(1, 3)) ? (fgetc(fp)) : 0;
-	printf("numLanguages : %c\n", gameSettings.numLanguages);
+	gameSettings.numLanguages = (gameVersion >= VERSION(1, 3)) ? (getch(fp)) : 0;
+	debug(kSludgeDebugDataLoad, "numLanguages : %c", gameSettings.numLanguages);
 	makeLanguageTable(fp);
 
 	if (gameVersion >= VERSION(1, 6)) {
-		fgetc(fp);
+		getch(fp);
 		// aaLoad
-		fgetc(fp);
+		getch(fp);
 		getFloat(fp);
 		getFloat(fp);
 	}
 
 	char *checker = readString(fp);
-	debug(kSludgeDebugDataLoad, "checker : %s\n", checker);
+	debug(kSludgeDebugDataLoad, "checker : %s", checker);
 
 	if (strcmp(checker, "okSoFar")) return fatal(ERROR_BAD_HEADER, filename);
 	delete checker;
 	checker = NULL;
 
-	unsigned char customIconLogo = fgetc(fp);
-	kSludgeDebugDataLoad(kSludgeDebugDataLoad, "Game icon: %i", customIconLogo);
+	unsigned char customIconLogo = getch(fp);
+	debug(kSludgeDebugDataLoad, "Game icon type: %i", customIconLogo);
 
 	if (customIconLogo & 1) {
 		// There is an icon - read it!
@@ -346,7 +340,7 @@ bool initSludge(char *filename) {
 		}
 
 		gameIcon = new unsigned char [iconW * iconH * 4];
-		if (! gameIcon) return fatal("Can't reserve memory for game icon.");
+		if (!gameIcon) return fatal("Can't reserve memory for game icon.");
 
 		int32_t transCol = 63519;
 		Uint8 *p = (Uint8 *) gameIcon;
@@ -388,8 +382,8 @@ bool initSludge(char *filename) {
 	if (customIconLogo & 2) {
 		// There is an logo - read it!
 		debug(kSludgeDebugDataLoad, "There is an logo - read it!");
+#if 0
 		int n;
-
 		long file_pointer = ftell(fp);
 
 		png_structp png_ptr;
@@ -402,7 +396,7 @@ bool initSludge(char *filename) {
 		char tmp[10];
 		bytes_read = fread(tmp, 1, 8, fp);
 		if (bytes_read != 8 && ferror(fp)) {
-			debugOut("Reading error in initSludge.\n");
+			debugOut("Reading error in initSludge.");
 		}
 		if (png_sig_cmp((png_byte *) tmp, 0, 8)) {
 			// No, it's old-school HSI
@@ -463,7 +457,7 @@ bool initSludge(char *filename) {
 		if ((logoW != 310) || (logoH != 88)) return fatal("Game logo have wrong dimensions. (Should be 310x88)");
 
 		gameLogo = new unsigned char [logoW * logoH * 4];
-		if (! gameLogo) return fatal("Can't reserve memory for game logo.");
+		if (!gameLogo) return fatal("Can't reserve memory for game logo.");
 
 		// int32_t transCol = 63519;
 		Uint8 *p = (Uint8 *) gameLogo;
@@ -506,13 +500,14 @@ bool initSludge(char *filename) {
 				}
 			}
 		}
+#endif
 	}
 
 	numGlobals = get2bytes(fp);
-	printf("numGlobals : %i\n", numGlobals);
+	debug("numGlobals : %i", numGlobals);
 
 	globalVars = new variable[numGlobals];
-	if (! checkNew(globalVars)) return false;
+	if (!checkNew(globalVars)) return false;
 	for (a = 0; a < numGlobals; a ++) initVarNew(globalVars[a]);
 
 	// Get the original (untranslated) name of the game and convert it to Unicode.
@@ -524,8 +519,9 @@ bool initSludge(char *filename) {
 
 	delete gameNameOrig;
 
-	changeToUserDir();
 #if 0
+	changeToUserDir();
+
 #ifdef _WIN32
 	mkdir(gameName);
 #else
@@ -542,11 +538,13 @@ bool initSludge(char *filename) {
 	// There's no startup window on Linux and respecting this
 	// option from the ini file would disable commandline options.
 #if defined __unix__ && !(defined __APPLE__)
-	if (! showSetupWindow()) return 0;
+#if 0
+	if (!showSetupWindow()) return 0;
+#endif
 	saveIniFile(filename);
 #else
-	if (! gameSettings.noStartWindow) {
-		if (! showSetupWindow()) return 0;
+	if (!gameSettings.noStartWindow) {
+		if (!showSetupWindow()) return 0;
 		saveIniFile(filename);
 	}
 #endif
@@ -571,7 +569,7 @@ bool initSludge(char *filename) {
 	}
 
 	positionStatus(10, winHeight - 15);
-#endif
+
 	return true;
 }
 
@@ -740,16 +738,16 @@ void pauseFunction(loadedFunction *fun) {
 	loadedFunction * * huntAndDestroy = & allRunningFunctions;
 	while (* huntAndDestroy) {
 		if (fun == * huntAndDestroy) {
-			(* huntAndDestroy) = (* huntAndDestroy) -> next;
+			(* huntAndDestroy) = (* huntAndDestroy)->next;
 			fun->next = NULL;
 		} else {
-			huntAndDestroy = & (* huntAndDestroy) -> next;
+			huntAndDestroy = & (* huntAndDestroy)->next;
 		}
 	}
 }
 
 void restartFunction(loadedFunction *fun) {
-	fun -> next = allRunningFunctions;
+	fun->next = allRunningFunctions;
 	allRunningFunctions = fun;
 }
 
@@ -757,11 +755,11 @@ void killSpeechTimers() {
 	loadedFunction *thisFunction = allRunningFunctions;
 
 	while (thisFunction) {
-		if (thisFunction -> freezerLevel == 0 && thisFunction -> isSpeech && thisFunction -> timeLeft) {
-			thisFunction -> timeLeft = 0;
-			thisFunction -> isSpeech = false;
+		if (thisFunction->freezerLevel == 0 && thisFunction->isSpeech && thisFunction->timeLeft) {
+			thisFunction->timeLeft = 0;
+			thisFunction->isSpeech = false;
 		}
-		thisFunction = thisFunction -> next;
+		thisFunction = thisFunction->next;
 	}
 
 	killAllSpeech();
@@ -771,8 +769,8 @@ void completeTimers() {
 	loadedFunction *thisFunction = allRunningFunctions;
 
 	while (thisFunction) {
-		if (thisFunction -> freezerLevel == 0) thisFunction -> timeLeft = 0;
-		thisFunction = thisFunction -> next;
+		if (thisFunction->freezerLevel == 0) thisFunction->timeLeft = 0;
+		thisFunction = thisFunction->next;
 	}
 }
 
@@ -780,11 +778,11 @@ void finishFunction(loadedFunction *fun) {
 	int a;
 
 	pauseFunction(fun);
-	if (fun -> stack) fatal(ERROR_NON_EMPTY_STACK);
-	delete fun -> compiledLines;
-	for (a = 0; a < fun -> numLocals; a ++) unlinkVar(fun -> localVars[a]);
-	delete fun -> localVars;
-	unlinkVar(fun -> reg);
+	if (fun->stack) fatal(ERROR_NON_EMPTY_STACK);
+	delete fun->compiledLines;
+	for (a = 0; a < fun->numLocals; a ++) unlinkVar(fun->localVars[a]);
+	delete fun->localVars;
+	unlinkVar(fun->reg);
 	delete fun;
 	fun = NULL;
 }
@@ -793,12 +791,12 @@ void abortFunction(loadedFunction *fun) {
 	int a;
 
 	pauseFunction(fun);
-	while (fun -> stack) trimStack(fun -> stack);
-	delete fun -> compiledLines;
-	for (a = 0; a < fun -> numLocals; a ++) unlinkVar(fun -> localVars[a]);
-	delete fun -> localVars;
-	unlinkVar(fun -> reg);
-	if (fun -> calledBy) abortFunction(fun -> calledBy);
+	while (fun->stack) trimStack(fun->stack);
+	delete fun->compiledLines;
+	for (a = 0; a < fun->numLocals; a ++) unlinkVar(fun->localVars[a]);
+	delete fun->localVars;
+	unlinkVar(fun->reg);
+	if (fun->calledBy) abortFunction(fun->calledBy);
 	delete fun;
 	fun = NULL;
 }
@@ -809,12 +807,12 @@ int cancelAFunction(int funcNum, loadedFunction *myself, bool &killedMyself) {
 
 	loadedFunction *fun = allRunningFunctions;
 	while (fun) {
-		if (fun -> originalNumber == funcNum) {
-			fun -> cancelMe = true;
+		if (fun->originalNumber == funcNum) {
+			fun->cancelMe = true;
 			n ++;
 			if (fun == myself) killedMyself = true;
 		}
-		fun = fun -> next;
+		fun = fun->next;
 	}
 	return n;
 }
@@ -823,12 +821,12 @@ void freezeSubs() {
 	loadedFunction *thisFunction = allRunningFunctions;
 
 	while (thisFunction) {
-		if (thisFunction -> unfreezable) {
+		if (thisFunction->unfreezable) {
 			//msgBox ("SLUDGE debugging bollocks!", "Trying to freeze an unfreezable function!");
 		} else {
-			thisFunction -> freezerLevel ++;
+			thisFunction->freezerLevel ++;
 		}
-		thisFunction = thisFunction -> next;
+		thisFunction = thisFunction->next;
 	}
 }
 
@@ -836,8 +834,8 @@ void unfreezeSubs() {
 	loadedFunction *thisFunction = allRunningFunctions;
 
 	while (thisFunction) {
-		if (thisFunction -> freezerLevel) thisFunction -> freezerLevel --;
-		thisFunction = thisFunction -> next;
+		if (thisFunction->freezerLevel) thisFunction->freezerLevel --;
+		thisFunction = thisFunction->next;
 	}
 }
 
@@ -848,25 +846,25 @@ bool continueFunction(loadedFunction *fun) {
 	unsigned int param;
 	sludgeCommand com;
 
-	if (fun -> cancelMe) {
+	if (fun->cancelMe) {
 		abortFunction(fun);
 		return true;
 	}
 
-//	if (numBIFNames) newDebug ("*** Function:", allUserFunc[fun -> originalNumber]);
+//	if (numBIFNames) newDebug ("*** Function:", allUserFunc[fun->originalNumber]);
 
 	//debugOut ("SLUDGER: continueFunction\n");
 
 	while (keepLooping) {
 		advanceNow = true;
-		param = fun -> compiledLines[fun -> runThisLine].param;
-		com = fun -> compiledLines[fun -> runThisLine].theCommand;
+		param = fun->compiledLines[fun->runThisLine].param;
+		com = fun->compiledLines[fun->runThisLine].theCommand;
 //		fprintf (stderr, "com: %d param: %d (%s)\n", com, param,
 //				(com < numSludgeCommands) ? sludgeText[com] : ERROR_UNKNOWN_MCODE); fflush(stderr);
 
 		if (numBIFNames) {
 			setFatalInfo(
-			    (fun -> originalNumber < numUserFunc) ? allUserFunc[fun -> originalNumber] : "Unknown user function",
+			    (fun->originalNumber < numUserFunc) ? allUserFunc[fun->originalNumber] : "Unknown user function",
 			    (com < numSludgeCommands) ? sludgeText[com] : ERROR_UNKNOWN_MCODE);
 //			newDebug (
 //				(com < numSludgeCommands) ? sludgeText[com] : "Unknown SLUDGE machine code",
@@ -877,9 +875,9 @@ bool continueFunction(loadedFunction *fun) {
 
 		switch (com) {
 		case SLU_RETURN:
-			if (fun -> calledBy) {
-				loadedFunction *returnTo = fun -> calledBy;
-				if (fun -> returnSomething) copyVariable(fun -> reg, returnTo -> reg);
+			if (fun->calledBy) {
+				loadedFunction *returnTo = fun->calledBy;
+				if (fun->returnSomething) copyVariable(fun->reg, returnTo->reg);
 				finishFunction(fun);
 				fun = returnTo;
 				restartFunction(fun);
@@ -891,20 +889,21 @@ bool continueFunction(loadedFunction *fun) {
 			break;
 
 		case SLU_CALLIT:
-			switch (fun -> reg.varType) {
+			switch (fun->reg.varType) {
 			case SVT_FUNC:
 				pauseFunction(fun);
 				if (numBIFNames) setFatalInfo(
-					    (fun -> originalNumber < numUserFunc) ? allUserFunc[fun -> originalNumber] : "Unknown user function",
-					    (fun -> reg.varData.intValue < numUserFunc) ? allUserFunc[fun -> reg.varData.intValue] : "Unknown user function");
+					    (fun->originalNumber < numUserFunc) ? allUserFunc[fun->originalNumber] : "Unknown user function",
+					    (fun->reg.varData.intValue < numUserFunc) ? allUserFunc[fun->reg.varData.intValue] : "Unknown user function");
 
-				if (! startNewFunctionNum(fun -> reg.varData.intValue, param, fun, fun -> stack)) return false;
+				if (!startNewFunctionNum(fun->reg.varData.intValue, param, fun, fun->stack)) return false;
 				fun = allRunningFunctions;
 				advanceNow = false;     // So we don't do anything else with "fun"
 				break;
 
 			case SVT_BUILT: {
-				builtReturn br = callBuiltIn(fun -> reg.varData.intValue, param, fun);
+				debug(kSludgeDebugStackMachine, "Built-in init value: %i", fun->reg.varData.intValue);
+				builtReturn br = callBuiltIn(fun->reg.varData.intValue, param, fun);
 
 				switch (br) {
 				case BR_ERROR:
@@ -924,13 +923,13 @@ bool continueFunction(loadedFunction *fun) {
 					break;
 
 				case BR_CALLAFUNC: {
-					int i = fun -> reg.varData.intValue;
-					setVariable(fun -> reg, SVT_INT, 1);
+					int i = fun->reg.varData.intValue;
+					setVariable(fun->reg, SVT_INT, 1);
 					pauseFunction(fun);
 					if (numBIFNames) setFatalInfo(
-						    (fun -> originalNumber < numUserFunc) ? allUserFunc[fun -> originalNumber] : "Unknown user function",
+						    (fun->originalNumber < numUserFunc) ? allUserFunc[fun->originalNumber] : "Unknown user function",
 						    (i < numUserFunc) ? allUserFunc[i] : "Unknown user function");
-					if (! startNewFunctionNum(i, 0, fun, noStack, false)) return false;
+					if (!startNewFunctionNum(i, 0, fun, noStack, false)) return false;
 					fun = allRunningFunctions;
 					advanceNow = false;     // So we don't do anything else with "fun"
 				}
@@ -950,41 +949,41 @@ bool continueFunction(loadedFunction *fun) {
 		// These all grab things and shove 'em into the register
 
 		case SLU_LOAD_NULL:
-			setVariable(fun -> reg, SVT_NULL, 0);
+			setVariable(fun->reg, SVT_NULL, 0);
 			break;
 
 		case SLU_LOAD_FILE:
-			setVariable(fun -> reg, SVT_FILE, param);
+			setVariable(fun->reg, SVT_FILE, param);
 			break;
 
 		case SLU_LOAD_VALUE:
-			setVariable(fun -> reg, SVT_INT, param);
+			setVariable(fun->reg, SVT_INT, param);
 			break;
 
 		case SLU_LOAD_LOCAL:
-			if (! copyVariable(fun -> localVars[param], fun -> reg)) return false;
+			if (!copyVariable(fun->localVars[param], fun->reg)) return false;
 			break;
 
 		case SLU_AND:
-			setVariable(fun -> reg, SVT_INT, getBoolean(fun -> reg) && getBoolean(fun -> stack -> thisVar));
-			trimStack(fun -> stack);
+			setVariable(fun->reg, SVT_INT, getBoolean(fun->reg) && getBoolean(fun->stack->thisVar));
+			trimStack(fun->stack);
 			break;
 
 		case SLU_OR:
-			setVariable(fun -> reg, SVT_INT, getBoolean(fun -> reg) || getBoolean(fun -> stack -> thisVar));
-			trimStack(fun -> stack);
+			setVariable(fun->reg, SVT_INT, getBoolean(fun->reg) || getBoolean(fun->stack->thisVar));
+			trimStack(fun->stack);
 			break;
 
 		case SLU_LOAD_FUNC:
-			setVariable(fun -> reg, SVT_FUNC, param);
+			setVariable(fun->reg, SVT_FUNC, param);
 			break;
 
 		case SLU_LOAD_BUILT:
-			setVariable(fun -> reg, SVT_BUILT, param);
+			setVariable(fun->reg, SVT_BUILT, param);
 			break;
 
 		case SLU_LOAD_OBJTYPE:
-			setVariable(fun -> reg, SVT_OBJTYPE, param);
+			setVariable(fun->reg, SVT_OBJTYPE, param);
 			break;
 
 		case SLU_UNREG:
@@ -992,7 +991,7 @@ bool continueFunction(loadedFunction *fun) {
 			break;
 
 		case SLU_LOAD_STRING:
-			if (! loadStringToVar(fun -> reg, param)) {
+			if (!loadStringToVar(fun->reg, param)) {
 				return false;
 			}
 			break;
@@ -1000,11 +999,11 @@ bool continueFunction(loadedFunction *fun) {
 		case SLU_INDEXGET:
 		case SLU_INCREMENT_INDEX:
 		case SLU_DECREMENT_INDEX:
-			switch (fun -> stack -> thisVar.varType) {
+			switch (fun->stack->thisVar.varType) {
 			case SVT_NULL:
 				if (com == SLU_INDEXGET) {
-					setVariable(fun -> reg, SVT_NULL, 0);
-					trimStack(fun -> stack);
+					setVariable(fun->reg, SVT_NULL, 0);
+					trimStack(fun->stack);
 				} else {
 					return fatal(ERROR_INCDEC_UNKNOWN);
 				}
@@ -1012,37 +1011,37 @@ bool continueFunction(loadedFunction *fun) {
 
 			case SVT_FASTARRAY:
 			case SVT_STACK:
-				if (fun -> stack -> thisVar.varData.theStack -> first == NULL) {
+				if (fun->stack->thisVar.varData.theStack->first == NULL) {
 					return fatal(ERROR_INDEX_EMPTY);
 				} else {
 					int ii;
-					if (! getValueType(ii, SVT_INT, fun -> reg)) return false;
-					variable *grab = (fun -> stack -> thisVar.varType == SVT_FASTARRAY) ?
-					                 fastArrayGetByIndex(fun -> stack -> thisVar.varData.fastArray, ii)
+					if (!getValueType(ii, SVT_INT, fun->reg)) return false;
+					variable *grab = (fun->stack->thisVar.varType == SVT_FASTARRAY) ?
+					                 fastArrayGetByIndex(fun->stack->thisVar.varData.fastArray, ii)
 					                 :
-					                 stackGetByIndex(fun -> stack -> thisVar.varData.theStack -> first, ii);
+					                 stackGetByIndex(fun->stack->thisVar.varData.theStack->first, ii);
 
-					trimStack(fun -> stack);
+					trimStack(fun->stack);
 
-					if (! grab) {
-						setVariable(fun -> reg, SVT_NULL, 0);
+					if (!grab) {
+						setVariable(fun->reg, SVT_NULL, 0);
 					} else {
 						int ii;
 						switch (com) {
 						case SLU_INCREMENT_INDEX:
-							if (! getValueType(ii, SVT_INT, * grab)) return false;
-							setVariable(fun -> reg, SVT_INT, ii);
-							grab -> varData.intValue = ii + 1;
+							if (!getValueType(ii, SVT_INT, * grab)) return false;
+							setVariable(fun->reg, SVT_INT, ii);
+							grab->varData.intValue = ii + 1;
 							break;
 
 						case SLU_DECREMENT_INDEX:
-							if (! getValueType(ii, SVT_INT, * grab)) return false;
-							setVariable(fun -> reg, SVT_INT, ii);
-							grab -> varData.intValue = ii - 1;
+							if (!getValueType(ii, SVT_INT, * grab)) return false;
+							setVariable(fun->reg, SVT_INT, ii);
+							grab->varData.intValue = ii - 1;
 							break;
 
 						default:
-							if (! copyVariable(* grab, fun -> reg)) return false;
+							if (!copyVariable(* grab, fun->reg)) return false;
 						}
 					}
 				}
@@ -1054,29 +1053,29 @@ bool continueFunction(loadedFunction *fun) {
 			break;
 
 		case SLU_INDEXSET:
-			switch (fun -> stack -> thisVar.varType) {
+			switch (fun->stack->thisVar.varType) {
 			case SVT_STACK:
-				if (fun -> stack -> thisVar.varData.theStack -> first == NULL) {
+				if (fun->stack->thisVar.varData.theStack->first == NULL) {
 					return fatal(ERROR_INDEX_EMPTY);
 				} else {
 					int ii;
-					if (! getValueType(ii, SVT_INT, fun -> reg)) return false;
-					if (! stackSetByIndex(fun -> stack -> thisVar.varData.theStack -> first, ii, fun -> stack -> next -> thisVar)) {
+					if (!getValueType(ii, SVT_INT, fun->reg)) return false;
+					if (!stackSetByIndex(fun->stack->thisVar.varData.theStack->first, ii, fun->stack->next->thisVar)) {
 						return false;
 					}
-					trimStack(fun -> stack);
-					trimStack(fun -> stack);
+					trimStack(fun->stack);
+					trimStack(fun->stack);
 				}
 				break;
 
 			case SVT_FASTARRAY: {
 				int ii;
-				if (! getValueType(ii, SVT_INT, fun -> reg)) return false;
-				variable *v = fastArrayGetByIndex(fun -> stack -> thisVar.varData.fastArray, ii);
+				if (!getValueType(ii, SVT_INT, fun->reg)) return false;
+				variable *v = fastArrayGetByIndex(fun->stack->thisVar.varData.fastArray, ii);
 				if (v == NULL) return fatal("Not within bounds of fast array.");
-				if (! copyVariable(fun -> stack -> next -> thisVar, * v)) return false;
-				trimStack(fun -> stack);
-				trimStack(fun -> stack);
+				if (!copyVariable(fun->stack->next->thisVar, * v)) return false;
+				trimStack(fun->stack);
+				trimStack(fun->stack);
 			}
 			break;
 
@@ -1090,81 +1089,81 @@ bool continueFunction(loadedFunction *fun) {
 
 		case SLU_INCREMENT_LOCAL: {
 			int ii;
-			if (! getValueType(ii, SVT_INT, fun -> localVars[param])) return false;
-			setVariable(fun -> reg, SVT_INT, ii);
-			setVariable(fun -> localVars[param], SVT_INT, ii + 1);
+			if (!getValueType(ii, SVT_INT, fun->localVars[param])) return false;
+			setVariable(fun->reg, SVT_INT, ii);
+			setVariable(fun->localVars[param], SVT_INT, ii + 1);
 		}
 		break;
 
 		case SLU_INCREMENT_GLOBAL: {
 			int ii;
-			if (! getValueType(ii, SVT_INT, globalVars[param])) return false;
-			setVariable(fun -> reg, SVT_INT, ii);
+			if (!getValueType(ii, SVT_INT, globalVars[param])) return false;
+			setVariable(fun->reg, SVT_INT, ii);
 			setVariable(globalVars[param], SVT_INT, ii + 1);
 		}
 		break;
 
 		case SLU_DECREMENT_LOCAL: {
 			int ii;
-			if (! getValueType(ii, SVT_INT, fun -> localVars[param])) return false;
-			setVariable(fun -> reg, SVT_INT, ii);
-			setVariable(fun -> localVars[param], SVT_INT, ii - 1);
+			if (!getValueType(ii, SVT_INT, fun->localVars[param])) return false;
+			setVariable(fun->reg, SVT_INT, ii);
+			setVariable(fun->localVars[param], SVT_INT, ii - 1);
 		}
 		break;
 
 		case SLU_DECREMENT_GLOBAL: {
 			int ii;
-			if (! getValueType(ii, SVT_INT, globalVars[param])) return false;
-			setVariable(fun -> reg, SVT_INT, ii);
+			if (!getValueType(ii, SVT_INT, globalVars[param])) return false;
+			setVariable(fun->reg, SVT_INT, ii);
 			setVariable(globalVars[param], SVT_INT, ii - 1);
 		}
 		break;
 
 		case SLU_SET_LOCAL:
-			if (! copyVariable(fun -> reg, fun -> localVars[param])) return false;
+			if (!copyVariable(fun->reg, fun->localVars[param])) return false;
 			break;
 
 		case SLU_SET_GLOBAL:
 //			newDebug ("  Copying TO global variable", param);
 //			newDebug ("  Global type at the moment", globalVars[param].varType);
-			if (! copyVariable(fun -> reg, globalVars[param])) return false;
+			if (!copyVariable(fun->reg, globalVars[param])) return false;
 //			newDebug ("  New type", globalVars[param].varType);
 			break;
 
 		case SLU_LOAD_GLOBAL:
 //			newDebug ("  Copying FROM global variable", param);
 //			newDebug ("  Global type at the moment", globalVars[param].varType);
-			if (! copyVariable(globalVars[param], fun -> reg)) return false;
+			if (!copyVariable(globalVars[param], fun->reg)) return false;
 			break;
 
 		case SLU_STACK_PUSH:
-			if (! addVarToStack(fun -> reg, fun -> stack)) return false;
+			if (!addVarToStack(fun->reg, fun->stack)) return false;
 			break;
 
 		case SLU_QUICK_PUSH:
-			if (! addVarToStackQuick(fun -> reg, fun -> stack)) return false;
+			if (!addVarToStackQuick(fun->reg, fun->stack)) return false;
 			break;
 
 		case SLU_NOT:
-			setVariable(fun -> reg, SVT_INT, ! getBoolean(fun -> reg));
+			setVariable(fun->reg, SVT_INT, !getBoolean(fun->reg));
 			break;
 
 		case SLU_BR_ZERO:
-			if (! getBoolean(fun -> reg)) {
+			if (!getBoolean(fun->reg)) {
 				advanceNow = false;
-				fun -> runThisLine = param;
+				fun->runThisLine = param;
 			}
 			break;
 
 		case SLU_BRANCH:
 			advanceNow = false;
-			fun -> runThisLine = param;
+			fun->runThisLine = param;
 			break;
 
 		case SLU_NEGATIVE: {
 			int i;
-			if (! getValueType(i, SVT_INT, fun -> reg)) return false;
-			setVariable(fun -> reg, SVT_INT, -i);
+			if (!getValueType(i, SVT_INT, fun->reg)) return false;
+			setVariable(fun->reg, SVT_INT, -i);
 		}
 		break;
 
@@ -1181,62 +1180,62 @@ bool continueFunction(loadedFunction *fun) {
 		case SLU_MORETHAN:
 		case SLU_LESS_EQUAL:
 		case SLU_MORE_EQUAL:
-			if (fun -> stack) {
+			if (fun->stack) {
 				int firstValue, secondValue;
 
 				switch (com) {
 				case SLU_PLUS:
-					addVariablesInSecond(fun -> stack -> thisVar, fun -> reg);
-					trimStack(fun -> stack);
+					addVariablesInSecond(fun->stack->thisVar, fun->reg);
+					trimStack(fun->stack);
 					break;
 
 				case SLU_EQUALS:
-					compareVariablesInSecond(fun -> stack -> thisVar, fun -> reg);
-					trimStack(fun -> stack);
+					compareVariablesInSecond(fun->stack->thisVar, fun->reg);
+					trimStack(fun->stack);
 					break;
 
 				case SLU_NOT_EQ:
-					compareVariablesInSecond(fun -> stack -> thisVar, fun -> reg);
-					trimStack(fun -> stack);
-					fun -> reg.varData.intValue = ! fun -> reg.varData.intValue;
+					compareVariablesInSecond(fun->stack->thisVar, fun->reg);
+					trimStack(fun->stack);
+					fun->reg.varData.intValue = !fun->reg.varData.intValue;
 					break;
 
 				default:
-					if (! getValueType(firstValue, SVT_INT, fun -> stack -> thisVar)) return false;
-					if (! getValueType(secondValue, SVT_INT, fun -> reg)) return false;
-					trimStack(fun -> stack);
+					if (!getValueType(firstValue, SVT_INT, fun->stack->thisVar)) return false;
+					if (!getValueType(secondValue, SVT_INT, fun->reg)) return false;
+					trimStack(fun->stack);
 
 					switch (com) {
 					case SLU_MULT:
-						setVariable(fun -> reg, SVT_INT, firstValue * secondValue);
+						setVariable(fun->reg, SVT_INT, firstValue * secondValue);
 						break;
 
 					case SLU_MINUS:
-						setVariable(fun -> reg, SVT_INT, firstValue - secondValue);
+						setVariable(fun->reg, SVT_INT, firstValue - secondValue);
 						break;
 
 					case SLU_MODULUS:
-						setVariable(fun -> reg, SVT_INT, firstValue % secondValue);
+						setVariable(fun->reg, SVT_INT, firstValue % secondValue);
 						break;
 
 					case SLU_DIVIDE:
-						setVariable(fun -> reg, SVT_INT, firstValue / secondValue);
+						setVariable(fun->reg, SVT_INT, firstValue / secondValue);
 						break;
 
 					case SLU_LESSTHAN:
-						setVariable(fun -> reg, SVT_INT, firstValue < secondValue);
+						setVariable(fun->reg, SVT_INT, firstValue < secondValue);
 						break;
 
 					case SLU_MORETHAN:
-						setVariable(fun -> reg, SVT_INT, firstValue > secondValue);
+						setVariable(fun->reg, SVT_INT, firstValue > secondValue);
 						break;
 
 					case SLU_LESS_EQUAL:
-						setVariable(fun -> reg, SVT_INT, firstValue <= secondValue);
+						setVariable(fun->reg, SVT_INT, firstValue <= secondValue);
 						break;
 
 					case SLU_MORE_EQUAL:
-						setVariable(fun -> reg, SVT_INT, firstValue >= secondValue);
+						setVariable(fun->reg, SVT_INT, firstValue >= secondValue);
 						break;
 
 					default:
@@ -1252,7 +1251,7 @@ bool continueFunction(loadedFunction *fun) {
 			return fatal(ERROR_UNKNOWN_CODE);
 		}
 
-		if (advanceNow) fun -> runThisLine ++;
+		if (advanceNow) fun->runThisLine ++;
 
 	}
 	return true;
@@ -1265,22 +1264,22 @@ bool runSludge() {
 	loadedFunction *nextFunction;
 
 	while (thisFunction) {
-		nextFunction = thisFunction -> next;
+		nextFunction = thisFunction->next;
 
-		if (! thisFunction -> freezerLevel) {
-			if (thisFunction -> timeLeft) {
-				if (thisFunction -> timeLeft < 0) {
-					if (! stillPlayingSound(findInSoundCache(speech -> lastFile))) {
-						thisFunction -> timeLeft = 0;
+		if (!thisFunction->freezerLevel) {
+			if (thisFunction->timeLeft) {
+				if (thisFunction->timeLeft < 0) {
+					if (!stillPlayingSound(findInSoundCache(speech->lastFile))) {
+						thisFunction->timeLeft = 0;
 					}
-				} else if (! -- (thisFunction -> timeLeft)) {
+				} else if (!-- (thisFunction->timeLeft)) {
 				}
 			} else {
-				if (thisFunction -> isSpeech) {
-					thisFunction -> isSpeech = false;
+				if (thisFunction->isSpeech) {
+					thisFunction->isSpeech = false;
 					killAllSpeech();
 				}
-				if (! continueFunction(thisFunction))
+				if (!continueFunction(thisFunction))
 					return false;
 			}
 		}
@@ -1291,9 +1290,9 @@ bool runSludge() {
 	if (loadNow) {
 		if (loadNow[0] == ':') {
 			saveGame(loadNow + 1);
-			setVariable(saverFunc -> reg, SVT_INT, 1);
+			setVariable(saverFunc->reg, SVT_INT, 1);
 		} else {
-			if (! loadGame(loadNow)) return false;
+			if (!loadGame(loadNow)) return false;
 		}
 		delete loadNow;
 		loadNow = NULL;
@@ -1303,38 +1302,37 @@ bool runSludge() {
 }
 
 bool loadFunctionCode(loadedFunction *newFunc) {
-#if ALLOW_FILE
-	printf("\nCurrent address: %li\n", ftell(bigDataFile));
+
+	debug(kSludgeDebugDataLoad, "Current address: %i", bigDataFile->pos());
 	unsigned int numLines, numLinesRead;
 
-	if (! openSubSlice(newFunc -> originalNumber)) return false;
+	if (!openSubSlice(newFunc->originalNumber)) return false;
 
-	printf("Load function code\n");
+	debug(kSludgeDebugDataLoad, "Load function code");
 
-	newFunc -> unfreezable  = fgetc(bigDataFile);
+	newFunc->unfreezable  = getch(bigDataFile);
 	numLines                = get2bytes(bigDataFile);
-	printf("numLines: %i\n", numLines);
-	newFunc -> numArgs      = get2bytes(bigDataFile);
-	printf("numArgs: %i\n", newFunc -> numArgs);
-	newFunc -> numLocals    = get2bytes(bigDataFile);
-	printf("numLocals: %i\n", newFunc -> numLocals);
-	newFunc -> compiledLines = new lineOfCode[numLines];
-	if (! checkNew(newFunc -> compiledLines)) return false;
+	debug(kSludgeDebugDataLoad, "numLines: %i", numLines);
+	newFunc->numArgs      = get2bytes(bigDataFile);
+	debug(kSludgeDebugDataLoad, "numArgs: %i", newFunc->numArgs);
+	newFunc->numLocals    = get2bytes(bigDataFile);
+	debug(kSludgeDebugDataLoad, "numLocals: %i", newFunc->numLocals);
+	newFunc->compiledLines = new lineOfCode[numLines];
+	if (!checkNew(newFunc->compiledLines)) return false;
 
 	for (numLinesRead = 0; numLinesRead < numLines; numLinesRead ++) {
-		newFunc -> compiledLines[numLinesRead].theCommand = (sludgeCommand) fgetc(bigDataFile);
-		newFunc -> compiledLines[numLinesRead].param = get2bytes(bigDataFile);
-		printf("command line %i: %i\n", numLinesRead, newFunc->compiledLines[numLinesRead].theCommand);
+		newFunc->compiledLines[numLinesRead].theCommand = (sludgeCommand) getch(bigDataFile);
+		newFunc->compiledLines[numLinesRead].param = get2bytes(bigDataFile);
+		debug(kSludgeDebugDataLoad, "command line %i: %i", numLinesRead, newFunc->compiledLines[numLinesRead].theCommand);
 	}
 	finishAccess();
 
 	// Now we need to reserve memory for the local variables
-	newFunc -> localVars = new variable[newFunc -> numLocals];
-	if (! checkNew(newFunc -> localVars)) return false;
-	for (int a = 0; a < newFunc -> numLocals; a ++) {
-		initVarNew(newFunc -> localVars[a]);
+	newFunc->localVars = new variable[newFunc->numLocals];
+	if (!checkNew(newFunc->localVars)) return false;
+	for (int a = 0; a < newFunc->numLocals; a ++) {
+		initVarNew(newFunc->localVars[a]);
 	}
-#endif
 
 	return true;
 }
@@ -1342,31 +1340,31 @@ bool loadFunctionCode(loadedFunction *newFunc) {
 int startNewFunctionNum(unsigned int funcNum, unsigned int numParamsExpected, loadedFunction *calledBy, variableStack *&vStack, bool returnSommet) {
 	loadedFunction *newFunc = new loadedFunction;
 	checkNew(newFunc);
-	newFunc -> originalNumber = funcNum;
+	newFunc->originalNumber = funcNum;
 
 	loadFunctionCode(newFunc);
 
-	if (newFunc -> numArgs != (int)numParamsExpected) return fatal("Wrong number of parameters!");
-	if (newFunc -> numArgs > newFunc -> numLocals) return fatal("More arguments than local variable space!");
+	if (newFunc->numArgs != (int)numParamsExpected) return fatal("Wrong number of parameters!");
+	if (newFunc->numArgs > newFunc->numLocals) return fatal("More arguments than local variable space!");
 
 	// Now, lets copy the parameters from the calling function's stack...
 
 	while (numParamsExpected) {
 		numParamsExpected --;
-		if (vStack == NULL) return fatal("Corrupted file! The stack's empty and there were still parameters expected");
-		copyVariable(vStack -> thisVar, newFunc -> localVars[numParamsExpected]);
+		if (vStack == NULL) return fatal("Corrupted file!The stack's empty and there were still parameters expected");
+		copyVariable(vStack->thisVar, newFunc->localVars[numParamsExpected]);
 		trimStack(vStack);
 	}
 
-	newFunc -> cancelMe = false;
-	newFunc -> timeLeft = 0;
-	newFunc -> returnSomething = returnSommet;
-	newFunc -> calledBy = calledBy;
-	newFunc -> stack = NULL;
-	newFunc -> freezerLevel = 0;
-	newFunc -> runThisLine = 0;
-	newFunc -> isSpeech = 0;
-	initVarNew(newFunc -> reg);
+	newFunc->cancelMe = false;
+	newFunc->timeLeft = 0;
+	newFunc->returnSomething = returnSommet;
+	newFunc->calledBy = calledBy;
+	newFunc->stack = NULL;
+	newFunc->freezerLevel = 0;
+	newFunc->runThisLine = 0;
+	newFunc->isSpeech = 0;
+	initVarNew(newFunc->reg);
 
 	restartFunction(newFunc);
 	return 1;
@@ -1408,40 +1406,40 @@ bool handleInput() {
 		l = 0;
 	}
 
-	if (! overRegion) getOverRegion();
+	if (!overRegion) getOverRegion();
 
 	if (input.justMoved) {
-		if (currentEvents -> moveMouseFunction) {
-			if (! startNewFunctionNum(currentEvents -> moveMouseFunction, 0, NULL, noStack)) return false;
+		if (currentEvents->moveMouseFunction) {
+			if (!startNewFunctionNum(currentEvents->moveMouseFunction, 0, NULL, noStack)) return false;
 		}
 	}
 	input.justMoved = false;
 
-	if (lastRegion != overRegion && currentEvents -> focusFunction) {
+	if (lastRegion != overRegion && currentEvents->focusFunction) {
 		variableStack *tempStack = new variableStack;
-		if (! checkNew(tempStack)) return false;
+		if (!checkNew(tempStack)) return false;
 
-		initVarNew(tempStack -> thisVar);
+		initVarNew(tempStack->thisVar);
 		if (overRegion) {
-			setVariable(tempStack -> thisVar, SVT_OBJTYPE, overRegion -> thisType -> objectNum);
+			setVariable(tempStack->thisVar, SVT_OBJTYPE, overRegion->thisType->objectNum);
 		} else {
-			setVariable(tempStack -> thisVar, SVT_INT, 0);
+			setVariable(tempStack->thisVar, SVT_INT, 0);
 		}
-		tempStack -> next = NULL;
-		if (! startNewFunctionNum(currentEvents -> focusFunction, 1, NULL, tempStack)) return false;
+		tempStack->next = NULL;
+		if (!startNewFunctionNum(currentEvents->focusFunction, 1, NULL, tempStack)) return false;
 	}
-	if (input.leftRelease && currentEvents -> leftMouseUpFunction)  {
-		if (! startNewFunctionNum(currentEvents -> leftMouseUpFunction, 0, NULL, noStack)) return false;
+	if (input.leftRelease && currentEvents->leftMouseUpFunction)  {
+		if (!startNewFunctionNum(currentEvents->leftMouseUpFunction, 0, NULL, noStack)) return false;
 	}
-	if (input.rightRelease && currentEvents -> rightMouseUpFunction) {
-		if (! startNewFunctionNum(currentEvents -> rightMouseUpFunction, 0, NULL, noStack)) return false;
+	if (input.rightRelease && currentEvents->rightMouseUpFunction) {
+		if (!startNewFunctionNum(currentEvents->rightMouseUpFunction, 0, NULL, noStack)) return false;
 	}
-	if (input.leftClick && currentEvents -> leftMouseFunction)
-		if (! startNewFunctionNum(currentEvents -> leftMouseFunction, 0, NULL, noStack)) return false;
-	if (input.rightClick && currentEvents -> rightMouseFunction) {
-		if (! startNewFunctionNum(currentEvents -> rightMouseFunction, 0, NULL, noStack)) return false;
+	if (input.leftClick && currentEvents->leftMouseFunction)
+		if (!startNewFunctionNum(currentEvents->leftMouseFunction, 0, NULL, noStack)) return false;
+	if (input.rightClick && currentEvents->rightMouseFunction) {
+		if (!startNewFunctionNum(currentEvents->rightMouseFunction, 0, NULL, noStack)) return false;
 	}
-	if (input.keyPressed && currentEvents -> spaceFunction) {
+	if (input.keyPressed && currentEvents->spaceFunction) {
 		char *tempString = NULL;
 		switch (input.keyPressed) {
 		case 127:
@@ -1551,13 +1549,13 @@ bool handleInput() {
 
 		if (tempString) {
 			variableStack *tempStack = new variableStack;
-			if (! checkNew(tempStack)) return false;
-			initVarNew(tempStack -> thisVar);
-			makeTextVar(tempStack -> thisVar, tempString);
+			if (!checkNew(tempStack)) return false;
+			initVarNew(tempStack->thisVar);
+			makeTextVar(tempStack->thisVar, tempString);
 			delete tempString;
 			tempString = NULL;
-			tempStack -> next = NULL;
-			if (! startNewFunctionNum(currentEvents -> spaceFunction, 1, NULL, tempStack)) return false;
+			tempStack->next = NULL;
+			if (!startNewFunctionNum(currentEvents->spaceFunction, 1, NULL, tempStack)) return false;
 		}
 	}
 	input.rightClick = false;
diff --git a/engines/sludge/sludger.h b/engines/sludge/sludger.h
index ff24b24..d67192d 100644
--- a/engines/sludge/sludger.h
+++ b/engines/sludge/sludger.h
@@ -29,6 +29,8 @@
 #include "csludge.h"
 #include "language.h"
 
+#include "common/file.h"
+
 namespace Sludge {
 
 #ifndef _WIN32
@@ -85,15 +87,13 @@ int startNewFunctionNum(unsigned int, unsigned int, loadedFunction *, variableSt
 bool handleInput();
 void restartFunction(loadedFunction *fun);
 bool loadFunctionCode(loadedFunction *newFunc);
-#if ALLOW_FILE
-void loadHandlers(FILE *fp);
-void saveHandlers(FILE *fp);
-#endif
+void loadHandlers(Common::SeekableReadStream *stream);
+void saveHandlers(Common::WriteStream *stream);
+
 void finishFunction(loadedFunction *fun);
 void abortFunction(loadedFunction *fun);
-#if ALLOW_FILE
-FILE *openAndVerify(char *filename, char extra1, char extra2, const char *er, int &fileVersion);
-#endif
+Common::File *openAndVerify(char *filename, char extra1, char extra2, const char *er, int &fileVersion);
+
 void freezeSubs();
 void unfreezeSubs();
 void completeTimers();
diff --git a/engines/sludge/sound.h b/engines/sludge/sound.h
index 5bb3f9d..1c5af96 100644
--- a/engines/sludge/sound.h
+++ b/engines/sludge/sound.h
@@ -31,6 +31,8 @@
 
 #include "variable.h"
 
+#include "common/file.h"
+
 namespace Sludge {
 
 // Sound list stuff
@@ -66,11 +68,9 @@ bool stillPlayingSound(int ch);
 bool getSoundCacheStack(stackHandler *sH);
 int findInSoundCache(int a);
 
-#if ALLOW_FILE
 void debugSounds();
-void loadSounds(FILE *fp);
-void saveSounds(FILE *fp);
-#endif
+void loadSounds(Common::SeekableReadStream *stream);
+void saveSounds(Common::WriteStream *stream);
 
 unsigned int getSoundSource(int index);
 
diff --git a/engines/sludge/sound_bass.cpp b/engines/sludge/sound_bass.cpp
index 017796c..6f16d66 100644
--- a/engines/sludge/sound_bass.cpp
+++ b/engines/sludge/sound_bass.cpp
@@ -49,10 +49,10 @@ soundThing soundCache[MAX_SAMPLES];
 int defVol = 128;
 int defSoundVol = 255;
 
-char *loadEntireFileToMemory(FILE *inputFile, uint32_t size) {
+char *loadEntireFileToMemory(Common::SeekableReadStream *inputFile, uint32_t size) {
 	char *allData = new char[size];
-	if (! allData) return NULL;
-	fread(allData, size, 1, inputFile);
+	if (!allData) return NULL;
+	inputFile->read(allData, size);
 	finishAccess();
 
 	return allData;
@@ -136,17 +136,17 @@ bool playMOD(int f, int a, int fromTrack) {
 
 		char *memImage;
 		memImage = loadEntireFileToMemory(bigDataFile, length);
-		if (! memImage) return fatal(ERROR_MUSIC_MEMORY_LOW);
+		if (!memImage) return fatal(ERROR_MUSIC_MEMORY_LOW);
 
 		mod[a] = BASS_MusicLoad(true, memImage, 0, length, BASS_MUSIC_LOOP | BASS_MUSIC_RAMP/*|BASS_MUSIC_PRESCAN needed too if we're going to set the position in bytes*/, 0);
 		delete memImage;
 
-		if (! mod[a]) {
+		if (!mod[a]) {
 
 		} else {
 			setMusicVolume(a, defVol);
 
-			if (! BASS_ChannelPlay(mod[a], true))
+			if (!BASS_ChannelPlay(mod[a], true))
 				debugOut("playMOD: Error %d!\n", BASS_ErrorGetCode());
 
 			BASS_ChannelSetPosition(mod[a], MAKELONG(fromTrack, 0), BASS_POS_MUSIC_ORDER);
@@ -161,7 +161,7 @@ void setMusicVolume(int a, int v) {
 	int ret;
 	if (soundOK && mod[a]) {
 		ret = BASS_ChannelSetAttribute(mod[a], BASS_ATTRIB_VOL, (float) v / 256);
-		if (! ret) {
+		if (!ret) {
 			debugOut("setMusicVolume: Error %d\n", BASS_ErrorGetCode());
 		}
 	}
@@ -215,19 +215,19 @@ int findEmptySoundSlot() {
 	for (t = 0; t < MAX_SAMPLES; t ++) {
 		emptySoundSlot ++;
 		emptySoundSlot %= MAX_SAMPLES;
-		if (! soundCache[emptySoundSlot].sample)
+		if (!soundCache[emptySoundSlot].sample)
 			return emptySoundSlot;
 	}
 
-	// Argh! They're all playing! Let's trash the oldest that's not looping...
+	// Argh!They're all playing!Let's trash the oldest that's not looping...
 
 	for (t = 0; t < MAX_SAMPLES; t ++) {
 		emptySoundSlot ++;
 		emptySoundSlot %= MAX_SAMPLES;
-		if (! soundCache[emptySoundSlot].looping) return emptySoundSlot;
+		if (!soundCache[emptySoundSlot].looping) return emptySoundSlot;
 	}
 
-	// Holy crap, they're all looping! What's this twat playing at?
+	// Holy crap, they're all looping!What's this twat playing at?
 
 	emptySoundSlot ++;
 	emptySoundSlot %= MAX_SAMPLES;
@@ -246,7 +246,7 @@ void soundWarning (char * t, int i) {
 
 bool forceRemoveSound() {
 	for (int a = 0; a < 8; a ++) {
-		if (soundCache[a].fileLoaded != -1 && ! stillPlayingSound(a)) {
+		if (soundCache[a].fileLoaded != -1 && !stillPlayingSound(a)) {
 //			soundWarning ("Deleting silent sound", a);
 			freeSound(a);
 			return 1;
@@ -267,7 +267,7 @@ bool forceRemoveSound() {
 int cacheSound(int f) {
 	setResourceForFatal(f);
 
-	if (! soundOK) return 0;
+	if (!soundOK) return 0;
 
 	int a = findInSoundCache(f);
 	if (a != -1) return a;
@@ -276,7 +276,7 @@ int cacheSound(int f) {
 	freeSound(a);
 
 	uint32_t length = openFileFromNum(f);
-	if (! length) return -1;
+	if (!length) return -1;
 
 	char *memImage;
 
@@ -286,7 +286,7 @@ int cacheSound(int f) {
 		memImage = loadEntireFileToMemory(bigDataFile, length);
 		tryAgain = memImage == NULL;
 		if (tryAgain) {
-			if (! forceRemoveSound()) {
+			if (!forceRemoveSound()) {
 				fatal(ERROR_SOUND_MEMORY_LOW);
 				return -1;
 			}
@@ -347,32 +347,32 @@ void debugSounds () {
 }
 // */
 
-void saveSounds(FILE *fp) {
+void saveSounds(Common::WriteStream *stream) {
 	if (soundOK) {
 		for (int i = 0; i < MAX_SAMPLES; i ++) {
 			if (soundCache[i].looping) {
-				fputc(1, fp);
-				put2bytes(soundCache[i].fileLoaded, fp);
-				put2bytes(soundCache[i].vol, fp);
+				putch(1, stream);
+				put2bytes(soundCache[i].fileLoaded, stream);
+				put2bytes(soundCache[i].vol, stream);
 			}
 		}
 	}
-	fputc(0, fp);
-	put2bytes(defSoundVol, fp);
-	put2bytes(defVol, fp);
+	putch(0, stream);
+	put2bytes(defSoundVol, stream);
+	put2bytes(defVol, stream);
 }
 
-void loadSounds(FILE *fp) {
+void loadSounds(Common::SeekableReadStream *stream) {
 	for (int i = 0; i < MAX_SAMPLES; i ++) freeSound(i);
 
-	while (fgetc(fp)) {
-		int fileLoaded = get2bytes(fp);
-		defSoundVol = get2bytes(fp);
+	while (getch(stream)) {
+		int fileLoaded = get2bytes(stream);
+		defSoundVol = get2bytes(stream);
 		startSound(fileLoaded, 1);
 	}
 
-	defSoundVol = get2bytes(fp);
-	defVol = get2bytes(fp);
+	defSoundVol = get2bytes(stream);
+	defVol = get2bytes(stream);
 }
 
 bool getSoundCacheStack(stackHandler *sH) {
@@ -382,7 +382,7 @@ bool getSoundCacheStack(stackHandler *sH) {
 	for (int a = 0; a < MAX_SAMPLES; a ++) {
 		if (soundCache[a].fileLoaded != -1) {
 			setVariable(newFileHandle, SVT_FILE, soundCache[a].fileLoaded);
-			if (! addVarToStackQuick(newFileHandle, sH -> first)) return false;
+			if (!addVarToStackQuick(newFileHandle, sH -> first)) return false;
 			if (sH -> last == NULL) sH -> last = sH -> first;
 		}
 	}
diff --git a/engines/sludge/sound_nosound.cpp b/engines/sludge/sound_nosound.cpp
index 8f8bb28..292148b 100644
--- a/engines/sludge/sound_nosound.cpp
+++ b/engines/sludge/sound_nosound.cpp
@@ -112,23 +112,22 @@ bool startSound(int f, bool loopy) {
 	return true;
 }
 
-#if ALLOW_FILE
-void saveSounds(FILE *fp) {
-	fputc(0, fp);
-	put2bytes(defSoundVol, fp);
-	put2bytes(defVol, fp);
+void saveSounds(Common::WriteStream *stream) {
+	putch(0, stream);
+	put2bytes(defSoundVol, stream);
+	put2bytes(defVol, stream);
 }
 
-void loadSounds(FILE *fp) {
-	while (fgetc(fp)) {
-		get2bytes(fp);
-		get2bytes(fp);
+void loadSounds(Common::SeekableReadStream *stream) {
+	while (getch(stream)) {
+		get2bytes(stream);
+		get2bytes(stream);
 	}
 
-	defSoundVol = get2bytes(fp);
-	defVol = get2bytes(fp);
+	defSoundVol = get2bytes(stream);
+	defVol = get2bytes(stream);
 }
-#endif
+
 bool getSoundCacheStack(stackHandler *sH) {
 //#pragma unused (sH)
 	return true;
diff --git a/engines/sludge/sound_openal.cpp b/engines/sludge/sound_openal.cpp
index aa8f8e1..5faefdb 100644
--- a/engines/sludge/sound_openal.cpp
+++ b/engines/sludge/sound_openal.cpp
@@ -33,6 +33,8 @@
 #include "moreio.h"
 #include "fileset.h"
 
+#include "common/file.h"
+
 #define MAX_SAMPLES 8
 #define MAX_MODS 3
 #define NUM_BUFS 3
@@ -359,13 +361,12 @@ void playStream(int a, bool isMOD, bool loopy) {
 #endif
 }
 
-#if ALLOW_FILE
-char *loadEntireFileToMemory(FILE *inputFile, uint32_t size) {
+char *loadEntireFileToMemory(Common::SeekableReadStream *inputFile, uint32_t size) {
 	char *allData = new char[size];
 	if (! allData) return NULL;
 
-	size_t bytes_read = fread(allData, size, 1, inputFile);
-	if (bytes_read != size && ferror(inputFile)) {
+	size_t bytes_read = inputFile->read(allData, size);
+	if (bytes_read != size && inputFile->err()) {
 		debugOut("Reading error in loadEntireFileToMemory.\n");
 	}
 
@@ -373,10 +374,8 @@ char *loadEntireFileToMemory(FILE *inputFile, uint32_t size) {
 
 	return allData;
 }
-#endif
 
 bool playMOD(int f, int a, int fromTrack) {
-#if ALLOW_FILE
 	if (! soundOK) return true;
 	stopMOD(a);
 
@@ -387,7 +386,6 @@ bool playMOD(int f, int a, int fromTrack) {
 		setResourceForFatal(-1);
 		return false;
 	}
-#endif
 #if 0
 	unsigned char *memImage;
 	memImage = (unsigned char *) loadEntireFileToMemory(bigDataFile, length);
@@ -592,35 +590,33 @@ bool startSound(int f, bool loopy) {
 	return true;
 }
 
-#if ALLOW_FILE
-void saveSounds(FILE *fp) {
+void saveSounds(Common::WriteStream *stream) {
 	if (soundOK) {
 		for (int i = 0; i < MAX_SAMPLES; i ++) {
 			if (soundCache[i].looping) {
-				fputc(1, fp);
-				put2bytes(soundCache[i].fileLoaded, fp);
-				put2bytes(soundCache[i].vol, fp);
+				putch(1, stream);
+				put2bytes(soundCache[i].fileLoaded, stream);
+				put2bytes(soundCache[i].vol, stream);
 			}
 		}
 	}
-	fputc(0, fp);
-	put2bytes(defSoundVol, fp);
-	put2bytes(defVol, fp);
+	putch(0, stream);
+	put2bytes(defSoundVol, stream);
+	put2bytes(defVol, stream);
 }
 
-void loadSounds(FILE *fp) {
+void loadSounds(Common::SeekableReadStream *stream) {
 	for (int i = 0; i < MAX_SAMPLES; i ++) freeSound(i);
 
-	while (fgetc(fp)) {
-		int fileLoaded = get2bytes(fp);
-		defSoundVol = get2bytes(fp);
+	while (getch(stream)) {
+		int fileLoaded = get2bytes(stream);
+		defSoundVol = get2bytes(stream);
 		startSound(fileLoaded, 1);
 	}
 
-	defSoundVol = get2bytes(fp);
-	defVol = get2bytes(fp);
+	defSoundVol = get2bytes(stream);
+	defVol = get2bytes(stream);
 }
-#endif
 
 bool getSoundCacheStack(stackHandler *sH) {
 	variable newFileHandle;
@@ -742,12 +738,12 @@ void playSoundList(soundList *s) {
 #endif
 }
 
-#if ALLOW_FILE
 void playMovieStream(int a) {
+#if 0
 	if (! soundOK) return;
 	ALboolean ok;
 	ALuint src;
-#if 0
+
 	alGenSources(1, &src);
 	if (alGetError() != AL_NO_ERROR) {
 		debugOut("Failed to create OpenAL source!\n");
@@ -758,22 +754,20 @@ void playMovieStream(int a) {
 
 	ok = alurePlaySourceStream(src, soundCache[a].stream,
 	                           10, 0, sound_eos_callback, &intpointers[a]);
-#endif
 	if (!ok) {
-#if 0
 		debugOut("Failed to play stream: %s\n", alureGetErrorString());
 		alDeleteSources(1, &src);
 		if (alGetError() != AL_NO_ERROR) {
 			debugOut("Failed to delete OpenAL source!\n");
 		}
-#endif
+
 		soundCache[a].playingOnSource = 0;
 	} else {
 		soundCache[a].playingOnSource = src;
 		soundCache[a].playing = true;
 	}
-}
 #endif
+}
 
 #if 0
 int initMovieSound(int f, ALenum format, int audioChannels, ALuint samplerate,
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index 792fe66..ec4144f 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -116,7 +116,7 @@ bool reserveSpritePal(spritePalette &sP, int n) {
 }
 
 bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
-#if ALLOW_FILE
+#if 0
 	int i, tex_num, total, picwidth, picheight, spriteBankVersion = 0, howmany = 0, startIndex = 0;
 	int *totalwidth, * maxheight;
 	int numTextures = 0;
diff --git a/engines/sludge/statusba.cpp b/engines/sludge/statusba.cpp
index e7dc4cb..d90d3a2 100644
--- a/engines/sludge/statusba.cpp
+++ b/engines/sludge/statusba.cpp
@@ -41,105 +41,105 @@ extern int fontHeight;
 extern float cameraZoom;
 
 void setLitStatus(int i) {
-	nowStatus -> litStatus = i;
+	nowStatus->litStatus = i;
 }
 
 void killLastStatus() {
-	if (nowStatus -> firstStatusBar) {
-		statusBar *kill = nowStatus -> firstStatusBar;
-		nowStatus -> firstStatusBar = kill -> next;
-		delete kill -> text;
+	if (nowStatus->firstStatusBar) {
+		statusBar *kill = nowStatus->firstStatusBar;
+		nowStatus->firstStatusBar = kill->next;
+		delete kill->text;
 		delete kill;
 	}
 }
 
 void clearStatusBar() {
-	statusBar *stat = nowStatus -> firstStatusBar;
+	statusBar *stat = nowStatus->firstStatusBar;
 	statusBar *kill;
-	nowStatus -> litStatus = -1;
+	nowStatus->litStatus = -1;
 	while (stat) {
 		kill = stat;
-		stat = stat -> next;
-		delete kill -> text;
+		stat = stat->next;
+		delete kill->text;
 		delete kill;
 	}
-	nowStatus -> firstStatusBar = NULL;
+	nowStatus->firstStatusBar = NULL;
 }
 
 void addStatusBar() {
 	statusBar *newStat = new statusBar;
 	if (checkNew(newStat)) {
-		newStat -> next = nowStatus -> firstStatusBar;
-		newStat -> text = copyString("");
-		nowStatus -> firstStatusBar = newStat;
+		newStat->next = nowStatus->firstStatusBar;
+		newStat->text = copyString("");
+		nowStatus->firstStatusBar = newStat;
 	}
 }
 
 void setStatusBar(char *txt) {
-	if (nowStatus -> firstStatusBar) {
-		delete nowStatus -> firstStatusBar -> text;
-		nowStatus -> firstStatusBar -> text = copyString(txt);
+	if (nowStatus->firstStatusBar) {
+		delete nowStatus->firstStatusBar->text;
+		nowStatus->firstStatusBar->text = copyString(txt);
 	}
 }
 
 void positionStatus(int x, int y) {
-	nowStatus -> statusX = x;
-	nowStatus -> statusY = y;
+	nowStatus->statusX = x;
+	nowStatus->statusY = y;
 }
 
 void drawStatusBar() {
-	int y = nowStatus -> statusY, n = 0;
-	statusBar *stat = nowStatus -> firstStatusBar;
+	int y = nowStatus->statusY, n = 0;
+	statusBar *stat = nowStatus->firstStatusBar;
 	fixFont(litVerbLinePalette);
 	fixFont(verbLinePalette);
 	while (stat) {
-		switch (nowStatus -> alignStatus) {
+		switch (nowStatus->alignStatus) {
 		case IN_THE_CENTRE:
-			pasteString(stat -> text, ((winWidth - stringWidth(stat -> text)) >> 1) / cameraZoom, y / cameraZoom, (n ++ == nowStatus -> litStatus) ? litVerbLinePalette : verbLinePalette);
+			pasteString(stat->text, ((winWidth - stringWidth(stat->text)) >> 1) / cameraZoom, y / cameraZoom, (n ++ == nowStatus->litStatus) ? litVerbLinePalette : verbLinePalette);
 			break;
 
 		case 1001:
-			pasteString(stat -> text, (winWidth - stringWidth(stat -> text)) - nowStatus -> statusX / cameraZoom, y / cameraZoom, (n ++ == nowStatus -> litStatus) ? litVerbLinePalette : verbLinePalette);
+			pasteString(stat->text, (winWidth - stringWidth(stat->text)) - nowStatus->statusX / cameraZoom, y / cameraZoom, (n ++ == nowStatus->litStatus) ? litVerbLinePalette : verbLinePalette);
 			break;
 
 		default:
-			pasteString(stat -> text, nowStatus -> statusX / cameraZoom, y / cameraZoom, (n ++ == nowStatus -> litStatus) ? litVerbLinePalette : verbLinePalette);
+			pasteString(stat->text, nowStatus->statusX / cameraZoom, y / cameraZoom, (n ++ == nowStatus->litStatus) ? litVerbLinePalette : verbLinePalette);
 		}
-		stat = stat -> next;
+		stat = stat->next;
 		y -= fontHeight;
 	}
 }
 
 void statusBarColour(byte r, byte g, byte b) {
 	setFontColour(verbLinePalette, r, g, b);
-	nowStatus -> statusR = r;
-	nowStatus -> statusG = g;
-	nowStatus -> statusB = b;
+	nowStatus->statusR = r;
+	nowStatus->statusG = g;
+	nowStatus->statusB = b;
 }
 
 void statusBarLitColour(byte r, byte g, byte b) {
 	setFontColour(litVerbLinePalette, r, g, b);
-	nowStatus -> statusLR = r;
-	nowStatus -> statusLG = g;
-	nowStatus -> statusLB = b;
+	nowStatus->statusLR = r;
+	nowStatus->statusLG = g;
+	nowStatus->statusLB = b;
 }
 
 statusStuff *copyStatusBarStuff(statusStuff *here) {
 
 	// Things we want to keep
-	here -> statusLR = nowStatus -> statusLR;
-	here -> statusLG = nowStatus -> statusLG;
-	here -> statusLB = nowStatus -> statusLB;
-	here -> statusR = nowStatus -> statusR;
-	here -> statusG = nowStatus -> statusG;
-	here -> statusB = nowStatus -> statusB;
-	here -> alignStatus = nowStatus -> alignStatus;
-	here -> statusX = nowStatus -> statusX;
-	here -> statusY = nowStatus -> statusY;
+	here->statusLR = nowStatus->statusLR;
+	here->statusLG = nowStatus->statusLG;
+	here->statusLB = nowStatus->statusLB;
+	here->statusR = nowStatus->statusR;
+	here->statusG = nowStatus->statusG;
+	here->statusB = nowStatus->statusB;
+	here->alignStatus = nowStatus->alignStatus;
+	here->statusX = nowStatus->statusX;
+	here->statusY = nowStatus->statusY;
 
 	// Things we want to clear
-	here -> litStatus = -1;
-	here -> firstStatusBar = NULL;
+	here->litStatus = -1;
+	here->firstStatusBar = NULL;
 
 	statusStuff *old = nowStatus;
 	nowStatus = here;
@@ -149,8 +149,8 @@ statusStuff *copyStatusBarStuff(statusStuff *here) {
 
 void restoreBarStuff(statusStuff *here) {
 	delete nowStatus;
-	setFontColour(verbLinePalette, here -> statusR, here -> statusG, here -> statusB);
-	setFontColour(litVerbLinePalette, here -> statusLR, here -> statusLG, here -> statusLB);
+	setFontColour(verbLinePalette, here->statusR, here->statusG, here->statusB);
+	setFontColour(litVerbLinePalette, here->statusLR, here->statusLG, here->statusLB);
 	nowStatus = here;
 }
 
@@ -166,68 +166,66 @@ void initStatusBar() {
 }
 
 const char *statusBarText() {
-	if (nowStatus -> firstStatusBar) {
-		return nowStatus -> firstStatusBar -> text;
+	if (nowStatus->firstStatusBar) {
+		return nowStatus->firstStatusBar->text;
 	} else {
 		return "";
 	}
 }
 
-#if ALLOW_FILE
-void saveStatusBars(FILE *fp) {
-	statusBar *viewLine = nowStatus -> firstStatusBar;
+void saveStatusBars(Common::WriteStream *stream) {
+	statusBar *viewLine = nowStatus->firstStatusBar;
 
-	put2bytes(nowStatus -> alignStatus, fp);
-	putSigned(nowStatus -> litStatus, fp);
-	put2bytes(nowStatus -> statusX, fp);
-	put2bytes(nowStatus -> statusY, fp);
+	put2bytes(nowStatus->alignStatus, stream);
+	putSigned(nowStatus->litStatus, stream);
+	put2bytes(nowStatus->statusX, stream);
+	put2bytes(nowStatus->statusY, stream);
 
-	fputc(nowStatus -> statusR, fp);
-	fputc(nowStatus -> statusG, fp);
-	fputc(nowStatus -> statusB, fp);
-	fputc(nowStatus -> statusLR, fp);
-	fputc(nowStatus -> statusLG, fp);
-	fputc(nowStatus -> statusLB, fp);
+	putch(nowStatus->statusR, stream);
+	putch(nowStatus->statusG, stream);
+	putch(nowStatus->statusB, stream);
+	putch(nowStatus->statusLR, stream);
+	putch(nowStatus->statusLG, stream);
+	putch(nowStatus->statusLB, stream);
 
 	// Write what's being said
 	while (viewLine) {
-		fputc(1, fp);
-		writeString(viewLine -> text, fp);
-		viewLine = viewLine -> next;
+		putch(1, stream);
+		writeString(viewLine->text, stream);
+		viewLine = viewLine->next;
 	}
-	fputc(0, fp);
+	putch(0, stream);
 }
 
-bool loadStatusBars(FILE *fp) {
+bool loadStatusBars(Common::SeekableReadStream *stream) {
 	clearStatusBar();
 
-	nowStatus -> alignStatus = get2bytes(fp);
-	nowStatus -> litStatus = getSigned(fp);
-	nowStatus -> statusX = get2bytes(fp);
-	nowStatus -> statusY = get2bytes(fp);
+	nowStatus->alignStatus = get2bytes(stream);
+	nowStatus->litStatus = getSigned(stream);
+	nowStatus->statusX = get2bytes(stream);
+	nowStatus->statusY = get2bytes(stream);
 
-	nowStatus -> statusR = fgetc(fp);
-	nowStatus -> statusG = fgetc(fp);
-	nowStatus -> statusB = fgetc(fp);
-	nowStatus -> statusLR = fgetc(fp);
-	nowStatus -> statusLG = fgetc(fp);
-	nowStatus -> statusLB = fgetc(fp);
+	nowStatus->statusR = getch(stream);
+	nowStatus->statusG = getch(stream);
+	nowStatus->statusB = getch(stream);
+	nowStatus->statusLR = getch(stream);
+	nowStatus->statusLG = getch(stream);
+	nowStatus->statusLB = getch(stream);
 
-	setFontColour(verbLinePalette, nowStatus -> statusR, nowStatus -> statusG, nowStatus -> statusB);
-	setFontColour(litVerbLinePalette, nowStatus -> statusLR, nowStatus -> statusLG, nowStatus -> statusLB);
+	setFontColour(verbLinePalette, nowStatus->statusR, nowStatus->statusG, nowStatus->statusB);
+	setFontColour(litVerbLinePalette, nowStatus->statusLR, nowStatus->statusLG, nowStatus->statusLB);
 	// Read what's being said
-	statusBar * * viewLine = & (nowStatus -> firstStatusBar);
+	statusBar * * viewLine = & (nowStatus->firstStatusBar);
 	statusBar *newOne;
-	while (fgetc(fp)) {
+	while (getch(stream)) {
 		newOne = new statusBar;
 		if (! checkNew(newOne)) return false;
-		newOne -> text = readString(fp);
-		newOne -> next = NULL;
+		newOne->text = readString(stream);
+		newOne->next = NULL;
 		(* viewLine) = newOne;
-		viewLine = & (newOne -> next);
+		viewLine = & (newOne->next);
 	}
 	return true;
 }
-#endif
 
 } // End of namespace Sludge
diff --git a/engines/sludge/statusba.h b/engines/sludge/statusba.h
index 2f0d30a..03c61cf 100644
--- a/engines/sludge/statusba.h
+++ b/engines/sludge/statusba.h
@@ -51,11 +51,9 @@ const char *statusBarText();
 void positionStatus(int, int);
 void drawStatusBar();
 
-#if ALLOW_FILE
 // Load and save
-bool loadStatusBars(FILE *fp);
-void saveStatusBars(FILE *fp);
-#endif
+bool loadStatusBars(Common::SeekableReadStream *stream);
+void saveStatusBars(Common::WriteStream *stream);
 
 // For freezing
 void restoreBarStuff(statusStuff *here);
diff --git a/engines/sludge/talk.cpp b/engines/sludge/talk.cpp
index b6bc864..abee33c 100644
--- a/engines/sludge/talk.cpp
+++ b/engines/sludge/talk.cpp
@@ -44,32 +44,32 @@ float speechSpeed = 1;
 void initSpeech() {
 	speech = new speechStruct;
 	if (checkNew(speech)) {
-		speech -> currentTalker = NULL;
-		speech -> allSpeech = NULL;
-		speech -> speechY = 0;
-		speech -> lastFile = -1;
+		speech->currentTalker = NULL;
+		speech->allSpeech = NULL;
+		speech->speechY = 0;
+		speech->lastFile = -1;
 	}
 }
 
 void killAllSpeech() {
-	if (speech -> lastFile != -1) {
+	if (speech->lastFile != -1) {
 #if 0
-		huntKillSound(speech -> lastFile);
+		huntKillSound(speech->lastFile);
 #endif
-		speech -> lastFile = -1;
+		speech->lastFile = -1;
 	}
 
-	if (speech -> currentTalker) {
-		makeSilent(* (speech -> currentTalker));
-		speech -> currentTalker = NULL;
+	if (speech->currentTalker) {
+		makeSilent(* (speech->currentTalker));
+		speech->currentTalker = NULL;
 	}
 
 	speechLine *killMe;
 
-	while (speech -> allSpeech) {
-		killMe = speech -> allSpeech;
-		speech -> allSpeech = speech -> allSpeech -> next;
-		delete killMe -> textLine;
+	while (speech->allSpeech) {
+		killMe = speech->allSpeech;
+		speech->allSpeech = speech->allSpeech->next;
+		delete killMe->textLine;
 		delete killMe;
 	}
 }
@@ -79,7 +79,7 @@ void killAllSpeech() {
 
 inline void setObjFontColour(objectType *t) {
 #if 0
-	setFontColour(speech -> talkCol, t -> r, t -> g, t -> b);
+	setFontColour(speech->talkCol, t->r, t->g, t->b);
 #endif
 }
 
@@ -90,10 +90,10 @@ void addSpeechLine(char *theLine, int x, int &offset) {
 	speechLine *newLine = new speechLine;
 	checkNew(newLine);
 
-	newLine -> next = speech -> allSpeech;
-	newLine -> textLine = copyString(theLine);
-	newLine -> x = xx1;
-	speech -> allSpeech = newLine;
+	newLine->next = speech->allSpeech;
+	newLine->textLine = copyString(theLine);
+	newLine->x = xx1;
+	speech->allSpeech = newLine;
 	if ((xx1 < 5) && (offset < (5 - xx1))) {
 		offset = 5 - xx1;
 	} else if ((xx2 >= ((float)winWidth / cameraZoom) - 5) && (offset > (((float)winWidth / cameraZoom) - 5 - xx2))) {
@@ -102,7 +102,7 @@ void addSpeechLine(char *theLine, int x, int &offset) {
 }
 
 int isThereAnySpeechGoingOn() {
-	return speech -> allSpeech ? speech -> lookWhosTalking : -1;
+	return speech->allSpeech ? speech->lookWhosTalking : -1;
 }
 
 int wrapSpeechXY(char *theText, int x, int y, int wrap, int sampleFile) {
@@ -117,13 +117,13 @@ int wrapSpeechXY(char *theText, int x, int y, int wrap, int sampleFile) {
 #if 0
 			if (startSound(sampleFile, false)) {
 				speechTime = -10;
-				speech -> lastFile = sampleFile;
+				speech->lastFile = sampleFile;
 				if (speechMode == 2) return -10;
 			}
 #endif
 		}
 	}
-	speech -> speechY = y;
+	speech->speechY = y;
 
 	while (strlen(theText) > wrap) {
 		a = wrap;
@@ -143,24 +143,24 @@ int wrapSpeechXY(char *theText, int x, int y, int wrap, int sampleFile) {
 	addSpeechLine(theText, x, offset);
 	y -= fontHeight / cameraZoom;
 
-	if (y < 0) speech -> speechY -= y;
-	else if (speech -> speechY > cameraY + (float)(winHeight - fontHeight / 3) / cameraZoom) speech -> speechY = cameraY + (float)(winHeight - fontHeight / 3) / cameraZoom;
+	if (y < 0) speech->speechY -= y;
+	else if (speech->speechY > cameraY + (float)(winHeight - fontHeight / 3) / cameraZoom) speech->speechY = cameraY + (float)(winHeight - fontHeight / 3) / cameraZoom;
 
 	if (offset) {
-		speechLine *viewLine = speech -> allSpeech;
+		speechLine *viewLine = speech->allSpeech;
 		while (viewLine) {
-			viewLine -> x += offset;
-			viewLine = viewLine -> next;
+			viewLine->x += offset;
+			viewLine = viewLine->next;
 		}
 	}
 	return speechTime;
 }
 
 int wrapSpeechPerson(char *theText, onScreenPerson &thePerson, int sampleFile, bool animPerson) {
-	int i = wrapSpeechXY(theText, thePerson.x - cameraX, thePerson.y - cameraY - (thePerson.scale * (thePerson.height - thePerson.floaty)) - thePerson.thisType -> speechGap, thePerson.thisType -> wrapSpeech, sampleFile);
+	int i = wrapSpeechXY(theText, thePerson.x - cameraX, thePerson.y - cameraY - (thePerson.scale * (thePerson.height - thePerson.floaty)) - thePerson.thisType->speechGap, thePerson.thisType->wrapSpeech, sampleFile);
 	if (animPerson) {
 		makeTalker(thePerson);
-		speech -> currentTalker = & thePerson;
+		speech->currentTalker = &thePerson;
 	}
 	return i;
 }
@@ -168,20 +168,20 @@ int wrapSpeechPerson(char *theText, onScreenPerson &thePerson, int sampleFile, b
 int wrapSpeech(char *theText, int objT, int sampleFile, bool animPerson) {
 	int i;
 
-	speech -> lookWhosTalking = objT;
+	speech->lookWhosTalking = objT;
 	onScreenPerson *thisPerson = findPerson(objT);
 	if (thisPerson) {
-		setObjFontColour(thisPerson -> thisType);
+		setObjFontColour(thisPerson->thisType);
 		i = wrapSpeechPerson(theText, * thisPerson, sampleFile, animPerson);
 	} else {
 		screenRegion *thisRegion = getRegionForObject(objT);
 		if (thisRegion) {
-			setObjFontColour(thisRegion -> thisType);
-			i = wrapSpeechXY(theText, ((thisRegion -> x1 + thisRegion -> x2) >> 1) - cameraX, thisRegion -> y1 - thisRegion -> thisType -> speechGap - cameraY, thisRegion -> thisType -> wrapSpeech, sampleFile);
+			setObjFontColour(thisRegion->thisType);
+			i = wrapSpeechXY(theText, ((thisRegion->x1 + thisRegion->x2) >> 1) - cameraX, thisRegion->y1 - thisRegion->thisType->speechGap - cameraY, thisRegion->thisType->wrapSpeech, sampleFile);
 		} else {
 			objectType *temp = findObjectType(objT);
 			setObjFontColour(temp);
-			i = wrapSpeechXY(theText, winWidth >> 1, 10, temp -> wrapSpeech, sampleFile);
+			i = wrapSpeechXY(theText, winWidth >> 1, 10, temp->wrapSpeech, sampleFile);
 		}
 	}
 	return i;
@@ -189,87 +189,89 @@ int wrapSpeech(char *theText, int objT, int sampleFile, bool animPerson) {
 
 void viewSpeech() {
 #if 0
-	int viewY = speech -> speechY;
-	speechLine *viewLine = speech -> allSpeech;
-	fixFont(speech -> talkCol);
+	int viewY = speech->speechY;
+	speechLine *viewLine = speech->allSpeech;
+	fixFont(speech->talkCol);
 	while (viewLine) {
-		pasteString(viewLine -> textLine, viewLine -> x, viewY, speech -> talkCol);
+		pasteString(viewLine->textLine, viewLine->x, viewY, speech->talkCol);
 		viewY -= fontHeight / cameraZoom;
-		viewLine = viewLine -> next;
+		viewLine = viewLine->next;
 	}
 #endif
 }
 
-#if ALLOW_FILE
-void saveSpeech(speechStruct *sS, FILE *fp) {
-	speechLine *viewLine = sS -> allSpeech;
+void saveSpeech(speechStruct *sS, Common::WriteStream *stream) {
+#if 0
+	speechLine *viewLine = sS->allSpeech;
 
-	fputc(sS -> talkCol.originalRed, fp);
-	fputc(sS -> talkCol.originalGreen, fp);
-	fputc(sS -> talkCol.originalBlue, fp);
+	putch(sS->talkCol.originalRed, stream);
+	putch(sS->talkCol.originalGreen, stream);
+	putch(sS->talkCol.originalBlue, stream);
 
-	putFloat(speechSpeed, fp);
+	putFloat(speechSpeed, stream);
 
 	// Write y co-ordinate
-	put2bytes(sS -> speechY, fp);
+	put2bytes(sS->speechY, stream);
 
 	// Write which character's talking
-	put2bytes(sS -> lookWhosTalking, fp);
-	if (sS -> currentTalker) {
-		fputc(1, fp);
-		put2bytes(sS -> currentTalker -> thisType -> objectNum, fp);
+	put2bytes(sS->lookWhosTalking, stream);
+	if (sS->currentTalker) {
+		putch(1, stream);
+		put2bytes(sS->currentTalker->thisType->objectNum, stream);
 	} else {
-		fputc(0, fp);
+		putch(0, stream);
 	}
 
 	// Write what's being said
 	while (viewLine) {
-		fputc(1, fp);
-		writeString(viewLine -> textLine, fp);
-		put2bytes(viewLine -> x, fp);
-		viewLine = viewLine -> next;
+		putch(1, stream);
+		writeString(viewLine->textLine, stream);
+		put2bytes(viewLine->x, stream);
+		viewLine = viewLine->next;
 	}
-	fputc(0, fp);
+	putch(0, stream);
+#endif
 }
 
-bool loadSpeech(speechStruct *sS, FILE *fp) {
-	speech -> currentTalker = NULL;
+bool loadSpeech(speechStruct *sS, Common::SeekableReadStream *stream) {
+#if 0
+	speech->currentTalker = NULL;
 	killAllSpeech();
-	byte r = fgetc(fp);
-	byte g = fgetc(fp);
-	byte b = fgetc(fp);
-	setFontColour(sS -> talkCol, r, g, b);
+	byte r = getch(stream);
+	byte g = getch(stream);
+	byte b = getch(stream);
+	setFontColour(sS->talkCol, r, g, b);
 
-	speechSpeed = getFloat(fp);
+	speechSpeed = getFloat(stream);
 
 	// Read y co-ordinate
-	sS -> speechY = get2bytes(fp);
+	sS->speechY = get2bytes(stream);
 
 	// Read which character's talking
-	sS -> lookWhosTalking = get2bytes(fp);
+	sS->lookWhosTalking = get2bytes(stream);
 
-	if (fgetc(fp)) {
-		sS -> currentTalker = findPerson(get2bytes(fp));
+	if (getch(stream)) {
+		sS->currentTalker = findPerson(get2bytes(stream));
 	} else {
-		sS -> currentTalker = NULL;
+		sS->currentTalker = NULL;
 	}
 
 	// Read what's being said
-	speechLine * * viewLine = & sS -> allSpeech;
+	speechLine * * viewLine = &sS->allSpeech;
 	speechLine *newOne;
-	speech -> lastFile = -1;
-	while (fgetc(fp)) {
+	speech->lastFile = -1;
+	while (getch(stream)) {
 		newOne = new speechLine;
 		if (! checkNew(newOne)) return false;
-		newOne -> textLine = readString(fp);
-		newOne -> x = get2bytes(fp);
-		newOne -> next = NULL;
+		newOne->textLine = readString(stream);
+		newOne->x = get2bytes(stream);
+		newOne->next = NULL;
 		(* viewLine) = newOne;
-		viewLine = & (newOne -> next);
+		viewLine = &(newOne->next);
 	}
 
 	return true;
-}
 #endif
+}
 
 } // End of namespace Sludge
diff --git a/engines/sludge/talk.h b/engines/sludge/talk.h
index a0fb1a9..2ce4c4a 100644
--- a/engines/sludge/talk.h
+++ b/engines/sludge/talk.h
@@ -47,10 +47,8 @@ void viewSpeech();
 void killAllSpeech();
 int isThereAnySpeechGoingOn();
 void initSpeech();
-#if ALLOW_FILE
-void saveSpeech(speechStruct *sS, FILE *fp);
-bool loadSpeech(speechStruct *sS, FILE *fp);
-#endif
+void saveSpeech(speechStruct *sS, Common::WriteStream *stream);
+bool loadSpeech(speechStruct *sS, Common::SeekableReadStream *stream);
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/thumbnail.cpp b/engines/sludge/thumbnail.cpp
index 9cb471f..c24946a 100644
--- a/engines/sludge/thumbnail.cpp
+++ b/engines/sludge/thumbnail.cpp
@@ -40,8 +40,9 @@ int thumbWidth = 0, thumbHeight = 0;
 extern GLuint backdropTextureName;
 #endif
 
-#if ALLOW_FILE
-bool saveThumbnail(FILE *fp) {
+
+bool saveThumbnail(Common::WriteStream *stream) {
+#if 0
 	GLuint thumbnailTextureName = 0;
 
 	put4bytes(thumbWidth, fp);
@@ -136,8 +137,8 @@ bool saveThumbnail(FILE *fp) {
 	}
 	fputc('!', fp);
 	return true;
-}
 #endif
+}
 
 void showThumbnail(char *filename, int atX, int atY) {
 #if 0
@@ -254,15 +255,13 @@ void showThumbnail(char *filename, int atX, int atY) {
 #endif
 }
 
-#if ALLOW_FILE
-bool skipThumbnail(FILE *fp) {
-	thumbWidth = get4bytes(fp);
-	thumbHeight = get4bytes(fp);
+bool skipThumbnail(Common::SeekableReadStream *stream) {
+	thumbWidth = get4bytes(stream);
+	thumbHeight = get4bytes(stream);
 	uint32_t skippy = thumbWidth;
 	skippy *= thumbHeight << 1;
-	fseek(fp, skippy, 1);
-	return (fgetc(fp) == '!');
+	stream->seek(skippy, 1);
+	return (getch(stream) == '!');
 }
-#endif
 
 } // End of namespace Sludge
diff --git a/engines/sludge/thumbnail.h b/engines/sludge/thumbnail.h
index 3836478..4452dca 100644
--- a/engines/sludge/thumbnail.h
+++ b/engines/sludge/thumbnail.h
@@ -24,10 +24,8 @@
 
 namespace Sludge {
 
-#if ALLOW_FILE
-bool saveThumbnail(FILE *fp);
-bool skipThumbnail(FILE *fp);
-#endif
+bool saveThumbnail(Common::WriteStream *stream);
+bool skipThumbnail(Common::SeekableReadStream *stream);
 
 void showThumbnail(char *filename, int x, int y);
 
diff --git a/engines/sludge/timing.cpp b/engines/sludge/timing.cpp
index ae4c0cd..887c4ed 100644
--- a/engines/sludge/timing.cpp
+++ b/engines/sludge/timing.cpp
@@ -26,6 +26,8 @@
 namespace Sludge {
 
 int desiredfps = 300;               //holds desired frames per second
+
+#if 0
 Uint32 starttime, endtime;
 Uint32 desired_frame_time;
 
@@ -55,5 +57,6 @@ void Wait_Frame(void) {
 
 	starttime = endtime;
 }
+#endif
 
 } // End of namespace Sludge
diff --git a/engines/sludge/variable.cpp b/engines/sludge/variable.cpp
index 334beb1..928b65b 100644
--- a/engines/sludge/variable.cpp
+++ b/engines/sludge/variable.cpp
@@ -29,6 +29,9 @@
 #include "people.h"
 #include "fileset.h"
 
+#include "sludge.h"
+#include "common/debug.h"
+
 #include <dirent.h>
 #include "moreio.h"
 #ifdef _WIN32
@@ -325,9 +328,8 @@ void makeTextVar(variable &thisVar, const char *txt) {
 }
 
 bool loadStringToVar(variable &thisVar, int value) {
-#if ALLOW_FILE
+
 	makeTextVar(thisVar, getNumberedString(value));
-#endif
 	return (bool)(thisVar.varData.theString != NULL);
 }
 
@@ -536,7 +538,7 @@ bool addVarToStack(const variable &va, variableStack *&thisStack) {
 	if (! copyMain(va, newStack -> thisVar)) return false;
 	newStack -> next = thisStack;
 	thisStack = newStack;
-	//printf("Variable %s was added to stack\n", getTextFromAnyVar(va));
+	debug(kSludgeDebugStackMachine, "Variable %s was added to stack", getTextFromAnyVar(va));
 	return true;
 }
 
@@ -551,7 +553,7 @@ bool addVarToStackQuick(variable &va, variableStack *&thisStack) {
 
 	newStack -> next = thisStack;
 	thisStack = newStack;
-	//printf("Variable %s was added to stack quick\n", getTextFromAnyVar(va));
+	debug(kSludgeDebugStackMachine, "Variable %s was added to stack quick", getTextFromAnyVar(va));
 	return true;
 }
 
@@ -622,7 +624,7 @@ void trimStack(variableStack *&stack) {
 	variableStack *killMe = stack;
 	stack = stack -> next;
 
-	//printf("Variable %s was removed from stack\n", getTextFromAnyVar(killMe -> thisVar));
+	debug(kSludgeDebugStackMachine, "Variable %s was removed from stack", getTextFromAnyVar(killMe -> thisVar));
 
 	// When calling this, we've ALWAYS checked that stack != NULL
 	unlinkVar(killMe -> thisVar);
diff --git a/engines/sludge/vid.cpp b/engines/sludge/vid.cpp
index 266c5bd..13eea52 100644
--- a/engines/sludge/vid.cpp
+++ b/engines/sludge/vid.cpp
@@ -155,7 +155,7 @@ bool extractSlice(int fileNum, char *toName) {
 
 	unsigned long fileLength = openFileFromNum(fileNum);
 	if (! fileLength) return false; // Error already displayed
-
+#if 0
 	FILE *copyVid = fopen(toName, "wb");
 	if (! copyVid) return fatal("Can't extract resource");
 
@@ -170,6 +170,7 @@ bool extractSlice(int fileNum, char *toName) {
 	}
 
 	fclose(copyVid);
+#endif
 	finishAccess();
 
 	return true;
diff --git a/engines/sludge/zbuffer.cpp b/engines/sludge/zbuffer.cpp
index ddcebb1..f73f4f6 100644
--- a/engines/sludge/zbuffer.cpp
+++ b/engines/sludge/zbuffer.cpp
@@ -19,8 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "common/system.h"
-
 #include "allfiles.h"
 #include "zbuffer.h"
 #include "fileset.h"
@@ -66,7 +64,7 @@ void sortZPal(int *oldpal, int *newpal, int size) {
 }
 
 bool setZBuffer(int y) {
-#if ALLOW_FILE
+#if 0
 	int x, n;
 	uint32_t stillToGo = 0;
 	int yPalette[16], sorted[16], sortback[16];


Commit: f8ca5d14c4e6468f2963561e15cc86978cb08fe4
    https://github.com/scummvm/scummvm/commit/f8ca5d14c4e6468f2963561e15cc86978cb08fe4
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Replace stream writing functions id backdrop and formatting

Changed paths:
    engines/sludge/backdrop.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index 929e67d..6b99f0c 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -110,14 +110,14 @@ void saveSnapshot(Common::WriteStream *stream) {
 bool snapshot() {
 
 	nosnapshot();
-	if (! freeze()) return false;
+	if (!freeze()) return false;
 #if 0
 	setPixelCoords(true);
 	glGenTextures(1, &snapshotTextureName);
 
 	int w = winWidth;
 	int h = winHeight;
-	if (! NPOT_textures) {
+	if (!NPOT_textures) {
 		w = getNextPOT(winWidth);
 		h = getNextPOT(winHeight);
 		snapTexW = ((double)winWidth) / w;
@@ -168,14 +168,14 @@ bool restoreSnapshot(Common::SeekableReadStream *stream) {
 	unsigned short c;
 #if 0
 	GLubyte *target;
-	if (! NPOT_textures) {
+	if (!NPOT_textures) {
 		picWidth = getNextPOT(picWidth);
 		picHeight = getNextPOT(picHeight);
 		snapTexW = ((double)winWidth) / picWidth;
 		snapTexH = ((double)winHeight) / picHeight;
 	}
 	GLubyte *snapshotTexture = new GLubyte [picHeight * picWidth * 4];
-	if (! snapshotTexture) return fatal("Out of memory while restoring snapshot.");
+	if (!snapshotTexture) return fatal("Out of memory while restoring snapshot.");
 #endif
 
 	for (t2 = 0; t2 < winHeight; t2 ++) {
@@ -201,7 +201,7 @@ bool restoreSnapshot(Common::SeekableReadStream *stream) {
 		}
 	}
 #if 0
-	if (! snapshotTextureName) glGenTextures(1, &snapshotTextureName);
+	if (!snapshotTextureName) glGenTextures(1, &snapshotTextureName);
 	glBindTexture(GL_TEXTURE_2D, snapshotTextureName);
 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
@@ -241,11 +241,11 @@ void killParallax() {
 	while (parallaxStuff) {
 
 		parallaxLayer *k = parallaxStuff;
-		parallaxStuff = k -> next;
+		parallaxStuff = k->next;
 
 		// Now kill the image
-		deleteTextures(1, &k -> textureName);
-		delete k -> texture;
+		deleteTextures(1, &k->textureName);
+		delete k->texture;
 		delete k;
 		k = NULL;
 	}
@@ -267,16 +267,16 @@ bool reserveBackdrop() {
 	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
 
 	if (backdropTexture) delete backdropTexture;
-	if (! NPOT_textures) {
+	if (!NPOT_textures) {
 		picWidth = getNextPOT(sceneWidth);
 		picHeight = getNextPOT(sceneHeight);
 		backdropTexW = ((double)sceneWidth) / picWidth;
 		backdropTexH = ((double)sceneHeight) / picHeight;
 	}
 	backdropTexture = new GLubyte [picWidth * picHeight * 4];
-	if (! checkNew(backdropTexture)) return false;
+	if (!checkNew(backdropTexture)) return false;
 
-	if (! backdropTextureName) glGenTextures(1, &backdropTextureName);
+	if (!backdropTextureName) glGenTextures(1, &backdropTextureName);
 	glBindTexture(GL_TEXTURE_2D, backdropTextureName);
 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
@@ -306,12 +306,12 @@ bool resizeBackdrop(int x, int y) {
 void loadBackDrop(int fileNum, int x, int y) {
 	setResourceForFatal(fileNum);
 #if 0
-	if (! openFileFromNum(fileNum)) {
+	if (!openFileFromNum(fileNum)) {
 		fatal("Can't load overlay image");
 		return;
 	}
 
-	if (! loadHSI(bigDataFile, x, y, false)) {
+	if (!loadHSI(bigDataFile, x, y, false)) {
 		char mess[200];
 		sprintf(mess, "Can't paste overlay image outside scene dimensions\n\nX = %i\nY = %i\nWidth = %i\nHeight = %i", x, y, sceneWidth, sceneHeight);
 		fatal(mess);
@@ -325,12 +325,12 @@ void loadBackDrop(int fileNum, int x, int y) {
 void mixBackDrop(int fileNum, int x, int y) {
 #if 0
 	setResourceForFatal(fileNum);
-	if (! openFileFromNum(fileNum)) {
+	if (!openFileFromNum(fileNum)) {
 		fatal("Can't load overlay image");
 		return;
 	}
 
-	if (! mixHSI(bigDataFile, x, y)) {
+	if (!mixHSI(bigDataFile, x, y)) {
 		fatal("Can't paste overlay image outside screen dimensions");
 	}
 
@@ -396,7 +396,7 @@ void hardScroll(int distance) {
 		return;
 	}
 
-	if (! distance) return;
+	if (!distance) return;
 #if 0
 	const GLfloat backdropTexCoords[] = {
 		0.0f, 0.0f,
@@ -563,15 +563,15 @@ void drawBackDrop() {
 		while (ps->next) ps = ps->next;
 
 		while (ps) {
-			ps -> cameraX = sortOutPCamera(cameraX, ps -> fractionX, (int)(sceneWidth - (float)winWidth / cameraZoom), (int)(ps -> width - (float)winWidth / cameraZoom));
-			ps -> cameraY = sortOutPCamera(cameraY, ps -> fractionY, (int)(sceneHeight - (float)winHeight / cameraZoom), (int)(ps -> height - (float)winHeight / cameraZoom));
+			ps->cameraX = sortOutPCamera(cameraX, ps->fractionX, (int)(sceneWidth - (float)winWidth / cameraZoom), (int)(ps->width - (float)winWidth / cameraZoom));
+			ps->cameraY = sortOutPCamera(cameraY, ps->fractionY, (int)(sceneHeight - (float)winHeight / cameraZoom), (int)(ps->height - (float)winHeight / cameraZoom));
 			glBindTexture(GL_TEXTURE_2D, ps->textureName);
 
 			float w = (ps->wrapS) ? sceneWidth : ps->width;
 			float h = (ps->wrapT) ? sceneHeight : ps->height;
 			float texw;
 			float texh;
-			if (! NPOT_textures) {
+			if (!NPOT_textures) {
 				texw = (ps->wrapS) ? (float) sceneWidth / ps->width : (float) ps->width / getNextPOT(ps->width);
 				texh = (ps->wrapT) ? (float) sceneHeight / ps->height : (float) ps->height / getNextPOT(ps->height);
 			} else {
@@ -580,10 +580,10 @@ void drawBackDrop() {
 			}
 
 			const GLfloat vertices[] = {
-				(GLfloat) - ps -> cameraX, (GLfloat) - ps -> cameraY, 0.1f,
-				w - ps -> cameraX, (GLfloat) - ps -> cameraY, 0.1f,
-				(GLfloat) - ps -> cameraX, h - ps -> cameraY, 0.1f,
-				w - ps -> cameraX, h - ps -> cameraY, 0.1f
+				(GLfloat) - ps->cameraX, (GLfloat) - ps->cameraY, 0.1f,
+				w - ps->cameraX, (GLfloat) - ps->cameraY, 0.1f,
+				(GLfloat) - ps->cameraX, h - ps->cameraY, 0.1f,
+				w - ps->cameraX, h - ps->cameraY, 0.1f
 			};
 
 			const GLfloat texCoords[] = {
@@ -594,7 +594,7 @@ void drawBackDrop() {
 			};
 			drawQuad(shader.smartScaler, vertices, 1, texCoords);
 
-			ps = ps -> prev;
+			ps = ps->prev;
 		}
 	}
 
@@ -626,7 +626,7 @@ bool loadLightMap(int v) {
 	int newPicWidth, newPicHeight;
 #if 0
 	setResourceForFatal(v);
-	if (! openFileFromNum(v)) return fatal("Can't open light map.");
+	if (!openFileFromNum(v)) return fatal("Can't open light map.");
 	long file_pointer = ftell(bigDataFile);
 
 	png_structp png_ptr;
@@ -701,7 +701,7 @@ bool loadLightMap(int v) {
 		}
 	}
 
-	if (! NPOT_textures) {
+	if (!NPOT_textures) {
 		newPicWidth = getNextPOT(lightMap.w);
 		newPicHeight = getNextPOT(lightMap.h);
 		lightMap.texW = (double) lightMap.w / newPicWidth;
@@ -719,7 +719,7 @@ bool loadLightMap(int v) {
 	if (lightMap.data) delete [] lightMap.data;
 
 	lightMap.data = new GLubyte [newPicWidth * newPicHeight * 4];
-	if (! lightMap.data) {
+	if (!lightMap.data) {
 		return fatal("Out of memory loading light map.");
 	}
 
@@ -759,7 +759,7 @@ bool loadLightMap(int v) {
 		}
 	}
 #if 0
-	if (! lightMap.name) glGenTextures(1, &lightMap.name);
+	if (!lightMap.name) glGenTextures(1, &lightMap.name);
 	glBindTexture(GL_TEXTURE_2D, lightMap.name);
 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
@@ -779,7 +779,7 @@ bool loadLightMap(int v) {
 void reloadParallaxTextures() {
 #if 0
 	parallaxLayer *nP = parallaxStuff;
-	if (! nP) return;
+	if (!nP) return;
 
 	while (nP) {
 		//fprintf (stderr, "Reloading parallax. (%d, %d) ", nP->width, nP->height);
@@ -787,11 +787,11 @@ void reloadParallaxTextures() {
 
 		glGenTextures(1, &nP->textureName);
 		glBindTexture(GL_TEXTURE_2D, nP->textureName);
-		if (nP -> wrapS)
+		if (nP->wrapS)
 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
 		else
 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
-		if (nP -> wrapT)
+		if (nP->wrapT)
 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
 		else
 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
@@ -804,7 +804,7 @@ void reloadParallaxTextures() {
 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 		}
 
-		if (! NPOT_textures) {
+		if (!NPOT_textures) {
 			texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, getNextPOT(nP->width), getNextPOT(nP->height), 0, GL_RGBA, GL_UNSIGNED_BYTE, nP->texture, nP->textureName);
 		} else {
 			texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, nP->width, nP->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nP->texture, nP->textureName);
@@ -819,17 +819,17 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 
 #if 0
 	setResourceForFatal(v);
-	if (! openFileFromNum(v)) return fatal("Can't open parallax image");
+	if (!openFileFromNum(v)) return fatal("Can't open parallax image");
 
 	parallaxLayer *nP = new parallaxLayer;
-	if (! checkNew(nP)) return false;
+	if (!checkNew(nP)) return false;
 
-	nP -> next = parallaxStuff;
+	nP->next = parallaxStuff;
 	parallaxStuff = nP;
-	if (nP -> next) {
-		nP -> next -> prev = nP;
+	if (nP->next) {
+		nP->next->prev = nP;
 	}
-	nP -> prev = NULL;
+	nP->prev = NULL;
 
 	int picWidth;
 	int picHeight;
@@ -854,8 +854,8 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 		fileIsPNG = false;
 		fseek(bigDataFile, file_pointer, SEEK_SET);
 
-		picWidth = nP -> width = get2bytes(bigDataFile);
-		picHeight = nP -> height = get2bytes(bigDataFile);
+		picWidth = nP->width = get2bytes(bigDataFile);
+		picHeight = nP->height = get2bytes(bigDataFile);
 	} else {
 		// Read the PNG header
 
@@ -884,8 +884,8 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 		int bit_depth, color_type, interlace_type, compression_type, filter_method;
 		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
 
-		picWidth = nP -> width = width;
-		picHeight = nP -> height = height;
+		picWidth = nP->width = width;
+		picHeight = nP->height = height;
 
 		if (bit_depth < 8) png_set_packing(png_ptr);
 		png_set_expand(png_ptr);
@@ -901,42 +901,42 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 
 	}
 
-	if (! NPOT_textures) {
+	if (!NPOT_textures) {
 		picWidth = getNextPOT(picWidth);
 		picHeight = getNextPOT(picHeight);
 	}
 
-	nP -> fileNum = v;
-	nP -> fractionX = fracX;
-	nP -> fractionY = fracY;
+	nP->fileNum = v;
+	nP->fractionX = fracX;
+	nP->fractionY = fracY;
 
 	if (fracX == 65535) {
-		nP -> wrapS = false;
-		if (nP -> width < winWidth) {
+		nP->wrapS = false;
+		if (nP->width < winWidth) {
 			fatal("For AUTOFIT parallax backgrounds, the image must be at least as wide as the game window/screen.");
 			return false;
 		}
 	} else {
-		nP -> wrapS = true;
+		nP->wrapS = true;
 	}
 
 	if (fracY == 65535) {
-		nP -> wrapT = false;
-		if (nP -> height < winHeight) {
+		nP->wrapT = false;
+		if (nP->height < winHeight) {
 			fatal("For AUTOFIT parallax backgrounds, the image must be at least as tall as the game window/screen.");
 			return false;
 		}
 	} else {
-		nP -> wrapT = true;
+		nP->wrapT = true;
 	}
 
-	nP -> texture = new GLubyte [picHeight * picWidth * 4];
-	if (! checkNew(nP -> texture)) return false;
+	nP->texture = new GLubyte [picHeight * picWidth * 4];
+	if (!checkNew(nP->texture)) return false;
 
 	if (fileIsPNG) {
-		unsigned char *row_pointers[nP -> height];
-		for (int i = 0; i < nP -> height; i++)
-			row_pointers[i] = nP -> texture + 4 * i * picWidth;
+		unsigned char *row_pointers[nP->height];
+		for (int i = 0; i < nP->height; i++)
+			row_pointers[i] = nP->texture + 4 * i * picWidth;
 
 		png_read_image(png_ptr, (png_byte **) row_pointers);
 		png_read_end(png_ptr, NULL);
@@ -947,9 +947,9 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 		unsigned short c;
 		GLubyte *target;
 
-		for (t2 = 0; t2 < nP -> height; t2 ++) {
+		for (t2 = 0; t2 < nP->height; t2 ++) {
 			t1 = 0;
-			while (t1 < nP -> width) {
+			while (t1 < nP->width) {
 				c = (unsigned short) get2bytes(bigDataFile);
 				if (c & 32) {
 					n = fgetc(bigDataFile) + 1;
@@ -958,7 +958,7 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 					n = 1;
 				}
 				while (n--) {
-					target = nP -> texture + 4 * picWidth * t2 + t1 * 4;
+					target = nP->texture + 4 * picWidth * t2 + t1 * 4;
 					if (c == 63519 || c == 2015) {
 						target[0] = (GLubyte) 0;
 						target[1] = (GLubyte) 0;
@@ -978,11 +978,11 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 
 	glGenTextures(1, &nP->textureName);
 	glBindTexture(GL_TEXTURE_2D, nP->textureName);
-	if (nP -> wrapS)
+	if (nP->wrapS)
 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
 	else
 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
-	if (nP -> wrapT)
+	if (nP->wrapT)
 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
 	else
 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
@@ -1005,9 +1005,9 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 
 extern int viewportOffsetX, viewportOffsetY;
 
-#if 0
-bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 
+bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
+#if 0
 	int t1, t2, n;
 	unsigned short c;
 	GLubyte *target;
@@ -1039,7 +1039,6 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 		picHeight = realPicHeight = get2bytes(stream);
 	} else {
 		// Read the PNG header
-#if 0
 		png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
 		if (!png_ptr) {
 			return false;
@@ -1079,13 +1078,11 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
 
 		//int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
-#endif
 	}
 
-#if 0
 	GLfloat texCoordW = 1.0;
 	GLfloat texCoordH = 1.0;
-	if (! NPOT_textures) {
+	if (!NPOT_textures) {
 		picWidth = getNextPOT(picWidth);
 		picHeight = getNextPOT(picHeight);
 		texCoordW = ((double)realPicWidth) / picWidth;
@@ -1093,7 +1090,7 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 	}
 
 	if (reserve) {
-		if (! resizeBackdrop(realPicWidth, realPicHeight)) return false;
+		if (!resizeBackdrop(realPicWidth, realPicHeight)) return false;
 	}
 
 	if (x == IN_THE_CENTRE) x = (sceneWidth - realPicWidth) >> 1;
@@ -1162,7 +1159,7 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 	float btx2;
 	float bty1;
 	float bty2;
-	if (! NPOT_textures) {
+	if (!NPOT_textures) {
 		btx1 = backdropTexW * x / sceneWidth;
 		btx2 = backdropTexW * (x + realPicWidth) / sceneWidth;
 		bty1 = backdropTexH * y / sceneHeight;
@@ -1259,12 +1256,13 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 	deleteTextures(1, &tmpTex);
 
 	setPixelCoords(false);
-#endif
 	backdropExists = true;
+#endif
 	return true;
 }
 
 bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
+#if 0
 	int realPicWidth, realPicHeight;
 	int picWidth;
 	int picHeight;
@@ -1283,7 +1281,6 @@ bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 	if (bytes_read != 8 && stream->err()) {
 		debugOut("Reading error in mixHSI.\n");
 	}
-#if 0
 	if (png_sig_cmp((png_byte *) tmp, 0, 8)) {
 		// No, it's old-school HSI
 		fileIsPNG = false;
@@ -1345,7 +1342,7 @@ bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 	float bty1, ty1;
 	float bty2, ty2;
 
-	if (! NPOT_textures) {
+	if (!NPOT_textures) {
 		tx1 = 0.0;
 		ty1 = 0.0;
 		tx2 = ((double)picWidth) / getNextPOT(picWidth);
@@ -1498,9 +1495,8 @@ bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 #endif
 	return true;
 }
-
-void saveCorePNG(Common::WriteStream *stream, GLuint texture, int w, int h) {
 #if 0
+void saveCorePNG(Common::WriteStream *stream, GLuint texture, int w, int h) {
 	GLint tw, th;
 
 	glBindTexture(GL_TEXTURE_2D, texture);
@@ -1508,13 +1504,12 @@ void saveCorePNG(Common::WriteStream *stream, GLuint texture, int w, int h) {
 	getTextureDimensions(texture, &tw, &th);
 
 	GLubyte *image = new GLubyte [tw * th * 4];
-	if (! checkNew(image)) return;
+	if (!checkNew(image)) return;
 
 	glPixelStorei(GL_PACK_ALIGNMENT, 1);
 //	glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
-#endif
+
 #ifdef HAVE_GLES2
-#if 0
 	GLuint old_fbo, new_fbo;
 	GLint old_vp[4];
 	glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint *)&old_fbo);
@@ -1527,13 +1522,8 @@ void saveCorePNG(Common::WriteStream *stream, GLuint texture, int w, int h) {
 	glBindFramebuffer(GL_FRAMEBUFFER, old_fbo);
 	glViewport(old_vp[0], old_vp[1], old_vp[2], old_vp[3]);
 	glDeleteFramebuffers(1, &new_fbo);
-#endif
 #else
 	setPixelCoords(true);
-
-
-	//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
-
 	const GLfloat texCoords[] = {
 		0.0f, 0.0f,
 		1.0f, 0.0f,
@@ -1548,9 +1538,8 @@ void saveCorePNG(Common::WriteStream *stream, GLuint texture, int w, int h) {
 		int yoffset = 0;
 		while (yoffset < th) {
 			int h = (th - yoffset < viewportHeight) ? th - yoffset : viewportHeight;
-#if 0
+
 			glClear(GL_COLOR_BUFFER_BIT);   // Clear The Screen
-#endif
 			const GLfloat vertices[] = {
 				(GLfloat) - xoffset, (GLfloat) - yoffset, 0.,
 				(GLfloat)tw - xoffset, (GLfloat) - yoffset, 0.,
@@ -1558,7 +1547,6 @@ void saveCorePNG(Common::WriteStream *stream, GLuint texture, int w, int h) {
 				(GLfloat)tw - xoffset, (GLfloat) - yoffset + th, 0.
 			};
 
-#if 0
 			glUseProgram(shader.texture);
 
 			setPMVMatrix(shader.texture);
@@ -1570,16 +1558,12 @@ void saveCorePNG(Common::WriteStream *stream, GLuint texture, int w, int h) {
 			for (int i = 0; i < h; i++)   {
 				glReadPixels(viewportOffsetX, viewportOffsetY + i, w, 1, GL_RGBA, GL_UNSIGNED_BYTE, image + xoffset * 4 + (yoffset + i) * 4 * tw);
 			}
-#endif
 			yoffset += viewportHeight;
 		}
 
 		xoffset += viewportWidth;
 	}
 	setPixelCoords(false);
-#endif
-
-
 
 	png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
 	if (!png_ptr) {
@@ -1610,22 +1594,20 @@ void saveCorePNG(Common::WriteStream *stream, GLuint texture, int w, int h) {
 
 	delete [] image;
 	image = NULL;
+#endif
 }
+#endif
 
-void saveCoreHSI(FILE *writer, GLuint texture, int w, int h) {
-
-	GLint tw, th;
 #if 0
+void saveCoreHSI(Common::WriteStream *stream, GLuint texture, int w, int h) {
+	GLint tw, th;
 	glBindTexture(GL_TEXTURE_2D, texture);
-#endif
 	getTextureDimensions(texture, &tw, &th);
 
 	GLushort *image = new GLushort [tw * th];
-	if (! checkNew(image)) return;
-#if 0
+	if (!checkNew(image)) return;
 	glPixelStorei(GL_PACK_ALIGNMENT, 1);
 //	glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, image);
-#endif
 	setPixelCoords(true);
 
 	//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
@@ -1644,9 +1626,7 @@ void saveCoreHSI(FILE *writer, GLuint texture, int w, int h) {
 		int yoffset = 0;
 		while (yoffset < th) {
 			int h = (th - yoffset < viewportHeight) ? th - yoffset : viewportHeight;
-#if 0
 			glClear(GL_COLOR_BUFFER_BIT);   // Clear The Screen
-#endif
 			const GLfloat vertices[] = {
 				(GLfloat) - xoffset, (GLfloat) - yoffset, 0.,
 				(GLfloat)w - xoffset, (GLfloat) - yoffset, 0.,
@@ -1654,34 +1634,27 @@ void saveCoreHSI(FILE *writer, GLuint texture, int w, int h) {
 				(GLfloat)w - xoffset, (GLfloat) - yoffset + h, 0.
 			};
 
-#if 0
 			glUseProgram(shader.texture);
-#endif
 			setPMVMatrix(shader.texture);
 			drawQuad(shader.texture, vertices, 1, texCoords);
-#if 0
 			glUseProgram(0);
 
 			for (int i = 0; i < h; i++)   {
 				glReadPixels(viewportOffsetX, viewportOffsetY + i, w, 1, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, image + xoffset + (yoffset + i)*tw);
 			}
-#endif
 			yoffset += viewportHeight;
 		}
 
 		xoffset += viewportWidth;
 	}
 	//glReadPixels(viewportOffsetX, viewportOffsetY, tw, th, GL_RGBA, GL_UNSIGNED_BYTE, data);
-
 	setPixelCoords(false);
 
-
-
 	int x, y, lookAhead;
 	unsigned short int *fromHere, * lookPointer;
 
-	put2bytes(w, writer);
-	put2bytes(h, writer);
+	put2bytes(w, stream);
+	put2bytes(h, stream);
 
 	for (y = 0; y < h; y ++) {
 		fromHere = image + (y * tw);
@@ -1694,10 +1667,10 @@ void saveCoreHSI(FILE *writer, GLuint texture, int w, int h) {
 				lookPointer ++;
 			}
 			if (lookAhead == x + 1) {
-				put2bytes((* fromHere) & 65503, writer);
+				put2bytes((* fromHere) & 65503, stream);
 			} else {
-				put2bytes(* fromHere | 32, writer);
-				fputc(lookAhead - x - 1, writer);
+				put2bytes(* fromHere | 32, stream);
+				putch(lookAhead - x - 1, stream);
 			}
 			fromHere = lookPointer;
 			x = lookAhead;
@@ -1706,22 +1679,23 @@ void saveCoreHSI(FILE *writer, GLuint texture, int w, int h) {
 	delete [] image;
 	image = NULL;
 }
+#endif
 
-void saveHSI(FILE *writer) {
-	saveCorePNG(writer, backdropTextureName, sceneWidth, sceneHeight);
+#if 0
+void saveHSI(Common::WriteStream *stream) {
+	saveCorePNG(stream, backdropTextureName, sceneWidth, sceneHeight);
 }
+#endif
 
-
-void saveParallaxRecursive(parallaxLayer *me, FILE *fp) {
+void saveParallaxRecursive(parallaxLayer *me, Common::WriteStream *stream) {
 	if (me) {
-		saveParallaxRecursive(me -> next, fp);
-		fputc(1, fp);
-		put2bytes(me->fileNum, fp);
-		put2bytes(me ->fractionX, fp);
-		put2bytes(me->fractionY, fp);
+		saveParallaxRecursive(me->next, stream);
+		putch(1, stream);
+		put2bytes(me->fileNum, stream);
+		put2bytes(me ->fractionX, stream);
+		put2bytes(me->fractionY, stream);
 	}
 }
-#endif
 
 bool getRGBIntoStack(unsigned int x, unsigned int y, stackHandler *sH) {
 #if 0
@@ -1736,21 +1710,21 @@ bool getRGBIntoStack(unsigned int x, unsigned int y, stackHandler *sH) {
 	saveTexture(backdropTextureName, backdropTexture);
 
 	GLubyte *target;
-	if (! NPOT_textures) {
+	if (!NPOT_textures) {
 		target = backdropTexture + 4 * getNextPOT(sceneWidth) * y + x * 4;
 	} else {
 		target = backdropTexture + 4 * sceneWidth * y + x * 4;
 	}
 
 	setVariable(newValue, SVT_INT, target[2]);
-	if (! addVarToStackQuick(newValue, sH -> first)) return false;
-	sH -> last = sH -> first;
+	if (!addVarToStackQuick(newValue, sH->first)) return false;
+	sH->last = sH->first;
 
 	setVariable(newValue, SVT_INT, target[1]);
-	if (! addVarToStackQuick(newValue, sH -> first)) return false;
+	if (!addVarToStackQuick(newValue, sH->first)) return false;
 
 	setVariable(newValue, SVT_INT, target[0]);
-	if (! addVarToStackQuick(newValue, sH -> first)) return false;
+	if (!addVarToStackQuick(newValue, sH->first)) return false;
 #endif
 	return true;
 }


Commit: 9f7d301ef4b48469ad1679e479f8597d1b3e97e1
    https://github.com/scummvm/scummvm/commit/9f7d301ef4b48469ad1679e479f8597d1b3e97e1
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Refactor background loading code

Changed paths:
    engines/sludge/backdrop.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index 6b99f0c..b5c3885 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -1005,24 +1005,19 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 
 extern int viewportOffsetX, viewportOffsetY;
 
-
-bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 #if 0
+bool loadImage(GLubyte *loadhere, int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, int x, int y, bool reserve) {
+
 	int t1, t2, n;
 	unsigned short c;
 	GLubyte *target;
 	int32_t transCol = reserve ? -1 : 63519;
-	int picWidth;
-	int picHeight;
-	int realPicWidth, realPicHeight;
 	long file_pointer = stream->pos();
-
 	png_structp png_ptr;
 	png_infop info_ptr, end_info;
 
 
 	int fileIsPNG = true;
-
 	// Is this a PNG file?
 
 	char tmp[10];
@@ -1076,21 +1071,10 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 
 		png_read_update_info(png_ptr, info_ptr);
 		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
-
-		//int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
-	}
-
-	GLfloat texCoordW = 1.0;
-	GLfloat texCoordH = 1.0;
-	if (!NPOT_textures) {
-		picWidth = getNextPOT(picWidth);
-		picHeight = getNextPOT(picHeight);
-		texCoordW = ((double)realPicWidth) / picWidth;
-		texCoordH = ((double)realPicHeight) / picHeight;
 	}
 
 	if (reserve) {
-		if (!resizeBackdrop(realPicWidth, realPicHeight)) return false;
+		if (! resizeBackdrop(realPicWidth, realPicHeight)) return false;
 	}
 
 	if (x == IN_THE_CENTRE) x = (sceneWidth - realPicWidth) >> 1;
@@ -1102,7 +1086,7 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 		for (int i = 0; i < realPicHeight; i++)
 			row_pointers[i] = backdropTexture + 4 * i * picWidth;
 
-		png_read_image(png_ptr, (png_byte **) row_pointers);
+		png_read_image(png_ptr, (png_byte **)row_pointers);
 		png_read_end(png_ptr, NULL);
 		png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
 	} else {
@@ -1116,7 +1100,7 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 				} else {
 					n = 1;
 				}
-				while (n --) {
+				while (--n) {
 					target = backdropTexture + 4 * picWidth * t2 + t1 * 4;
 					if (c == transCol || c == 2015) {
 						target[0] = (GLubyte) 0;
@@ -1134,9 +1118,10 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 			}
 		}
 	}
+	return true;
+}
 
-	GLuint tmpTex;
-
+void makeGlArray(GLuint &tmpTex, const GLubyte *texture, int picWidth, int picHeight) {
 	glGenTextures(1, &tmpTex);
 	glBindTexture(GL_TEXTURE_2D, tmpTex);
 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
@@ -1148,18 +1133,25 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 	}
+	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture, tmpTex);
 
-	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, backdropTexture, tmpTex);
-
-
-	//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+}
 
+void renderToTexture(GLuint tmpTex, int x, int y, int picWidth, int picHeight, int realPicWidth, int realPicHeight) {
+	GLfloat texCoordW = 1.0;
+	GLfloat texCoordH = 1.0;
+	if (! NPOT_textures) {
+		picWidth = getNextPOT(picWidth);
+		picHeight = getNextPOT(picHeight);
+		texCoordW = ((double)realPicWidth) / picWidth;
+		texCoordH = ((double)realPicHeight) / picHeight;
+	}
 
 	float btx1;
 	float btx2;
 	float bty1;
 	float bty2;
-	if (!NPOT_textures) {
+	if (! NPOT_textures) {
 		btx1 = backdropTexW * x / sceneWidth;
 		btx2 = backdropTexW * (x + realPicWidth) / sceneWidth;
 		bty1 = backdropTexH * y / sceneHeight;
@@ -1205,7 +1197,6 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 			};
 
 			if (backdropExists) {
-
 				// Render the sprite to the backdrop
 				// (using mulitexturing, so the old backdrop is seen where alpha < 1.0)
 				glActiveTexture(GL_TEXTURE2);
@@ -1215,10 +1206,10 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 				glUseProgram(shader.paste);
 				GLint uniform = glGetUniformLocation(shader.paste, "useLightTexture");
 				if (uniform >= 0) glUniform1i(uniform, 0); // No lighting
+
 				setPMVMatrix(shader.paste);
 
 				setPrimaryColor(1.0, 1.0, 1.0, 1.0);
-
 				glBindTexture(GL_TEXTURE_2D, tmpTex);
 				//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
 
@@ -1228,10 +1219,7 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 
 			} else {
 				// It's all new - nothing special to be done.
-
-
 				glUseProgram(shader.texture);
-
 				setPMVMatrix(shader.texture);
 
 				glBindTexture(GL_TEXTURE_2D, tmpTex);
@@ -1240,9 +1228,7 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 
 				drawQuad(shader.texture, vertices, 1, texCoords);
 
-
 				glUseProgram(0);
-
 			}
 
 			// Copy Our ViewPort To The Texture
@@ -1250,12 +1236,27 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 
 			yoffset += viewportHeight;
 		}
-
 		xoffset += viewportWidth;
 	}
+	setPixelCoords(false);
+}
+#endif
+
+bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
+#if 0
+	int picWidth, picHeight;
+	int realPicWidth, realPicHeight;
+
+	if (!loadImage(backdropTexture, picWidth, picHeight, realPicWidth, realPicHeight, stream, x, y, reserve))
+		return false;
+
+	GLuint tmpTex;
+	makeGlArray(tmpTex, backdropTexture, picWidth, picHeight);
+
+	renderToTexture(tmpTex, x, y, picWidth, picHeight, realPicWidth, realPicHeight);
+
 	deleteTextures(1, &tmpTex);
 
-	setPixelCoords(false);
 	backdropExists = true;
 #endif
 	return true;


Commit: 6808650f3e17f57c2dc2424c813f1f62a04ed03c
    https://github.com/scummvm/scummvm/commit/6808650f3e17f57c2dc2424c813f1f62a04ed03c
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Refactor png specific functions in backdrop

Changed paths:
    engines/sludge/backdrop.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index b5c3885..3e05997 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -1006,118 +1006,128 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 extern int viewportOffsetX, viewportOffsetY;
 
 #if 0
-bool loadImage(GLubyte *loadhere, int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, int x, int y, bool reserve) {
-
-	int t1, t2, n;
-	unsigned short c;
-	GLubyte *target;
-	int32_t transCol = reserve ? -1 : 63519;
+bool loadPng(GLubyte *loadhere, int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, bool reserve) {
 	long file_pointer = stream->pos();
 	png_structp png_ptr;
 	png_infop info_ptr, end_info;
 
-
-	int fileIsPNG = true;
-	// Is this a PNG file?
-
 	char tmp[10];
 	size_t bytes_read = stream->read(tmp, 8);
+
 	if (bytes_read != 8 && stream->err()) {
-		debugOut("Reading error in loadHSI.\n");
+		stream->seek(file_pointer, SEEK_SET);
+		return false;
 	}
+
 	if (png_sig_cmp((png_byte *) tmp, 0, 8)) {
-		// No, it's old-school HSI
-		fileIsPNG = false;
 		stream->seek(file_pointer, SEEK_SET);
+		return false;
+	}
 
-		picWidth = realPicWidth = get2bytes(stream);
-		picHeight = realPicHeight = get2bytes(stream);
-	} else {
-		// Read the PNG header
-		png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
-		if (!png_ptr) {
-			return false;
-		}
+	png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+	if (!png_ptr) {
+		return false;
+	}
 
-		info_ptr = png_create_info_struct(png_ptr);
-		if (!info_ptr) {
-			png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
-			return false;
-		}
+	info_ptr = png_create_info_struct(png_ptr);
+	if (!info_ptr) {
+		png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
+		return false;
+	}
 
-		end_info = png_create_info_struct(png_ptr);
-		if (!end_info) {
-			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
-			return false;
-		}
-		png_init_io(png_ptr, fp);       // Tell libpng which file to read
-		png_set_sig_bytes(png_ptr, 8);  // 8 bytes already read
+	end_info = png_create_info_struct(png_ptr);
+	if (!end_info) {
+		png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
+		return false;
+	}
+	png_init_io(png_ptr, stream);		// Tell libpng which file to read
+	png_set_sig_bytes(png_ptr, 8);	// 8 bytes already read
 
-		png_read_info(png_ptr, info_ptr);
+	png_read_info(png_ptr, info_ptr);
 
-		png_uint_32 width, height;
-		int bit_depth, color_type, interlace_type, compression_type, filter_method;
-		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
+	png_uint_32 width, height;
+	int bit_depth, color_type, interlace_type, compression_type, filter_method;
+	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
 
-		picWidth = realPicWidth = width;
-		picHeight = realPicHeight = height;
+	picWidth = realPicWidth = width;
+	picHeight = realPicHeight = height;
 
-		if (bit_depth < 8) png_set_packing(png_ptr);
-		png_set_expand(png_ptr);
-		if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr);
-		if (bit_depth == 16) png_set_strip_16(png_ptr);
+	if (bit_depth < 8) png_set_packing(png_ptr);
+	png_set_expand(png_ptr);
+	if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr);
+	if (bit_depth == 16) png_set_strip_16(png_ptr);
 
-		png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER);
+	png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER);
 
-		png_read_update_info(png_ptr, info_ptr);
-		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
-	}
+	png_read_update_info(png_ptr, info_ptr);
+	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
 
 	if (reserve) {
-		if (! resizeBackdrop(realPicWidth, realPicHeight)) return false;
+		if (!resizeBackdrop(realPicWidth, realPicHeight)) return false;
 	}
 
-	if (x == IN_THE_CENTRE) x = (sceneWidth - realPicWidth) >> 1;
-	if (y == IN_THE_CENTRE) y = (sceneHeight - realPicHeight) >> 1;
-	if (x < 0 || x + realPicWidth > sceneWidth || y < 0 || y + realPicHeight > sceneHeight) return false;
+	unsigned char *row_pointers[realPicHeight];
 
-	if (fileIsPNG) {
-		unsigned char *row_pointers[realPicHeight];
-		for (int i = 0; i < realPicHeight; i++)
-			row_pointers[i] = backdropTexture + 4 * i * picWidth;
+	for (int i = 0; i < realPicHeight; i++)
+		row_pointers[i] = loadhere + 4 * i * picWidth;
 
-		png_read_image(png_ptr, (png_byte **)row_pointers);
-		png_read_end(png_ptr, NULL);
-		png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
-	} else {
-		for (t2 = 0; t2 < realPicHeight; t2 ++) {
-			t1 = 0;
-			while (t1 < realPicWidth) {
-				c = (unsigned short) get2bytes(fp);
-				if (c & 32) {
-					n = fgetc(fp) + 1;
-					c -= 32;
+	png_read_image(png_ptr, (png_byte **) row_pointers);
+	png_read_end(png_ptr, NULL);
+	png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
+}
+
+bool loadByteArray(GLubyte *loadhere, int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, bool reserve) {
+	int32_t transCol = reserve ? -1 : 63519;
+	int t1, t2, n;
+	unsigned short c;
+	picWidth = realPicWidth = get2bytes(stream);
+	picHeight = realPicHeight = get2bytes(stream);
+
+	if (reserve) {
+		if (!resizeBackdrop(realPicWidth, realPicHeight)) return false;
+	}
+
+	for (t2 = 0; t2 < realPicHeight; t2 ++) {
+		t1 = 0;
+		while (t1 < realPicWidth) {
+			c = (unsigned short) get2bytes(stream);
+			if (c & 32) {
+				n = getch(stream) + 1;
+				c -= 32;
+			} else {
+				n = 1;
+			}
+			while (n --) {
+				GLubyte *target = loadhere + 4 * picWidth * t2 + t1 * 4;
+				if (c == transCol || c == 2015) {
+					target[0] = (GLubyte)0;
+					target[1] = (GLubyte)0;
+					target[2] = (GLubyte)0;
+					target[3] = (GLubyte)0;
 				} else {
-					n = 1;
-				}
-				while (--n) {
-					target = backdropTexture + 4 * picWidth * t2 + t1 * 4;
-					if (c == transCol || c == 2015) {
-						target[0] = (GLubyte) 0;
-						target[1] = (GLubyte) 0;
-						target[2] = (GLubyte) 0;
-						target[3] = (GLubyte) 0;
-					} else {
-						target[0] = (GLubyte) redValue(c);
-						target[1] = (GLubyte) greenValue(c);
-						target[2] = (GLubyte) blueValue(c);
-						target[3] = (GLubyte) 255;
-					}
-					t1++;
+					target[0] = (GLubyte)redValue(c);
+					target[1] = (GLubyte)greenValue(c);
+					target[2] = (GLubyte)blueValue(c);
+					target[3] = (GLubyte)255;
 				}
+				t1++;
 			}
 		}
 	}
+}
+
+bool loadImage(GLubyte *loadhere, int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, int x, int y, bool reserve) {
+
+	if (!loadPng(loadhere, picWidth, picHeight, realPicWidth, realPicHeight, stream, reserve)) {
+		if (!loadByteArray(loadhere, picWidth, picHeight, realPicWidth, realPicHeight, stream, reserve)) {
+			return false;
+		}
+	}
+
+	if (x == IN_THE_CENTRE) x = (sceneWidth - realPicWidth) >> 1;
+	if (y == IN_THE_CENTRE) y = (sceneHeight - realPicHeight) >> 1;
+	if (x < 0 || x + realPicWidth > sceneWidth || y < 0 || y + realPicHeight > sceneHeight) return false;
+
 	return true;
 }
 
@@ -1140,7 +1150,7 @@ void makeGlArray(GLuint &tmpTex, const GLubyte *texture, int picWidth, int picHe
 void renderToTexture(GLuint tmpTex, int x, int y, int picWidth, int picHeight, int realPicWidth, int realPicHeight) {
 	GLfloat texCoordW = 1.0;
 	GLfloat texCoordH = 1.0;
-	if (! NPOT_textures) {
+	if (!NPOT_textures) {
 		picWidth = getNextPOT(picWidth);
 		picHeight = getNextPOT(picHeight);
 		texCoordW = ((double)realPicWidth) / picWidth;
@@ -1151,7 +1161,7 @@ void renderToTexture(GLuint tmpTex, int x, int y, int picWidth, int picHeight, i
 	float btx2;
 	float bty1;
 	float bty2;
-	if (! NPOT_textures) {
+	if (!NPOT_textures) {
 		btx1 = backdropTexW * x / sceneWidth;
 		btx2 = backdropTexW * (x + realPicWidth) / sceneWidth;
 		bty1 = backdropTexH * y / sceneHeight;


Commit: 2dddb900c9b6d4356a19886cd31587a049be23d8
    https://github.com/scummvm/scummvm/commit/2dddb900c9b6d4356a19886cd31587a049be23d8
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Use PNGDecoder to read backdrop

Changed paths:
    engines/sludge/backdrop.cpp
    engines/sludge/detection.cpp
    engines/sludge/main_loop.cpp
    engines/sludge/sludge.cpp
    engines/sludge/sludge.h


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index 3e05997..c28a7d0 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -55,6 +55,10 @@
 #include "statusba.h"
 #include "variable.h"
 #include "CommonCode/version.h"
+#include "common/debug.h"
+#include "image/png.h"
+#include "graphics/surface.h"
+#include "sludge.h"
 
 namespace Sludge {
 
@@ -75,6 +79,8 @@ texture lightMap;
 GLuint snapshotTextureName = 0;
 #endif
 
+Graphics::Surface backdropSurface;
+
 float snapTexW = 1.0;
 float snapTexH = 1.0;
 
@@ -110,7 +116,8 @@ void saveSnapshot(Common::WriteStream *stream) {
 bool snapshot() {
 
 	nosnapshot();
-	if (!freeze()) return false;
+	if (!freeze())
+		return false;
 #if 0
 	setPixelCoords(true);
 	glGenTextures(1, &snapshotTextureName);
@@ -134,19 +141,19 @@ bool snapshot() {
 
 	// Render scene
 	glDepthMask(GL_TRUE);
-	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen
+	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Clear The Screen
 	glDepthMask(GL_FALSE);
 
-	drawBackDrop();                 // Draw the room
+	drawBackDrop();// Draw the room
 	drawZBuffer(cameraX, cameraY, false);
 
 	glEnable(GL_DEPTH_TEST);
 
-	drawPeople();                   // Then add any moving characters...
+	drawPeople();// Then add any moving characters...
 
 	glDisable(GL_DEPTH_TEST);
 
-	viewSpeech();                   // ...and anything being said
+	viewSpeech();// ...and anything being said
 	drawStatusBar();
 	// Copy Our ViewPort To The Texture
 	copyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, viewportOffsetX, viewportOffsetY, winWidth, winHeight, snapshotTextureName);
@@ -178,7 +185,7 @@ bool restoreSnapshot(Common::SeekableReadStream *stream) {
 	if (!snapshotTexture) return fatal("Out of memory while restoring snapshot.");
 #endif
 
-	for (t2 = 0; t2 < winHeight; t2 ++) {
+	for (t2 = 0; t2 < winHeight; t2++) {
 		t1 = 0;
 		while (t1 < winWidth) {
 			c = (unsigned short) get2bytes(stream);
@@ -255,11 +262,11 @@ void killParallax() {
 bool reserveBackdrop() {
 	cameraX = 0;
 	cameraY = 0;
-	input.mouseX = (int)((float)input.mouseX * cameraZoom);
-	input.mouseY = (int)((float)input.mouseY * cameraZoom);
+	input.mouseX = (int) ((float) input.mouseX * cameraZoom);
+	input.mouseY = (int) ((float) input.mouseY * cameraZoom);
 	cameraZoom = 1.0;
-	input.mouseX = (int)((float)input.mouseX / cameraZoom);
-	input.mouseY = (int)((float)input.mouseY / cameraZoom);
+	input.mouseX = (int) ((float) input.mouseX / cameraZoom);
+	input.mouseY = (int) ((float) input.mouseY / cameraZoom);
 	setPixelCoords(false);
 	int picWidth = sceneWidth;
 	int picHeight = sceneHeight;
@@ -304,8 +311,8 @@ bool resizeBackdrop(int x, int y) {
 }
 
 void loadBackDrop(int fileNum, int x, int y) {
+	debug(kSludgeDebugGraphics, "Load back drop");
 	setResourceForFatal(fileNum);
-#if 0
 	if (!openFileFromNum(fileNum)) {
 		fatal("Can't load overlay image");
 		return;
@@ -318,7 +325,6 @@ void loadBackDrop(int fileNum, int x, int y) {
 	}
 
 	finishAccess();
-#endif
 	setResourceForFatal(-1);
 }
 
@@ -341,10 +347,14 @@ void mixBackDrop(int fileNum, int x, int y) {
 
 void blankScreen(int x1, int y1, int x2, int y2) {
 
-	if (y1 < 0) y1 = 0;
-	if (x1 < 0) x1 = 0;
-	if (x2 > (int) sceneWidth) x2 = (int)sceneWidth;
-	if (y2 > (int) sceneHeight) y2 = (int)sceneHeight;
+	if (y1 < 0)
+		y1 = 0;
+	if (x1 < 0)
+		x1 = 0;
+	if (x2 > (int) sceneWidth)
+		x2 = (int) sceneWidth;
+	if (y2 > (int) sceneHeight)
+		y2 = (int) sceneHeight;
 
 	int picWidth = x2 - x1;
 	int picHeight = y2 - y1;
@@ -361,8 +371,6 @@ void blankScreen(int x1, int y1, int x2, int y2) {
 
 			// Render the scene
 
-
-
 			const GLfloat vertices[] = {
 				-10.325f, -1.325f, 0.0f,
 				w + 1.325f, -1.325f, 0.0f,
@@ -396,7 +404,8 @@ void hardScroll(int distance) {
 		return;
 	}
 
-	if (!distance) return;
+	if (!distance)
+		return;
 #if 0
 	const GLfloat backdropTexCoords[] = {
 		0.0f, 0.0f,
@@ -415,7 +424,6 @@ void hardScroll(int distance) {
 		while (yoffset < sceneHeight) {
 			int h = (sceneHeight - yoffset < viewportHeight) ? sceneHeight - yoffset : viewportHeight;
 
-
 			glClear(GL_COLOR_BUFFER_BIT);   // Clear The Screen
 
 			// Render the backdrop
@@ -430,7 +438,6 @@ void hardScroll(int distance) {
 				(GLfloat)sceneWidth - xoffset, (GLfloat)sceneHeight - distance - yoffset, 0.
 			};
 
-
 			glUseProgram(shader.texture);
 
 			setPMVMatrix(shader.texture);
@@ -463,11 +470,13 @@ void darkScreen() {
 
 	int xoffset = 0;
 	while (xoffset < sceneWidth) {
-		int w = (sceneWidth - xoffset < viewportWidth) ? sceneWidth - xoffset : viewportWidth;
+		int w = (sceneWidth - xoffset < viewportWidth) ?
+				sceneWidth - xoffset : viewportWidth;
 
 		int yoffset = 0;
 		while (yoffset < sceneHeight) {
-			int h = (sceneHeight - yoffset < viewportHeight) ? sceneHeight - yoffset : viewportHeight;
+			int h = (sceneHeight - yoffset < viewportHeight) ?
+					sceneHeight - yoffset : viewportHeight;
 
 			// Render the scene - first the old backdrop
 #if 0
@@ -490,7 +499,6 @@ void darkScreen() {
 				backdropTexW, backdropTexH
 			};
 
-
 			glUseProgram(shader.texture);
 
 			setPMVMatrix(shader.texture);
@@ -524,20 +532,14 @@ void darkScreen() {
 		xoffset += w;
 	}
 
-
 	setPixelCoords(false);
 }
 
-
-
 inline int sortOutPCamera(int cX, int fX, int sceneMax, int boxMax) {
 	return (fX == 65535) ?
-	       (sceneMax ? ((cX * boxMax) / sceneMax) : 0)
-	       :
-	       ((cX * fX) / 100);
+			(sceneMax ? ((cX * boxMax) / sceneMax) : 0) : ((cX * fX) / 100);
 }
 
-
 void drawBackDrop() {
 #if 0
 	setPrimaryColor(1.0, 1.0, 1.0, 1.0);
@@ -632,7 +634,6 @@ bool loadLightMap(int v) {
 	png_structp png_ptr;
 	png_infop info_ptr, end_info;
 
-
 	int fileIsPNG = true;
 
 	// Is this a PNG file?
@@ -669,8 +670,8 @@ bool loadLightMap(int v) {
 			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
 			return false;
 		}
-		png_init_io(png_ptr, bigDataFile);      // Tell libpng which file to read
-		png_set_sig_bytes(png_ptr, 8);  // 8 bytes already read
+		png_init_io(png_ptr, bigDataFile);     // Tell libpng which file to read
+		png_set_sig_bytes(png_ptr, 8);// 8 bytes already read
 
 		png_read_info(png_ptr, info_ptr);
 
@@ -730,7 +731,7 @@ bool loadLightMap(int v) {
 	if (fileIsPNG) {
 		unsigned char *row_pointers[lightMap.h];
 		for (int i = 0; i < lightMap.h; i++)
-			row_pointers[i] = lightMap.data + 4 * i * newPicWidth;
+		row_pointers[i] = lightMap.data + 4 * i * newPicWidth;
 
 		png_read_image(png_ptr, (png_byte **) row_pointers);
 		png_read_end(png_ptr, NULL);
@@ -788,13 +789,13 @@ void reloadParallaxTextures() {
 		glGenTextures(1, &nP->textureName);
 		glBindTexture(GL_TEXTURE_2D, nP->textureName);
 		if (nP->wrapS)
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
 		else
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
 		if (nP->wrapT)
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
 		else
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
 
 		if (gameSettings.antiAlias < 0) {
 			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
@@ -815,7 +816,8 @@ void reloadParallaxTextures() {
 #endif
 }
 
-bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY) {
+bool loadParallax(unsigned short v, unsigned short fracX,
+		unsigned short fracY) {
 
 #if 0
 	setResourceForFatal(v);
@@ -839,7 +841,6 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 	png_structp png_ptr;
 	png_infop info_ptr, end_info;
 
-
 	int fileIsPNG = true;
 
 	// Is this a PNG file?
@@ -875,8 +876,8 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
 			return false;
 		}
-		png_init_io(png_ptr, bigDataFile);      // Tell libpng which file to read
-		png_set_sig_bytes(png_ptr, 8);  // 8 bytes already read
+		png_init_io(png_ptr, bigDataFile);     // Tell libpng which file to read
+		png_set_sig_bytes(png_ptr, 8);// 8 bytes already read
 
 		png_read_info(png_ptr, info_ptr);
 
@@ -936,7 +937,7 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 	if (fileIsPNG) {
 		unsigned char *row_pointers[nP->height];
 		for (int i = 0; i < nP->height; i++)
-			row_pointers[i] = nP->texture + 4 * i * picWidth;
+		row_pointers[i] = nP->texture + 4 * i * picWidth;
 
 		png_read_image(png_ptr, (png_byte **) row_pointers);
 		png_read_end(png_ptr, NULL);
@@ -979,13 +980,13 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 	glGenTextures(1, &nP->textureName);
 	glBindTexture(GL_TEXTURE_2D, nP->textureName);
 	if (nP->wrapS)
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
 	else
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
 	if (nP->wrapT)
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
 	else
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
 
 	if (gameSettings.antiAlias < 0) {
 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
@@ -1005,8 +1006,16 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 
 extern int viewportOffsetX, viewportOffsetY;
 
+bool loadPng(int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, bool reserve) {
+	debug("Loading back drop png.");
+	::Image::PNGDecoder png;
+	if (!png.loadStream(*stream))
+		return false;
+	backdropSurface.copyFrom(*(png.getSurface()));
+	picWidth = realPicWidth = backdropSurface.w;
+	picHeight = realPicHeight = backdropSurface.h;
+	return true;
 #if 0
-bool loadPng(GLubyte *loadhere, int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, bool reserve) {
 	long file_pointer = stream->pos();
 	png_structp png_ptr;
 	png_infop info_ptr, end_info;
@@ -1041,7 +1050,7 @@ bool loadPng(GLubyte *loadhere, int &picWidth, int &picHeight, int &realPicWidth
 		return false;
 	}
 	png_init_io(png_ptr, stream);		// Tell libpng which file to read
-	png_set_sig_bytes(png_ptr, 8);	// 8 bytes already read
+	png_set_sig_bytes(png_ptr, 8);// 8 bytes already read
 
 	png_read_info(png_ptr, info_ptr);
 
@@ -1069,14 +1078,16 @@ bool loadPng(GLubyte *loadhere, int &picWidth, int &picHeight, int &realPicWidth
 	unsigned char *row_pointers[realPicHeight];
 
 	for (int i = 0; i < realPicHeight; i++)
-		row_pointers[i] = loadhere + 4 * i * picWidth;
+	row_pointers[i] = loadhere + 4 * i * picWidth;
 
 	png_read_image(png_ptr, (png_byte **) row_pointers);
 	png_read_end(png_ptr, NULL);
 	png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
+#endif
 }
 
-bool loadByteArray(GLubyte *loadhere, int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, bool reserve) {
+bool loadByteArray(int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, bool reserve) {
+#if 0
 	int32_t transCol = reserve ? -1 : 63519;
 	int t1, t2, n;
 	unsigned short c;
@@ -1114,12 +1125,13 @@ bool loadByteArray(GLubyte *loadhere, int &picWidth, int &picHeight, int &realPi
 			}
 		}
 	}
+#endif
 }
 
-bool loadImage(GLubyte *loadhere, int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, int x, int y, bool reserve) {
-
-	if (!loadPng(loadhere, picWidth, picHeight, realPicWidth, realPicHeight, stream, reserve)) {
-		if (!loadByteArray(loadhere, picWidth, picHeight, realPicWidth, realPicHeight, stream, reserve)) {
+bool loadImage(int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, int x, int y, bool reserve) {
+	debug(kSludgeDebugGraphics, "Loading back drop image.");
+	if (!loadPng(picWidth, picHeight, realPicWidth, realPicHeight, stream, reserve)) {
+		if (!loadByteArray(picWidth, picHeight, realPicWidth, realPicHeight, stream, reserve)) {
 			return false;
 		}
 	}
@@ -1131,6 +1143,7 @@ bool loadImage(GLubyte *loadhere, int &picWidth, int &picHeight, int &realPicWid
 	return true;
 }
 
+#if 0
 void makeGlArray(GLuint &tmpTex, const GLubyte *texture, int picWidth, int picHeight) {
 	glGenTextures(1, &tmpTex);
 	glBindTexture(GL_TEXTURE_2D, tmpTex);
@@ -1215,7 +1228,7 @@ void renderToTexture(GLuint tmpTex, int x, int y, int picWidth, int picHeight, i
 
 				glUseProgram(shader.paste);
 				GLint uniform = glGetUniformLocation(shader.paste, "useLightTexture");
-				if (uniform >= 0) glUniform1i(uniform, 0); // No lighting
+				if (uniform >= 0) glUniform1i(uniform, 0);// No lighting
 
 				setPMVMatrix(shader.paste);
 
@@ -1251,15 +1264,14 @@ void renderToTexture(GLuint tmpTex, int x, int y, int picWidth, int picHeight, i
 	setPixelCoords(false);
 }
 #endif
-
 bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
-#if 0
+	debug(kSludgeDebugGraphics, "Load HSI");
 	int picWidth, picHeight;
 	int realPicWidth, realPicHeight;
 
-	if (!loadImage(backdropTexture, picWidth, picHeight, realPicWidth, realPicHeight, stream, x, y, reserve))
+	if (!loadImage(picWidth, picHeight, realPicWidth, realPicHeight, stream, x, y, reserve))
 		return false;
-
+#if 0
 	GLuint tmpTex;
 	makeGlArray(tmpTex, backdropTexture, picWidth, picHeight);
 
@@ -1283,7 +1295,6 @@ bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 	png_structp png_ptr;
 	png_infop info_ptr, end_info;
 
-
 	int fileIsPNG = true;
 
 	// Is this a PNG file?
@@ -1319,7 +1330,7 @@ bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 			return false;
 		}
 		png_init_io(png_ptr, stream);       // Tell libpng which file to read
-		png_set_sig_bytes(png_ptr, 8);  // 8 bytes already read
+		png_set_sig_bytes(png_ptr, 8);// 8 bytes already read
 
 		png_read_info(png_ptr, info_ptr);
 
@@ -1394,11 +1405,10 @@ bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 	GLubyte *target;
 	int32_t transCol = 63519;
 
-
 	if (fileIsPNG) {
 		unsigned char *row_pointers[realPicHeight];
 		for (int i = 0; i < realPicHeight; i++)
-			row_pointers[i] = backdropTexture + 4 * i * picWidth;
+		row_pointers[i] = backdropTexture + 4 * i * picWidth;
 
 		png_read_image(png_ptr, (png_byte **) row_pointers);
 		png_read_end(png_ptr, NULL);
@@ -1449,12 +1459,10 @@ bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 
 	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, backdropTexture, tmpTex);
 
-
 	//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
 
 	setPixelCoords(true);
 
-
 	int xoffset = 0;
 	while (xoffset < realPicWidth) {
 		int w = (realPicWidth - xoffset < viewportWidth) ? realPicWidth - xoffset : viewportWidth;
@@ -1473,7 +1481,7 @@ bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 
 			glUseProgram(shader.paste);
 			GLint uniform = glGetUniformLocation(shader.paste, "useLightTexture");
-			if (uniform >= 0) glUniform1i(uniform, 0); // No lighting
+			if (uniform >= 0) glUniform1i(uniform, 0);// No lighting
 
 			setPMVMatrix(shader.paste);
 
@@ -1566,7 +1574,7 @@ void saveCorePNG(Common::WriteStream *stream, GLuint texture, int w, int h) {
 
 			glUseProgram(0);
 
-			for (int i = 0; i < h; i++)   {
+			for (int i = 0; i < h; i++) {
 				glReadPixels(viewportOffsetX, viewportOffsetY + i, w, 1, GL_RGBA, GL_UNSIGNED_BYTE, image + xoffset * 4 + (yoffset + i) * 4 * tw);
 			}
 			yoffset += viewportHeight;
@@ -1592,7 +1600,7 @@ void saveCorePNG(Common::WriteStream *stream, GLuint texture, int w, int h) {
 	png_init_io(png_ptr, writer);
 
 	png_set_IHDR(png_ptr, info_ptr, w, h,
-	             8, PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
+			8, PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
 
 	unsigned char *row_pointers[h];
 
@@ -1650,7 +1658,7 @@ void saveCoreHSI(Common::WriteStream *stream, GLuint texture, int w, int h) {
 			drawQuad(shader.texture, vertices, 1, texCoords);
 			glUseProgram(0);
 
-			for (int i = 0; i < h; i++)   {
+			for (int i = 0; i < h; i++) {
 				glReadPixels(viewportOffsetX, viewportOffsetY + i, w, 1, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, image + xoffset + (yoffset + i)*tw);
 			}
 			yoffset += viewportHeight;
@@ -1703,7 +1711,7 @@ void saveParallaxRecursive(parallaxLayer *me, Common::WriteStream *stream) {
 		saveParallaxRecursive(me->next, stream);
 		putch(1, stream);
 		put2bytes(me->fileNum, stream);
-		put2bytes(me ->fractionX, stream);
+		put2bytes(me->fractionX, stream);
 		put2bytes(me->fractionY, stream);
 	}
 }
diff --git a/engines/sludge/detection.cpp b/engines/sludge/detection.cpp
index 7e5c124..e45ada2 100644
--- a/engines/sludge/detection.cpp
+++ b/engines/sludge/detection.cpp
@@ -44,6 +44,7 @@ static const PlainGameDescriptor sludgeGames[] = {
 	{ "sludge", "Sludge Game" },
 	{ "welcome", "Welcome Example" },
 	{ "welcome2", "Welcome Example 2" },
+	{ "welcomePng", "Welcome For PNG Test" },
 	{ "verbcoin", "Verb Coin" },
 	{ 0, 0 }
 };
@@ -78,6 +79,19 @@ static const SludgeGameDescription gameDescriptions[] = {
 
 	{
 		{
+			"welcomePng",
+			"",
+			AD_ENTRY1("Welcome.slg", "ff0d7ef0ce73b5503ef6b965928af6d6"),
+			Common::EN_ANY,
+			Common::kPlatformUnknown,
+			ADGF_NO_FLAGS,
+			GUIO0()
+		},
+		0
+	},
+
+	{
+		{
 			"verbcoin",
 			"",
 			AD_ENTRY1("Welcome.slg", "e39ec315dcbf3a1137481f0a5fe1617d"),
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index b278a35..283a228 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -74,6 +74,7 @@
 #include "sludger.h"
 #include "graphics.h"
 #include "helpers.h"
+#include "graphics/surface.h"
 
 namespace Sludge {
 
@@ -97,6 +98,7 @@ extern float cameraZoom;
 extern int specialSettings;
 extern inputType input;
 extern variableStack *noStack;
+extern Graphics::Surface backdropSurface;
 
 int dialogValue = 0;
 
@@ -471,6 +473,8 @@ try
 		walkAllPeople();
 		handleInput();
 		sludgeDisplay();
+		g_system->copyRectToScreen(backdropSurface.getPixels(), backdropSurface.pitch, 0, 0, backdropSurface.w, backdropSurface.h);
+		g_system->updateScreen();
 #if 0
 		Wait_Frame();
 #endif
diff --git a/engines/sludge/sludge.cpp b/engines/sludge/sludge.cpp
index d0d6b37..ea9dc57 100644
--- a/engines/sludge/sludge.cpp
+++ b/engines/sludge/sludge.cpp
@@ -44,6 +44,7 @@ SludgeEngine::SludgeEngine(OSystem *syst, const SludgeGameDescription *gameDesc)
 	DebugMan.addDebugChannel(kSludgeDebugDataLoad, "Data Load", "Data loading debug level");
 	DebugMan.addDebugChannel(kSludgeDebugStackMachine, "Stack Machine", "Stack Machine debug level");
 	DebugMan.addDebugChannel(kSludgeDebugBuiltin, "Built-in", "Built-in debug level");
+	DebugMan.addDebugChannel(kSludgeDebugGraphics, "Graphics", "Graphics debug level");
 
 	// check init
 	debug("SludgeEngine::SludgeEngine");
diff --git a/engines/sludge/sludge.h b/engines/sludge/sludge.h
index 4570b04..734a856 100644
--- a/engines/sludge/sludge.h
+++ b/engines/sludge/sludge.h
@@ -41,6 +41,7 @@ enum {
 	kSludgeDebugDataLoad = 1 << 1,
 	kSludgeDebugStackMachine = 1 << 2,
 	kSludgeDebugBuiltin = 1 << 3,
+	kSludgeDebugGraphics = 1 << 4
 };
  
 class SludgeEngine : public Engine {


Commit: ca2ee02496f232a53ed6c96bd296e0941da636f6
    https://github.com/scummvm/scummvm/commit/ca2ee02496f232a53ed6c96bd296e0941da636f6
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: code formatting

Changed paths:
    engines/sludge/CommonCode/functionlist.h
    engines/sludge/backdrop.cpp
    engines/sludge/backdrop.h
    engines/sludge/builtin.cpp
    engines/sludge/builtin.h
    engines/sludge/colours.h
    engines/sludge/console.cpp
    engines/sludge/console.h
    engines/sludge/csludge.h
    engines/sludge/cursors.cpp
    engines/sludge/fileset.cpp
    engines/sludge/floor.cpp
    engines/sludge/floor.h
    engines/sludge/fonttext.cpp
    engines/sludge/freeze.cpp
    engines/sludge/freeze.h
    engines/sludge/graphics.cpp
    engines/sludge/graphics.h
    engines/sludge/language.cpp
    engines/sludge/line.cpp
    engines/sludge/loadsave.cpp
    engines/sludge/main_loop.cpp
    engines/sludge/memwatch.cpp
    engines/sludge/moreio.cpp
    engines/sludge/movie.cpp
    engines/sludge/movie.h
    engines/sludge/newfatal.cpp
    engines/sludge/objtypes.cpp
    engines/sludge/people.cpp
    engines/sludge/people.h
    engines/sludge/region.cpp
    engines/sludge/savedata.cpp
    engines/sludge/sludge.h
    engines/sludge/sludger.cpp
    engines/sludge/sludger.h
    engines/sludge/sound_bass.cpp
    engines/sludge/sound_openal.cpp
    engines/sludge/sprbanks.cpp
    engines/sludge/sprites.cpp
    engines/sludge/sprites.h
    engines/sludge/stringy.cpp
    engines/sludge/talk.cpp
    engines/sludge/talk.h
    engines/sludge/thumbnail.cpp
    engines/sludge/timing.cpp
    engines/sludge/transition.cpp
    engines/sludge/variable.cpp
    engines/sludge/variable.h
    engines/sludge/vid.cpp
    engines/sludge/winstuff.cpp
    engines/sludge/zbuffer.cpp
    engines/sludge/zbuffer.h


diff --git a/engines/sludge/CommonCode/functionlist.h b/engines/sludge/CommonCode/functionlist.h
index 3d98553..637ed5c 100644
--- a/engines/sludge/CommonCode/functionlist.h
+++ b/engines/sludge/CommonCode/functionlist.h
@@ -1,10 +1,10 @@
 /*
-This is the list of the built in functions
+ This is the list of the built in functions
 
-true or false states if it's a used function
-in the current version of the engine,
-but that value currently isn't used anywhere
-*/
+ true or false states if it's a used function
+ in the current version of the engine,
+ but that value currently isn't used anywhere
+ */
 
 FUNC(true, say)
 FUNC(true, skipSpeech)
@@ -135,10 +135,10 @@ FUNC(true, captureAllKeys)
 FUNC(true, cacheSound)
 FUNC(true, setCharacterSpinSpeed)
 FUNC(true, transitionMode)
-FUNC(false,  _rem_movieStart)
-FUNC(false,  _rem_movieAbort)
-FUNC(false,  _rem_moviePlaying)
-FUNC(false,  _rem_updateDisplay)
+FUNC(false, _rem_movieStart)
+FUNC(false, _rem_movieAbort)
+FUNC(false, _rem_moviePlaying)
+FUNC(false, _rem_updateDisplay)
 FUNC(true, getSoundCache)
 FUNC(true, saveCustomData)
 FUNC(true, loadCustomData)
@@ -160,7 +160,7 @@ FUNC(true, hasFlag)
 FUNC(true, snapshotGrab)
 FUNC(true, snapshotClear)
 FUNC(true, bodgeFilenames)
-FUNC(false,  _rem_registryGetString)
+FUNC(false, _rem_registryGetString)
 FUNC(true, quitWithFatalError)
 FUNC(true, _rem_setCharacterAA)
 FUNC(true, _rem_setMaximumAA)
diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index c28a7d0..7fecf57 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -155,7 +155,7 @@ bool snapshot() {
 
 	viewSpeech();// ...and anything being said
 	drawStatusBar();
-	// Copy Our ViewPort To The Texture
+				 // Copy Our ViewPort To The Texture
 	copyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, viewportOffsetX, viewportOffsetY, winWidth, winHeight, snapshotTextureName);
 
 	setPixelCoords(false);
@@ -320,7 +320,9 @@ void loadBackDrop(int fileNum, int x, int y) {
 
 	if (!loadHSI(bigDataFile, x, y, false)) {
 		char mess[200];
-		sprintf(mess, "Can't paste overlay image outside scene dimensions\n\nX = %i\nY = %i\nWidth = %i\nHeight = %i", x, y, sceneWidth, sceneHeight);
+		sprintf(mess,
+				"Can't paste overlay image outside scene dimensions\n\nX = %i\nY = %i\nWidth = %i\nHeight = %i",
+				x, y, sceneWidth, sceneHeight);
 		fatal(mess);
 	}
 
@@ -1006,11 +1008,14 @@ bool loadParallax(unsigned short v, unsigned short fracX,
 
 extern int viewportOffsetX, viewportOffsetY;
 
-bool loadPng(int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, bool reserve) {
-	debug("Loading back drop png.");
+bool loadPng(int &picWidth, int &picHeight, int &realPicWidth,
+		int &realPicHeight, Common::SeekableReadStream *stream, bool reserve) {
+	debug(kSludgeDebugGraphics, "Loading back drop png.");
 	::Image::PNGDecoder png;
-	if (!png.loadStream(*stream))
+	if (!png.loadStream(*stream)) {
+		debug(kSludgeDebugGraphics, "Back drop is not a png");
 		return false;
+	}
 	backdropSurface.copyFrom(*(png.getSurface()));
 	picWidth = realPicWidth = backdropSurface.w;
 	picHeight = realPicHeight = backdropSurface.h;
@@ -1049,7 +1054,7 @@ bool loadPng(int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeigh
 		png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
 		return false;
 	}
-	png_init_io(png_ptr, stream);		// Tell libpng which file to read
+	png_init_io(png_ptr, stream);       // Tell libpng which file to read
 	png_set_sig_bytes(png_ptr, 8);// 8 bytes already read
 
 	png_read_info(png_ptr, info_ptr);
@@ -1086,7 +1091,8 @@ bool loadPng(int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeigh
 #endif
 }
 
-bool loadByteArray(int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, bool reserve) {
+bool loadByteArray(int &picWidth, int &picHeight, int &realPicWidth,
+		int &realPicHeight, Common::SeekableReadStream *stream, bool reserve) {
 #if 0
 	int32_t transCol = reserve ? -1 : 63519;
 	int t1, t2, n;
@@ -1128,17 +1134,25 @@ bool loadByteArray(int &picWidth, int &picHeight, int &realPicWidth, int &realPi
 #endif
 }
 
-bool loadImage(int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, int x, int y, bool reserve) {
+bool loadImage(int &picWidth, int &picHeight, int &realPicWidth,
+		int &realPicHeight, Common::SeekableReadStream *stream, int x, int y,
+		bool reserve) {
 	debug(kSludgeDebugGraphics, "Loading back drop image.");
-	if (!loadPng(picWidth, picHeight, realPicWidth, realPicHeight, stream, reserve)) {
-		if (!loadByteArray(picWidth, picHeight, realPicWidth, realPicHeight, stream, reserve)) {
+	if (!loadPng(picWidth, picHeight, realPicWidth, realPicHeight, stream,
+			reserve)) {
+		if (!loadByteArray(picWidth, picHeight, realPicWidth, realPicHeight,
+				stream, reserve)) {
 			return false;
 		}
 	}
 
-	if (x == IN_THE_CENTRE) x = (sceneWidth - realPicWidth) >> 1;
-	if (y == IN_THE_CENTRE) y = (sceneHeight - realPicHeight) >> 1;
-	if (x < 0 || x + realPicWidth > sceneWidth || y < 0 || y + realPicHeight > sceneHeight) return false;
+	if (x == IN_THE_CENTRE)
+		x = (sceneWidth - realPicWidth) >> 1;
+	if (y == IN_THE_CENTRE)
+		y = (sceneHeight - realPicHeight) >> 1;
+	if (x < 0 || x + realPicWidth > sceneWidth || y < 0
+			|| y + realPicHeight > sceneHeight)
+		return false;
 
 	return true;
 }
@@ -1269,7 +1283,8 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 	int picWidth, picHeight;
 	int realPicWidth, realPicHeight;
 
-	if (!loadImage(picWidth, picHeight, realPicWidth, realPicHeight, stream, x, y, reserve))
+	if (!loadImage(picWidth, picHeight, realPicWidth, realPicHeight, stream, x,
+			y, reserve))
 		return false;
 #if 0
 	GLuint tmpTex;
diff --git a/engines/sludge/backdrop.h b/engines/sludge/backdrop.h
index 8974f92..8346a46 100644
--- a/engines/sludge/backdrop.h
+++ b/engines/sludge/backdrop.h
@@ -37,7 +37,7 @@
 namespace Sludge {
 
 enum {
-	LIGHTMAPMODE_NONE       = -1,
+	LIGHTMAPMODE_NONE = -1,
 	LIGHTMAPMODE_HOTSPOT,
 	LIGHTMAPMODE_PIXEL,
 	LIGHTMAPMODE_NUM
@@ -46,7 +46,6 @@ enum {
 extern unsigned int winWidth, winHeight, sceneWidth, sceneHeight;
 extern int lightMapMode;
 
-
 struct parallaxLayer {
 #if 0
 	GLubyte *texture;
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 5d5c0fa..f35a2bd 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -2529,7 +2529,7 @@ builtReturn callBuiltIn(int whichFunc, int numParams, loadedFunction *fun) {
 				char buff[100];
 				sprintf(buff, "Built in function must have %i parameter%s",
 				        paramNum[whichFunc],
-				        (paramNum[whichFunc] == 1) ? "" : "s");
+						(paramNum[whichFunc] == 1) ? "" : "s");
 
 				fatal(copyString(buff));
 				return BR_ERROR;
diff --git a/engines/sludge/builtin.h b/engines/sludge/builtin.h
index 00d780e..0fb15d1 100644
--- a/engines/sludge/builtin.h
+++ b/engines/sludge/builtin.h
@@ -25,7 +25,14 @@
 
 namespace Sludge {
 
-enum builtReturn {BR_KEEP_AND_PAUSE, BR_ERROR, BR_CONTINUE, BR_PAUSE, BR_CALLAFUNC, BR_ALREADY_GONE};
+enum builtReturn {
+	BR_KEEP_AND_PAUSE,
+	BR_ERROR,
+	BR_CONTINUE,
+	BR_PAUSE,
+	BR_CALLAFUNC,
+	BR_ALREADY_GONE
+};
 
 bool failSecurityCheck(char *fn);
 builtReturn callBuiltIn(int whichFunc, int numParams, loadedFunction *fun);
diff --git a/engines/sludge/colours.h b/engines/sludge/colours.h
index 2caf963..a613f67 100644
--- a/engines/sludge/colours.h
+++ b/engines/sludge/colours.h
@@ -42,7 +42,8 @@ inline unsigned short makeGrey(unsigned short int r) {
 	return ((r >> 3) << 11) | ((r >> 2) << 5) | (r >> 3);
 }
 
-inline unsigned short makeColour(unsigned short int r, unsigned short int g, unsigned short int b) {
+inline unsigned short makeColour(unsigned short int r, unsigned short int g,
+		unsigned short int b) {
 	return ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3);
 }
 
diff --git a/engines/sludge/console.cpp b/engines/sludge/console.cpp
index 95d70b9..d47f04c 100644
--- a/engines/sludge/console.cpp
+++ b/engines/sludge/console.cpp
@@ -24,7 +24,8 @@
 
 namespace Sludge {
 
-SludgeConsole::SludgeConsole(SludgeEngine *vm) : GUI::Debugger() {
+SludgeConsole::SludgeConsole(SludgeEngine *vm) :
+		GUI::Debugger() {
 	_vm = vm;
 }
 
diff --git a/engines/sludge/console.h b/engines/sludge/console.h
index 5f96409..a720073 100644
--- a/engines/sludge/console.h
+++ b/engines/sludge/console.h
@@ -30,11 +30,11 @@ namespace Sludge {
 class SludgeEngine;
 
 // Example console class
-class SludgeConsole : public GUI::Debugger {
+class SludgeConsole: public GUI::Debugger {
 public:
 	SludgeConsole(SludgeEngine *vm);
 	virtual ~SludgeConsole(void);
-	
+
 private:
 	SludgeEngine *_vm;
 };
diff --git a/engines/sludge/csludge.h b/engines/sludge/csludge.h
index 22b6125..0564853 100644
--- a/engines/sludge/csludge.h
+++ b/engines/sludge/csludge.h
@@ -25,22 +25,51 @@
 
 namespace Sludge {
 
-enum sludgeCommand {SLU_UNKNOWN,
-                    SLU_RETURN, SLU_BRANCH, SLU_BR_ZERO, SLU_SET_GLOBAL,
-                    SLU_SET_LOCAL, SLU_LOAD_GLOBAL, SLU_LOAD_LOCAL,
-                    SLU_PLUS, SLU_MINUS, SLU_MULT, SLU_DIVIDE,
-                    SLU_AND, SLU_OR, SLU_EQUALS, SLU_NOT_EQ, SLU_MODULUS,
-                    SLU_LOAD_VALUE, SLU_LOAD_BUILT, SLU_LOAD_FUNC, SLU_CALLIT,
-                    SLU_LOAD_STRING, SLU_LOAD_FILE, /*SLU_LOAD_SCENE,*/ SLU_LOAD_OBJTYPE,
-                    SLU_NOT, SLU_LOAD_NULL, SLU_STACK_PUSH, SLU_LESSTHAN, SLU_MORETHAN, SLU_NEGATIVE,
-                    SLU_UNREG, SLU_LESS_EQUAL, SLU_MORE_EQUAL,
-                    SLU_INCREMENT_LOCAL,
-                    SLU_DECREMENT_LOCAL,
-                    SLU_INCREMENT_GLOBAL,
-                    SLU_DECREMENT_GLOBAL, SLU_INDEXSET, SLU_INDEXGET,
-                    SLU_INCREMENT_INDEX, SLU_DECREMENT_INDEX, SLU_QUICK_PUSH,
-                    numSludgeCommands
-                   };
+enum sludgeCommand {
+	SLU_UNKNOWN,
+	SLU_RETURN,
+	SLU_BRANCH,
+	SLU_BR_ZERO,
+	SLU_SET_GLOBAL,
+	SLU_SET_LOCAL,
+	SLU_LOAD_GLOBAL,
+	SLU_LOAD_LOCAL,
+	SLU_PLUS,
+	SLU_MINUS,
+	SLU_MULT,
+	SLU_DIVIDE,
+	SLU_AND,
+	SLU_OR,
+	SLU_EQUALS,
+	SLU_NOT_EQ,
+	SLU_MODULUS,
+	SLU_LOAD_VALUE,
+	SLU_LOAD_BUILT,
+	SLU_LOAD_FUNC,
+	SLU_CALLIT,
+	SLU_LOAD_STRING,
+	SLU_LOAD_FILE, /*SLU_LOAD_SCENE,*/
+	SLU_LOAD_OBJTYPE,
+	SLU_NOT,
+	SLU_LOAD_NULL,
+	SLU_STACK_PUSH,
+	SLU_LESSTHAN,
+	SLU_MORETHAN,
+	SLU_NEGATIVE,
+	SLU_UNREG,
+	SLU_LESS_EQUAL,
+	SLU_MORE_EQUAL,
+	SLU_INCREMENT_LOCAL,
+	SLU_DECREMENT_LOCAL,
+	SLU_INCREMENT_GLOBAL,
+	SLU_DECREMENT_GLOBAL,
+	SLU_INDEXSET,
+	SLU_INDEXGET,
+	SLU_INCREMENT_INDEX,
+	SLU_DECREMENT_INDEX,
+	SLU_QUICK_PUSH,
+	numSludgeCommands
+};
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/cursors.cpp b/engines/sludge/cursors.cpp
index 91d0112..562f386 100644
--- a/engines/sludge/cursors.cpp
+++ b/engines/sludge/cursors.cpp
@@ -68,8 +68,8 @@ void displayCursor() {
 
 		if (flipMe != 2) {
 			(flipMe ? flipFontSprite : fontSprite)(input.mouseX, input.mouseY,
-			                                       mouseCursorAnim -> theSprites -> bank.sprites[spriteNum],
-			                                       mouseCursorAnim -> theSprites -> bank.myPalette /* ( spritePalette&) NULL*/);
+					mouseCursorAnim -> theSprites -> bank.sprites[spriteNum],
+					mouseCursorAnim -> theSprites -> bank.myPalette /* ( spritePalette&) NULL*/);
 		}
 
 		if (++ mouseCursorCountUp >= mouseCursorAnim -> frames[mouseCursorFrameNum].howMany) {
@@ -82,9 +82,10 @@ void displayCursor() {
 }
 
 void pasteCursor(int x, int y, personaAnimation *c) {
-	if (c -> numFrames) pasteSpriteToBackDrop(x, y,
-		        c -> theSprites -> bank.sprites[c -> frames[0].frameNum],
-		        c -> theSprites -> bank.myPalette);
+	if (c->numFrames)
+		pasteSpriteToBackDrop(x, y,
+				c->theSprites->bank.sprites[c->frames[0].frameNum],
+				c->theSprites->bank.myPalette);
 }
 
 } // End of namespace Sludge
diff --git a/engines/sludge/fileset.cpp b/engines/sludge/fileset.cpp
index 3c653f4..eb39166 100644
--- a/engines/sludge/fileset.cpp
+++ b/engines/sludge/fileset.cpp
@@ -42,8 +42,8 @@ bool sliceBusy = true;
 
 Common::File *bigDataFile = NULL;
 
-uint32_t startOfDataIndex, startOfTextIndex,
-         startOfSubIndex, startOfObjectIndex;
+uint32_t startOfDataIndex, startOfTextIndex, startOfSubIndex,
+		startOfObjectIndex;
 
 bool openSubSlice(int num) {
 //	FILE * dbug = fopen ("debuggy.txt", "at");
@@ -100,7 +100,6 @@ unsigned int openFileFromNum(int num) {
 	return get4bytes(bigDataFile);
 }
 
-
 // Converts a string from Windows CP-1252 to UTF-8.
 // This is needed for old games.
 char *convertString(char *s) {
@@ -124,10 +123,10 @@ char *convertString(char *s) {
 
 	if (convert == (iconv_t) - 1) {
 		switch (errno) {
-		case EINVAL:
+			case EINVAL:
 			fprintf(stderr, "Error: Encoding not supported by iconv.\n");
 			break;
-		default:
+			default:
 			fprintf(stderr, "Error: Could not open iconv conversion descriptor.\n");
 		}
 	}
@@ -136,35 +135,34 @@ char *convertString(char *s) {
 	size_t len2 = 65535;
 	size_t iconv_value =
 #ifdef _WIN32
-	    iconv(convert, (const char **) tmp1, &len1, tmp2, &len2);
+	iconv(convert, (const char **) tmp1, &len1, tmp2, &len2);
 #else
-	    iconv(convert, (char **) tmp1, &len1, tmp2, &len2);
+	iconv(convert, (char **) tmp1, &len1, tmp2, &len2);
 #endif
 
 	if (iconv_value == (size_t) - 1) {
 		switch (errno) {
-		/* See "man 3 iconv" for an explanation. */
-		case EILSEQ:
+			/* See "man 3 iconv" for an explanation. */
+			case EILSEQ:
 			fprintf(stderr, "Invalid multibyte sequence.\n");
 			break;
-		case EINVAL:
+			case EINVAL:
 			fprintf(stderr, "Incomplete multibyte sequence.\n");
 			break;
-		case E2BIG:
+			case E2BIG:
 			fprintf(stderr, "No more room.\n");
 			break;
-		default:
+			default:
 			fprintf(stderr, "Error: %s.\n", strerror(errno));
 		}
 		fatal("Conversion to Unicode failed. This can be fixed by recompiling the game in a current version of the SLUDGE Development Kit, but this error should never happen. Congratulations, you've found a bug in the SLUDGE engine! Please let us know about it.");
 	}
 	iconv_close(convert);
 
-
 	delete [] sOrig;
 	return copyString(buf = bufOrig);
 #endif
-	return s;//TODO: false value
+	return s; //TODO: false value
 }
 
 char *getNumberedString(int value) {
@@ -199,7 +197,8 @@ void finishAccess() {
 
 int32_t startIndex;
 
-void setFileIndices(Common::File *fp, int numLanguages, unsigned int skipBefore) {
+void setFileIndices(Common::File *fp, int numLanguages,
+		unsigned int skipBefore) {
 	if (fp) {
 		// Keep hold of the file handle, and let things get at it
 		bigDataFile = fp;
@@ -220,7 +219,7 @@ void setFileIndices(Common::File *fp, int numLanguages, unsigned int skipBefore)
 	int skipAfter = numLanguages - skipBefore;
 	while (skipBefore) {
 		fp->seek(get4bytes(fp), SEEK_SET);
-		skipBefore --;
+		skipBefore--;
 	}
 	startOfTextIndex = fp->pos() + 4;
 
@@ -228,7 +227,7 @@ void setFileIndices(Common::File *fp, int numLanguages, unsigned int skipBefore)
 
 	while (skipAfter) {
 		fp->seek(get4bytes(fp), SEEK_SET);
-		skipAfter --;
+		skipAfter--;
 	}
 
 	startOfSubIndex = fp->pos() + 4;
diff --git a/engines/sludge/floor.cpp b/engines/sludge/floor.cpp
index 7ca30b6..ec57387 100644
--- a/engines/sludge/floor.cpp
+++ b/engines/sludge/floor.cpp
@@ -35,17 +35,15 @@ bool pointInFloorPolygon(floorPolygon &floorPoly, int x, int y) {
 	float xp_i, yp_i;
 	float xp_j, yp_j;
 
-	for (j = floorPoly.numVertices - 1; i < floorPoly.numVertices;
-	        j = i ++) {
+	for (j = floorPoly.numVertices - 1; i < floorPoly.numVertices; j = i++) {
 
-		xp_i = currentFloor -> vertex[floorPoly.vertexID[i]].x;
-		yp_i = currentFloor -> vertex[floorPoly.vertexID[i]].y;
-		xp_j = currentFloor -> vertex[floorPoly.vertexID[j]].x;
-		yp_j = currentFloor -> vertex[floorPoly.vertexID[j]].y;
+		xp_i = currentFloor->vertex[floorPoly.vertexID[i]].x;
+		yp_i = currentFloor->vertex[floorPoly.vertexID[i]].y;
+		xp_j = currentFloor->vertex[floorPoly.vertexID[j]].x;
+		yp_j = currentFloor->vertex[floorPoly.vertexID[j]].y;
 
-		if ((((yp_i <= y) && (y < yp_j)) ||
-		        ((yp_j <= y) && (y < yp_i))) &&
-		        (x < (xp_j - xp_i) * (y - yp_i) / (yp_j - yp_i) + xp_i)) {
+		if ((((yp_i <= y) && (y < yp_j)) || ((yp_j <= y) && (y < yp_i)))
+				&& (x < (xp_j - xp_i) * (y - yp_i) / (yp_j - yp_i) + xp_i)) {
 
 			c = !c;
 		}
@@ -53,14 +51,15 @@ bool pointInFloorPolygon(floorPolygon &floorPoly, int x, int y) {
 	return c;
 }
 
-bool getMatchingCorners(floorPolygon &a, floorPolygon &b, int &cornerA, int &cornerB) {
+bool getMatchingCorners(floorPolygon &a, floorPolygon &b, int &cornerA,
+		int &cornerB) {
 	int sharedVertices = 0;
 	int i, j;
 
-	for (i = 0; i < a.numVertices; i ++) {
-		for (j = 0; j < b.numVertices; j ++) {
+	for (i = 0; i < a.numVertices; i++) {
+		for (j = 0; j < b.numVertices; j++) {
 			if (a.vertexID[i] == b.vertexID[j]) {
-				if (sharedVertices ++) {
+				if (sharedVertices++) {
 					cornerB = a.vertexID[i];
 					return true;
 				} else {
@@ -77,10 +76,11 @@ bool polysShareSide(floorPolygon &a, floorPolygon &b) {
 	int sharedVertices = 0;
 	int i, j;
 
-	for (i = 0; i < a.numVertices; i ++) {
-		for (j = 0; j < b.numVertices; j ++) {
+	for (i = 0; i < a.numVertices; i++) {
+		for (j = 0; j < b.numVertices; j++) {
 			if (a.vertexID[i] == b.vertexID[j]) {
-				if (sharedVertices ++) return true;
+				if (sharedVertices++)
+					return true;
 			}
 		}
 	}
@@ -89,30 +89,31 @@ bool polysShareSide(floorPolygon &a, floorPolygon &b) {
 }
 
 void noFloor() {
-	currentFloor -> numPolygons = 0;
-	currentFloor -> polygon = NULL;
-	currentFloor -> vertex = NULL;
-	currentFloor -> matrix = NULL;
+	currentFloor->numPolygons = 0;
+	currentFloor->polygon = NULL;
+	currentFloor->vertex = NULL;
+	currentFloor->matrix = NULL;
 }
 
 bool initFloor() {
 	currentFloor = new flor;
-	if (! checkNew(currentFloor)) return false;
+	if (!checkNew(currentFloor))
+		return false;
 	noFloor();
 	return true;
 }
 
 void killFloor() {
-	for (int i = 0; i < currentFloor -> numPolygons; i ++) {
-		delete currentFloor -> polygon[i].vertexID;
-		delete currentFloor -> matrix[i];
+	for (int i = 0; i < currentFloor->numPolygons; i++) {
+		delete currentFloor->polygon[i].vertexID;
+		delete currentFloor->matrix[i];
 	}
-	delete currentFloor -> polygon;
-	currentFloor -> polygon = NULL;
-	delete currentFloor -> vertex;
-	currentFloor -> vertex = NULL;
-	delete currentFloor -> matrix;
-	currentFloor -> matrix = NULL;
+	delete currentFloor->polygon;
+	currentFloor->polygon = NULL;
+	delete currentFloor->vertex;
+	currentFloor->vertex = NULL;
+	delete currentFloor->matrix;
+	currentFloor->matrix = NULL;
 }
 
 void setFloorNull() {
@@ -128,73 +129,81 @@ bool setFloor(int fileNum) {
 
 	setResourceForFatal(fileNum);
 
-	if (! openFileFromNum(fileNum)) return false;
+	if (!openFileFromNum(fileNum))
+		return false;
 
 	// Find out how many polygons there are and reserve memory
 
-	currentFloor -> originalNum = fileNum;
-	currentFloor -> numPolygons = getch(bigDataFile);
-	currentFloor -> polygon = new floorPolygon[currentFloor -> numPolygons];
-	if (! checkNew(currentFloor -> polygon)) return false;
+	currentFloor->originalNum = fileNum;
+	currentFloor->numPolygons = getch(bigDataFile);
+	currentFloor->polygon = new floorPolygon[currentFloor->numPolygons];
+	if (!checkNew(currentFloor->polygon))
+		return false;
 
 	// Read in each polygon
 
-	for (i = 0; i < currentFloor -> numPolygons; i ++) {
+	for (i = 0; i < currentFloor->numPolygons; i++) {
 
 		// Find out how many vertex IDs there are and reserve memory
 
-		currentFloor -> polygon[i].numVertices = getch(bigDataFile);
-		currentFloor -> polygon[i].vertexID = new int[currentFloor -> polygon[i].numVertices];
-		if (! checkNew(currentFloor -> polygon[i].vertexID)) return false;
+		currentFloor->polygon[i].numVertices = getch(bigDataFile);
+		currentFloor->polygon[i].vertexID =
+				new int[currentFloor->polygon[i].numVertices];
+		if (!checkNew(currentFloor->polygon[i].vertexID))
+			return false;
 
 		// Read in each vertex ID
 
-		for (j = 0; j < currentFloor -> polygon[i].numVertices; j ++) {
-			currentFloor -> polygon[i].vertexID[j] = get2bytes(bigDataFile);
+		for (j = 0; j < currentFloor->polygon[i].numVertices; j++) {
+			currentFloor->polygon[i].vertexID[j] = get2bytes(bigDataFile);
 		}
 	}
 
 	// Find out how many vertices there are and reserve memory
 
 	i = get2bytes(bigDataFile);
-	currentFloor -> vertex = new POINT[i];
-	if (! checkNew(currentFloor -> vertex)) return false;
+	currentFloor->vertex = new POINT[i];
+	if (!checkNew(currentFloor->vertex))
+		return false;
 
-	for (j = 0; j < i; j ++) {
+	for (j = 0; j < i; j++) {
 
-		currentFloor -> vertex[j].x = get2bytes(bigDataFile);
-		currentFloor -> vertex[j].y = get2bytes(bigDataFile);
+		currentFloor->vertex[j].x = get2bytes(bigDataFile);
+		currentFloor->vertex[j].y = get2bytes(bigDataFile);
 	}
 
 	finishAccess();
 
 	// Now build the movement martix
 
-	currentFloor -> matrix = new int *[currentFloor -> numPolygons];
-	int * * distanceMatrix = new int *[currentFloor -> numPolygons];
+	currentFloor->matrix = new int *[currentFloor->numPolygons];
+	int * * distanceMatrix = new int *[currentFloor->numPolygons];
 
-	if (! checkNew(currentFloor -> matrix)) return false;
+	if (!checkNew(currentFloor->matrix))
+		return false;
 
-	for (i = 0; i < currentFloor -> numPolygons; i ++) {
-		currentFloor -> matrix[i] = new int [currentFloor -> numPolygons];
-		distanceMatrix        [i] = new int [currentFloor -> numPolygons];
-		if (! checkNew(currentFloor -> matrix[i])) return false;
-		for (j = 0; j < currentFloor -> numPolygons; j ++) {
-			currentFloor -> matrix[i][j] = -1;
-			distanceMatrix        [i][j] = 10000;
+	for (i = 0; i < currentFloor->numPolygons; i++) {
+		currentFloor->matrix[i] = new int[currentFloor->numPolygons];
+		distanceMatrix[i] = new int[currentFloor->numPolygons];
+		if (!checkNew(currentFloor->matrix[i]))
+			return false;
+		for (j = 0; j < currentFloor->numPolygons; j++) {
+			currentFloor->matrix[i][j] = -1;
+			distanceMatrix[i][j] = 10000;
 		}
 	}
 
-	for (i = 0; i < currentFloor -> numPolygons; i ++) {
-		for (j = 0; j < currentFloor -> numPolygons; j ++) {
+	for (i = 0; i < currentFloor->numPolygons; i++) {
+		for (j = 0; j < currentFloor->numPolygons; j++) {
 			if (i != j) {
-				if (polysShareSide(currentFloor -> polygon[i], currentFloor -> polygon[j])) {
-					currentFloor -> matrix[i][j] = j;
-					distanceMatrix        [i][j] = 1;
+				if (polysShareSide(currentFloor->polygon[i],
+						currentFloor->polygon[j])) {
+					currentFloor->matrix[i][j] = j;
+					distanceMatrix[i][j] = 1;
 				}
 			} else {
-				currentFloor -> matrix[i][j] = -2;
-				distanceMatrix        [i][j] = 0;
+				currentFloor->matrix[i][j] = -2;
+				distanceMatrix[i][j] = 0;
 			}
 		}
 	}
@@ -203,22 +212,23 @@ bool setFloor(int fileNum) {
 	int lookForDistance = 0;
 
 	do {
-		lookForDistance ++;
+		lookForDistance++;
 //		debugMatrix ();
 		madeChange = false;
-		for (i = 0; i < currentFloor -> numPolygons; i ++) {
-			for (j = 0; j < currentFloor -> numPolygons; j ++) {
-				if (currentFloor -> matrix[i][j] == -1) {
+		for (i = 0; i < currentFloor->numPolygons; i++) {
+			for (j = 0; j < currentFloor->numPolygons; j++) {
+				if (currentFloor->matrix[i][j] == -1) {
 
 					// OK, so we don't know how to get from i to j...
-					for (int d = 0; d < currentFloor -> numPolygons; d ++) {
+					for (int d = 0; d < currentFloor->numPolygons; d++) {
 						if (d != i && d != j) {
-							if (currentFloor -> matrix[i][d] == d &&
-							        currentFloor -> matrix[d][j] >= 0 &&
-							        distanceMatrix        [d][j] <= lookForDistance) {
+							if (currentFloor->matrix[i][d] == d
+									&& currentFloor->matrix[d][j] >= 0
+									&& distanceMatrix[d][j]
+											<= lookForDistance) {
 
-								currentFloor -> matrix[i][j] = d;
-								distanceMatrix       [i][j] = lookForDistance + 1;
+								currentFloor->matrix[i][j] = d;
+								distanceMatrix[i][j] = lookForDistance + 1;
 								madeChange = true;
 							}
 						}
@@ -228,8 +238,8 @@ bool setFloor(int fileNum) {
 		}
 	} while (madeChange);
 
-	for (i = 0; i < currentFloor -> numPolygons; i ++) {
-		delete distanceMatrix [i];
+	for (i = 0; i < currentFloor->numPolygons; i++) {
+		delete distanceMatrix[i];
 	}
 
 	delete distanceMatrix;
@@ -242,20 +252,26 @@ bool setFloor(int fileNum) {
 
 void drawFloor() {
 	int i, j, nV;
-	for (i = 0; i < currentFloor -> numPolygons; i ++) {
+	for (i = 0; i < currentFloor->numPolygons; i++) {
 //		drawLine (i, 0, i + 5, 100);
-		nV = currentFloor -> polygon[i].numVertices;
+		nV = currentFloor->polygon[i].numVertices;
 		if (nV > 1) {
-			for (j = 1; j < nV; j ++) {
-				drawLine(currentFloor -> vertex[currentFloor -> polygon[i].vertexID[j - 1]].x,
-				         currentFloor -> vertex[currentFloor -> polygon[i].vertexID[j - 1]].y,
-				         currentFloor -> vertex[currentFloor -> polygon[i].vertexID[j]].x,
-				         currentFloor -> vertex[currentFloor -> polygon[i].vertexID[j]].y);
+			for (j = 1; j < nV; j++) {
+				drawLine(
+						currentFloor->vertex[currentFloor->polygon[i].vertexID[j
+								- 1]].x,
+						currentFloor->vertex[currentFloor->polygon[i].vertexID[j
+								- 1]].y,
+						currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].x,
+						currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].y);
 			}
-			drawLine(currentFloor -> vertex[currentFloor -> polygon[i].vertexID[0]].x,
-			         currentFloor -> vertex[currentFloor -> polygon[i].vertexID[0]].y,
-			         currentFloor -> vertex[currentFloor -> polygon[i].vertexID[nV - 1]].x,
-			         currentFloor -> vertex[currentFloor -> polygon[i].vertexID[nV - 1]].y);
+			drawLine(
+					currentFloor->vertex[currentFloor->polygon[i].vertexID[0]].x,
+					currentFloor->vertex[currentFloor->polygon[i].vertexID[0]].y,
+					currentFloor->vertex[currentFloor->polygon[i].vertexID[nV
+							- 1]].x,
+					currentFloor->vertex[currentFloor->polygon[i].vertexID[nV
+							- 1]].y);
 		}
 	}
 }
@@ -263,14 +279,15 @@ void drawFloor() {
 int inFloor(int x, int y) {
 	int i, r = -1;
 
-	for (i = 0; i < currentFloor -> numPolygons; i ++)
-		if (pointInFloorPolygon(currentFloor -> polygon[i], x, y))
+	for (i = 0; i < currentFloor->numPolygons; i++)
+		if (pointInFloorPolygon(currentFloor->polygon[i], x, y))
 			r = i;
 
 	return r;
 }
 
-bool closestPointOnLine(int &closestX, int &closestY, int x1, int y1, int x2, int y2, int xP, int yP) {
+bool closestPointOnLine(int &closestX, int &closestY, int x1, int y1, int x2,
+		int y2, int xP, int yP) {
 	int xDiff = x2 - x1;
 	int yDiff = y2 - y1;
 
diff --git a/engines/sludge/floor.h b/engines/sludge/floor.h
index 193b6d1..50fe56e 100644
--- a/engines/sludge/floor.h
+++ b/engines/sludge/floor.h
@@ -54,7 +54,8 @@ bool setFloor(int fileNum);
 void drawFloor();
 int inFloor(int x, int y);
 bool getMatchingCorners(floorPolygon &, floorPolygon &, int &, int &);
-bool closestPointOnLine(int &closestX, int &closestY, int x1, int y1, int x2, int y2, int xP, int yP);
+bool closestPointOnLine(int &closestX, int &closestY, int x1, int y1, int x2,
+		int y2, int xP, int yP);
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/fonttext.cpp b/engines/sludge/fonttext.cpp
index 6ac9209..7339d8f 100644
--- a/engines/sludge/fonttext.cpp
+++ b/engines/sludge/fonttext.cpp
@@ -51,11 +51,14 @@ unsigned int fontTableSize = 0;
 extern float cameraZoom;
 
 bool isInFont(char *theText) {
-	if (! fontTableSize) return 0;
-	if (! theText[0]) return 0;
+	if (!fontTableSize)
+		return 0;
+	if (!theText[0])
+		return 0;
 
 	// We don't want to compare strings. Only single characters allowed!
-	if (u8_strlen(theText) > 1) return false;
+	if (u8_strlen(theText) > 1)
+		return false;
 
 	int i = 0;
 	uint32_t c = u8_nextchar(theText, &i);
@@ -72,7 +75,8 @@ int stringWidth(char *theText) {
 	uint32_t c;
 	int xOff = 0;
 
-	if (! fontTableSize) return 0;
+	if (!fontTableSize)
+		return 0;
 
 	while (theText[a]) {
 		c = u8_nextchar(theText, &a);
@@ -87,46 +91,51 @@ void pasteString(char *theText, int xOff, int y, spritePalette &thePal) {
 	int a = 0;
 	uint32_t c;
 
-	if (! fontTableSize) return;
+	if (!fontTableSize)
+		return;
 
-	xOff += (int)((float)(fontSpace >> 1) / cameraZoom);
+	xOff += (int) ((float) (fontSpace >> 1) / cameraZoom);
 	while (theText[a]) {
 		c = u8_nextchar(theText, &a);
-		mySprite = & theFont.sprites[fontInTable(c)];
-		fontSprite(xOff, y, * mySprite, thePal);
-		xOff += (int)((double)(mySprite -> width + fontSpace) / cameraZoom);
+		mySprite = &theFont.sprites[fontInTable(c)];
+		fontSprite(xOff, y, *mySprite, thePal);
+		xOff += (int) ((double) (mySprite->width + fontSpace) / cameraZoom);
 	}
 }
 
-void pasteStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal) {
+void pasteStringToBackdrop(char *theText, int xOff, int y,
+		spritePalette &thePal) {
 	sprite *mySprite;
 	int a = 0;
 	uint32_t c;
 
-	if (! fontTableSize) return;
+	if (!fontTableSize)
+		return;
 
 	xOff += fontSpace >> 1;
 	while (theText[a]) {
 		c = u8_nextchar(theText, &a);
-		mySprite = & theFont.sprites[fontInTable(c)];
-		pasteSpriteToBackDrop(xOff, y, * mySprite, thePal);
-		xOff += mySprite -> width + fontSpace;
+		mySprite = &theFont.sprites[fontInTable(c)];
+		pasteSpriteToBackDrop(xOff, y, *mySprite, thePal);
+		xOff += mySprite->width + fontSpace;
 	}
 }
 
-void burnStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal) {
+void burnStringToBackdrop(char *theText, int xOff, int y,
+		spritePalette &thePal) {
 	sprite *mySprite;
 	int a = 0;
 	uint32_t c;
 
-	if (! fontTableSize) return;
+	if (!fontTableSize)
+		return;
 
 	xOff += fontSpace >> 1;
 	while (theText[a]) {
 		c = u8_nextchar(theText, &a);
-		mySprite = & theFont.sprites[fontInTable(c)];
-		burnSpriteToBackDrop(xOff, y, * mySprite, thePal);
-		xOff += mySprite -> width + fontSpace;
+		mySprite = &theFont.sprites[fontInTable(c)];
+		burnSpriteToBackDrop(xOff, y, *mySprite, thePal);
+		xOff += mySprite->width + fontSpace;
 	}
 }
 
@@ -167,26 +176,27 @@ bool loadFont(int filenum, const char *charOrder, int h) {
 	int a = 0;
 	uint32_t c;
 
-	delete [] fontOrderString;
+	delete[] fontOrderString;
 	fontOrderString = copyString(charOrder);
 
 	forgetSpriteBank(theFont);
 
 	loadedFontNum = filenum;
 
-
 	fontTableSize = 0;
 	while (charOrder[a]) {
 		c = u8_nextchar(charOrder, &a);
-		if (c > fontTableSize) fontTableSize = c;
+		if (c > fontTableSize)
+			fontTableSize = c;
 	}
 	fontTableSize++;
 
-	delete [] fontTable;
-	fontTable = new uint32_t [fontTableSize];
-	if (! checkNew(fontTable)) return false;
+	delete[] fontTable;
+	fontTable = new uint32_t[fontTableSize];
+	if (!checkNew(fontTable))
+		return false;
 
-	for (a = 0; a < fontTableSize; a ++) {
+	for (a = 0; a < fontTableSize; a++) {
 		fontTable[a] = 0;
 	}
 	a = 0;
@@ -197,7 +207,7 @@ bool loadFont(int filenum, const char *charOrder, int h) {
 		i++;
 	}
 
-	if (! loadSpriteBank(filenum, theFont, true)) {
+	if (!loadSpriteBank(filenum, theFont, true)) {
 		fatal("Can't load font");
 		return false;
 	}
diff --git a/engines/sludge/freeze.cpp b/engines/sludge/freeze.cpp
index 8435a9c..7057f6e 100644
--- a/engines/sludge/freeze.cpp
+++ b/engines/sludge/freeze.cpp
@@ -72,7 +72,7 @@ void freezeGraphics() {
 #endif
 	int w = winWidth;
 	int h = winHeight;
-	if (! NPOT_textures) {
+	if (!NPOT_textures) {
 		w = getNextPOT(winWidth);
 		h = getNextPOT(winHeight);
 	}
@@ -89,7 +89,6 @@ void freezeGraphics() {
 	int antiAlias = gameSettings.antiAlias;
 	gameSettings.antiAlias = 0;
 
-
 	int x = 0;
 	while (x < winWidth) {
 		int y = 0;
@@ -109,10 +108,10 @@ void freezeGraphics() {
 			}
 #if 0
 			const GLfloat bPMVMatrix[] = {
-				2.0f / realWinWidth * cameraZoom,                            .0,   .0,  .0,
-				.0, 2.0f / realWinHeight * cameraZoom,   .0,  .0,
-				.0,                            .0, 1.0f,  .0,
-				-2.0f * (x / realWinWidth) - 1.0f,  -2.0f * (y / realWinHeight) - 1.0f,   .0, 1.0f
+				2.0f / realWinWidth * cameraZoom, .0, .0, .0,
+				.0, 2.0f / realWinHeight * cameraZoom, .0, .0,
+				.0, .0, 1.0f, .0,
+				-2.0f * (x / realWinWidth) - 1.0f, -2.0f * (y / realWinHeight) - 1.0f, .0, 1.0f
 
 			};
 			for (int i = 0; i < 16; i++) {
@@ -120,19 +119,18 @@ void freezeGraphics() {
 			}
 			// Render scene
 			glDepthMask(GL_TRUE);
-			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen
+			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Clear The Screen
 			glDepthMask(GL_FALSE);
 
-			drawBackDrop();                 // Draw the room
+			drawBackDrop();// Draw the room
 			drawZBuffer(cameraX, cameraY, false);
 
 			glEnable(GL_DEPTH_TEST);
 
-			drawPeople();                   // Then add any moving characters...
+			drawPeople();// Then add any moving characters...
 
 			glDisable(GL_DEPTH_TEST);
 
-
 			// Copy Our ViewPort To The Texture
 			copyTexSubImage2D(GL_TEXTURE_2D, 0, x, y, 0, 0, w, h, freezeTextureName);
 #endif
@@ -152,7 +150,8 @@ void freezeGraphics() {
 bool freeze() {
 	debugOut("calling freeze()\n");
 	frozenStuffStruct *newFreezer = new frozenStuffStruct;
-	if (! checkNew(newFreezer)) return false;
+	if (!checkNew(newFreezer))
+		return false;
 
 	// Grab a copy of the current scene
 	freezeGraphics();
@@ -161,7 +160,7 @@ bool freeze() {
 #endif
 	int picWidth = sceneWidth;
 	int picHeight = sceneHeight;
-	if (! NPOT_textures) {
+	if (!NPOT_textures) {
 		picWidth = getNextPOT(picWidth);
 		picHeight = getNextPOT(picHeight);
 	}
@@ -173,11 +172,11 @@ bool freeze() {
 
 	backdropTextureName = 0;
 #endif
-	newFreezer -> sceneWidth = sceneWidth;
-	newFreezer -> sceneHeight = sceneHeight;
-	newFreezer -> cameraX = cameraX;
-	newFreezer -> cameraY = cameraY;
-	newFreezer -> cameraZoom = cameraZoom;
+	newFreezer->sceneWidth = sceneWidth;
+	newFreezer->sceneHeight = sceneHeight;
+	newFreezer->cameraX = cameraX;
+	newFreezer->cameraY = cameraY;
+	newFreezer->cameraZoom = cameraZoom;
 #if 0
 	newFreezer -> lightMapTexture = lightMap.data;
 	newFreezer -> lightMapTextureName = lightMap.name;
@@ -192,9 +191,10 @@ bool freeze() {
 	zBuffer.tex = NULL;
 #endif
 	// resizeBackdrop kills parallax stuff, light map, z-buffer...
-	if (! resizeBackdrop(winWidth, winHeight)) return fatal("Can't create new temporary backdrop buffer");
+	if (!resizeBackdrop(winWidth, winHeight))
+		return fatal("Can't create new temporary backdrop buffer");
 
-	if (! NPOT_textures) {
+	if (!NPOT_textures) {
 		picWidth = getNextPOT(sceneWidth);
 		picHeight = getNextPOT(sceneHeight);
 #if 0
@@ -225,31 +225,33 @@ bool freeze() {
 		deleteTextures(1, &newFreezer -> backdropTextureName);
 	}
 #endif
-	newFreezer -> allPeople = allPeople;
+	newFreezer->allPeople = allPeople;
 	allPeople = NULL;
 
 	statusStuff *newStatusStuff = new statusStuff;
-	if (! checkNew(newStatusStuff)) return false;
-	newFreezer -> frozenStatus = copyStatusBarStuff(newStatusStuff);
+	if (!checkNew(newStatusStuff))
+		return false;
+	newFreezer->frozenStatus = copyStatusBarStuff(newStatusStuff);
 
-	newFreezer -> allScreenRegions = allScreenRegions;
+	newFreezer->allScreenRegions = allScreenRegions;
 	allScreenRegions = NULL;
 	overRegion = NULL;
 
-	newFreezer -> mouseCursorAnim = mouseCursorAnim;
-	newFreezer -> mouseCursorFrameNum = mouseCursorFrameNum;
+	newFreezer->mouseCursorAnim = mouseCursorAnim;
+	newFreezer->mouseCursorFrameNum = mouseCursorFrameNum;
 	mouseCursorAnim = makeNullAnim();
 	mouseCursorFrameNum = 0;
 
-	newFreezer -> speech = speech;
+	newFreezer->speech = speech;
 	initSpeech();
 
-	newFreezer -> currentEvents = currentEvents;
+	newFreezer->currentEvents = currentEvents;
 	currentEvents = new eventHandlers;
-	if (! checkNew(currentEvents)) return false;
+	if (!checkNew(currentEvents))
+		return false;
 	memset(currentEvents, 0, sizeof(eventHandlers));
 
-	newFreezer -> next = frozenStuff;
+	newFreezer->next = frozenStuff;
 	frozenStuff = newFreezer;
 
 	return true;
@@ -259,8 +261,8 @@ int howFrozen() {
 	int a = 0;
 	frozenStuffStruct *f = frozenStuff;
 	while (f) {
-		a ++;
-		f = f -> next;
+		a++;
+		f = f->next;
 	}
 	return a;
 }
@@ -272,25 +274,26 @@ extern GLubyte *backdropTexture;
 void unfreeze(bool killImage) {
 	frozenStuffStruct *killMe = frozenStuff;
 
-	if (! frozenStuff) return;
+	if (!frozenStuff)
+		return;
 
-	sceneWidth = frozenStuff -> sceneWidth;
-	sceneHeight = frozenStuff -> sceneHeight;
+	sceneWidth = frozenStuff->sceneWidth;
+	sceneHeight = frozenStuff->sceneHeight;
 
-	cameraX = frozenStuff -> cameraX;
-	cameraY = frozenStuff -> cameraY;
-	input.mouseX = (int)(input.mouseX * cameraZoom);
-	input.mouseY = (int)(input.mouseY * cameraZoom);
-	cameraZoom = frozenStuff -> cameraZoom;
-	input.mouseX = (int)(input.mouseX / cameraZoom);
-	input.mouseY = (int)(input.mouseY / cameraZoom);
+	cameraX = frozenStuff->cameraX;
+	cameraY = frozenStuff->cameraY;
+	input.mouseX = (int) (input.mouseX * cameraZoom);
+	input.mouseY = (int) (input.mouseY * cameraZoom);
+	cameraZoom = frozenStuff->cameraZoom;
+	input.mouseX = (int) (input.mouseX / cameraZoom);
+	input.mouseY = (int) (input.mouseY / cameraZoom);
 	setPixelCoords(false);
 
 	killAllPeople();
-	allPeople = frozenStuff -> allPeople;
+	allPeople = frozenStuff->allPeople;
 
 	killAllRegions();
-	allScreenRegions = frozenStuff -> allScreenRegions;
+	allScreenRegions = frozenStuff->allScreenRegions;
 
 	killLightMap();
 #if 0
@@ -346,18 +349,18 @@ void unfreeze(bool killImage) {
 	}
 #endif
 	deleteAnim(mouseCursorAnim);
-	mouseCursorAnim = frozenStuff -> mouseCursorAnim;
-	mouseCursorFrameNum = frozenStuff -> mouseCursorFrameNum;
+	mouseCursorAnim = frozenStuff->mouseCursorAnim;
+	mouseCursorFrameNum = frozenStuff->mouseCursorFrameNum;
 
-	restoreBarStuff(frozenStuff -> frozenStatus);
+	restoreBarStuff(frozenStuff->frozenStatus);
 
 	delete currentEvents;
-	currentEvents = frozenStuff -> currentEvents;
+	currentEvents = frozenStuff->currentEvents;
 	killAllSpeech();
 	delete speech;
 
-	speech = frozenStuff -> speech;
-	frozenStuff = frozenStuff -> next;
+	speech = frozenStuff->speech;
+	frozenStuff = frozenStuff->next;
 
 	overRegion = NULL;
 	delete killMe;
diff --git a/engines/sludge/freeze.h b/engines/sludge/freeze.h
index a9f5129..4472852 100644
--- a/engines/sludge/freeze.h
+++ b/engines/sludge/freeze.h
@@ -48,7 +48,6 @@ struct frozenStuffStruct {
 	frozenStuffStruct *next;
 };
 
-
 bool freeze();
 void unfreeze(bool killImage = true);
 int howFrozen();
diff --git a/engines/sludge/graphics.cpp b/engines/sludge/graphics.cpp
index 702865e..7c7c7be 100644
--- a/engines/sludge/graphics.cpp
+++ b/engines/sludge/graphics.cpp
@@ -94,13 +94,13 @@ struct textureList *firstTexture = NULL;
 
 textureList *addTexture() {
 	textureList *newTexture = new textureList;
-	newTexture -> next = firstTexture;
+	newTexture->next = firstTexture;
 	firstTexture = newTexture;
 	return newTexture;
 }
 
 #if 0
-void deleteTextures(GLsizei n,  const GLuint *textures) {
+void deleteTextures(GLsizei n, const GLuint *textures) {
 	if (firstTexture == NULL) {
 		//debugOut("Deleting texture while list is already empty.\n");
 	} else {
@@ -133,10 +133,10 @@ void deleteTextures(GLsizei n,  const GLuint *textures) {
 
 }
 
-void getTextureDimensions(GLuint name, GLint *width,  GLint *height) {
+void getTextureDimensions(GLuint name, GLint *width, GLint *height) {
 	textureList *list = firstTexture;
 	while (list) {
-		if (list->name == name)  {
+		if (list->name == name) {
 			*width = list->width;
 			*height = list->height;
 #if !defined(HAVE_GLES2)
@@ -156,7 +156,7 @@ void getTextureDimensions(GLuint name, GLint *width,  GLint *height) {
 	fatal("Texture not found in list.\n");
 }
 
-void storeTextureDimensions(GLuint name, GLsizei width,  GLsizei height, const char *file, int line) {
+void storeTextureDimensions(GLuint name, GLsizei width, GLsizei height, const char *file, int line) {
 	if (! NPOT_textures && !(((height & (height - 1)) == 0) || ((width & (width - 1)) == 0))) {
 		debugOut("I was told to create a texture with dimensions %ix%i in %s @ line %d although NPOT textures are disabled.\n", width, height, file, line);
 		//height = getNextPOT(height);
@@ -165,7 +165,7 @@ void storeTextureDimensions(GLuint name, GLsizei width,  GLsizei height, const c
 
 	textureList *list = firstTexture;
 	while (list) {
-		if (list->name == name)  {
+		if (list->name == name) {
 			//debugOut("Texture dimensions are overwritten.\n");
 			break;
 		}
@@ -182,14 +182,14 @@ void storeTextureDimensions(GLuint name, GLsizei width,  GLsizei height, const c
 #endif
 
 #ifdef HAVE_GLES2
-void glesCopyTexSubImage2D(GLenum target,  GLint level, GLint xoffset, GLint yoffset, GLint x,  GLint y,  GLsizei width,  GLsizei height) {
+void glesCopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height) {
 	// Work around for broken glCopy(Sub)TexImage2D...
 	void *tmp = malloc(width * height * 4);
 	glReadPixels(x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, tmp);
 	glTexSubImage2D(target, level, xoffset, yoffset, width, height, GL_RGBA, GL_UNSIGNED_BYTE, tmp);
 	free(tmp);
 }
-void glesCopyTexImage2D(GLenum target,  GLint level,  GLenum internalformat,  GLint x,  GLint y,  GLsizei width,  GLsizei height,  GLint border) {
+void glesCopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border) {
 	// Work around for broken glCopy(Sub)TexImage2D...
 	void *tmp = malloc(width * height * 4);
 	glReadPixels(x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, tmp);
@@ -199,7 +199,7 @@ void glesCopyTexImage2D(GLenum target,  GLint level,  GLenum internalformat,  GL
 #endif
 
 #if 0
-void dcopyTexImage2D(GLenum target,  GLint level,  GLenum internalformat,  GLint x,  GLint y,  GLsizei width,  GLsizei height,  GLint border, GLuint name, const char *file, int line) {
+void dcopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border, GLuint name, const char *file, int line) {
 
 	glBindTexture(GL_TEXTURE_2D, name);
 #ifdef HAVE_GLES2_
@@ -209,7 +209,7 @@ void dcopyTexImage2D(GLenum target,  GLint level,  GLenum internalformat,  GLint
 #endif
 }
 
-void dcopyTexSubImage2D(GLenum target,  GLint level,  GLint xoffset,  GLint yoffset,  GLint x,  GLint y,  GLsizei width,  GLsizei height, GLuint name, const char *file, int line) {
+void dcopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, GLuint name, const char *file, int line) {
 	glBindTexture(GL_TEXTURE_2D, name);
 #ifdef HAVE_GLES2_
 	glesCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
@@ -218,16 +218,16 @@ void dcopyTexSubImage2D(GLenum target,  GLint level,  GLint xoffset,  GLint yoff
 #endif
 }
 
-void dtexImage2D(GLenum target,  GLint level,  GLint internalformat,  GLsizei width,  GLsizei height,
-                 GLint border,  GLenum format,  GLenum type,  const GLvoid *data, GLuint name, const char *file, int line) {
-	storeTextureDimensions(name, width,  height, file, line);
+void dtexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height,
+		GLint border, GLenum format, GLenum type, const GLvoid *data, GLuint name, const char *file, int line) {
+	storeTextureDimensions(name, width, height, file, line);
 	glBindTexture(GL_TEXTURE_2D, name);
-	glTexImage2D(target, level, internalformat, width, height, border, format, type,  data);
+	glTexImage2D(target, level, internalformat, width, height, border, format, type, data);
 }
 
-void dtexSubImage2D(GLenum target,  GLint level,  GLint xoffset,  GLint yoffset,  GLsizei width,  GLsizei height,
-                    GLenum format,  GLenum type,  const GLvoid *data, GLuint name, const char *file, int line) {
-	storeTextureDimensions(name, width,  height, file, line);
+void dtexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
+		GLenum format, GLenum type, const GLvoid *data, GLuint name, const char *file, int line) {
+	storeTextureDimensions(name, width, height, file, line);
 	glBindTexture(GL_TEXTURE_2D, name);
 	glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, data);
 }
@@ -289,7 +289,6 @@ void drawQuad(GLint program, const GLfloat *vertices, int numTexCoords, ...) {
 
 }
 
-
 void setPMVMatrix(GLint program) {
 	glUniformMatrix4fv(glGetUniformLocation(program, "myPMVMatrix"), 1, GL_FALSE, aPMVMatrix);
 }
@@ -310,10 +309,10 @@ void setPixelCoords(bool pixels) {
 		glClear(GL_COLOR_BUFFER_BIT);
 
 		const GLfloat bPMVMatrix[] = {
-			2.0f / viewportWidth,                  .0,   .0,  .0,
-			.0, 2.0f / viewportHeight,   .0,  .0,
-			.0,                  .0, 1.0f,  .0,
-			-1.0,               -1.0f,   .0, 1.0f
+			2.0f / viewportWidth, .0, .0, .0,
+			.0, 2.0f / viewportHeight, .0, .0,
+			.0, .0, 1.0f, .0,
+			-1.0, -1.0f, .0, 1.0f
 
 		};
 		for (int i = 0; i < 16; i++) {
@@ -332,10 +331,10 @@ void setPixelCoords(bool pixels) {
 		GLfloat h = (GLfloat) winHeight / cameraZoom;
 
 		const GLfloat bPMVMatrix[] = {
-			2.0f / w,      .0,   .0,  .0,
-			.0, -2.0f / h,   .0,  .0,
-			.0,      .0, 1.0f,  .0,
-			-1.0,    1.0f,   .0, 1.0f
+			2.0f / w, .0, .0, .0,
+			.0, -2.0f / h, .0, .0,
+			.0, .0, 1.0f, .0,
+			-1.0, 1.0f, .0, 1.0f
 
 		};
 		for (int i = 0; i < 16; i++) {
@@ -348,7 +347,6 @@ void setPixelCoords(bool pixels) {
 int desktopW = 0, desktopH = 0;
 bool runningFullscreen = false;
 
-
 #if defined(HAVE_GLES2)
 void saveTexture(GLuint tex, GLubyte *data) {
 	// use an FBO to easily grab the texture...
@@ -412,7 +410,7 @@ void saveTexture(GLuint tex, GLubyte *data) {
 			drawQuad(shader.texture, vertices, 1, texCoords);
 			glUseProgram(0);
 
-			for (int i = 0; i < h; i++)   {
+			for (int i = 0; i < h; i++) {
 				glReadPixels(viewportOffsetX, viewportOffsetY + i, w, 1, GL_RGBA, GL_UNSIGNED_BYTE, data + xoffset * 4 + (yoffset + i) * 4 * tw);
 			}
 
@@ -607,13 +605,13 @@ void setGraphicsWindow(bool fullscreen, bool restoreGraphics, bool resize) {
 	Fragment = shaderFileRead("scale.frag");
 #else
 	/*  const GLubyte *str;
-	    int glDerivativesAvailable;
-	    str = glGetString (GL_EXTENSIONS);
-	    glDerivativesAvailable = (strstr((const char *)str, "GL_OES_standard_derivatives") != NULL);
-	    if (!glDerivativesAvailable) {
-	        debugOut("Extension \"GL_OES_standard_derivatives\" not available. Advanced anti-aliasing is not possible. Using linear anti-aliasing instead.");
-	        gameSettings.antiAlias = -1;
-	*/
+	 int glDerivativesAvailable;
+	 str = glGetString (GL_EXTENSIONS);
+	 glDerivativesAvailable = (strstr((const char *)str, "GL_OES_standard_derivatives") != NULL);
+	 if (!glDerivativesAvailable) {
+	 debugOut("Extension \"GL_OES_standard_derivatives\" not available. Advanced anti-aliasing is not possible. Using linear anti-aliasing instead.");
+	 gameSettings.antiAlias = -1;
+	 */
 	Fragment = shaderFileRead("scale_noaa.frag");
 //	}
 
@@ -823,7 +821,6 @@ void setGraphicsWindow(bool fullscreen, bool restoreGraphics, bool resize) {
 			}
 		}
 
-
 		reloadSpriteTextures();
 		reloadParallaxTextures();
 		zBuffer.texName = 0;
@@ -839,7 +836,7 @@ void setGraphicsWindow(bool fullscreen, bool restoreGraphics, bool resize) {
 	}
 
 	if (movieIsPlaying)
-		setMovieViewport();
+	setMovieViewport();
 #endif
 }
 
@@ -923,7 +920,6 @@ void setupOpenGLStuff() {
 
 }
 
-
 // I found this function on a coding forum on the 'net.
 // Looks a bit weird, but it should work.
 int getNextPOT(int n) {
diff --git a/engines/sludge/graphics.h b/engines/sludge/graphics.h
index 24b7671..493e6f1 100644
--- a/engines/sludge/graphics.h
+++ b/engines/sludge/graphics.h
@@ -87,7 +87,8 @@ void setPMVMatrix(GLint program);
 #endif
 
 void setPixelCoords(bool pixels);
-void setGraphicsWindow(bool fullscreen, bool restoreGraphics = true, bool resize = false);
+void setGraphicsWindow(bool fullscreen, bool restoreGraphics = true,
+		bool resize = false);
 
 void setupOpenGLStuff();
 
@@ -96,10 +97,10 @@ int getNextPOT(int n);
 #if 0
 void saveTexture(GLuint tex, GLubyte *data);
 
-void dcopyTexImage2D(GLenum target,  GLint level,  GLenum internalformat,  GLint x,  GLint y,  GLsizei width,  GLsizei height,  GLint border, GLuint name, const char *file, int line);
-void dcopyTexSubImage2D(GLenum target,  GLint level,  GLint xoffset,  GLint yoffset,  GLint x,  GLint y,  GLsizei width,  GLsizei height, GLuint name, const char *file, int line);
-void dtexImage2D(GLenum target,  GLint level,  GLint internalformat,  GLsizei width,  GLsizei height,  GLint border,  GLenum format,  GLenum type,  const GLvoid *data, GLuint name, const char *file, int line);
-void dtexSubImage2D(GLenum target,  GLint level,  GLint xoffset,  GLint yoffset,  GLsizei width,  GLsizei height,  GLenum format,  GLenum type,  const GLvoid *data, GLuint name, const char *file, int line);
+void dcopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border, GLuint name, const char *file, int line);
+void dcopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, GLuint name, const char *file, int line);
+void dtexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *data, GLuint name, const char *file, int line);
+void dtexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *data, GLuint name, const char *file, int line);
 
 #define copyTexImage2D(target, level, internalformat, x, y,  width, height, border, name) dcopyTexImage2D(target,  level,  internalformat,  x,  y,  width,height, border, name, __FILE__, __LINE__)
 
@@ -109,14 +110,15 @@ void dtexSubImage2D(GLenum target,  GLint level,  GLint xoffset,  GLint yoffset,
 
 #define texSubImage2D( target,  level,   xoffset,   yoffset,   width,  height, format,  type,   data,name) dtexSubImage2D( target, level,   xoffset,  yoffset,  width,  height, format,  type,  data,  name, __FILE__, __LINE__)
 
-void deleteTextures(GLsizei n,  const GLuint *textures);
+void deleteTextures(GLsizei n, const GLuint *textures);
 
-void getTextureDimensions(GLuint name, GLint *width,  GLint *height);
+void getTextureDimensions(GLuint name, GLint *width, GLint *height);
 
-int printOglError(const char *file, int         line);
+int printOglError(const char *file, int line);
 #define printOpenGLError() printOglError(__FILE__, __LINE__)
 #endif
 
-} // End of namespace Sludge
+}
+ // End of namespace Sludge
 
 #endif
diff --git a/engines/sludge/language.cpp b/engines/sludge/language.cpp
index 4fe2780..6bbb6d3 100644
--- a/engines/sludge/language.cpp
+++ b/engines/sludge/language.cpp
@@ -44,9 +44,9 @@ unsigned int stringToInt(char *s) {
 		if (*s >= '0' && *s <= '9') {
 			i *= 10;
 			i += *s - '0';
-			s ++;
+			s++;
 		} else if (*s == '-') {
-			negative = ! negative;
+			negative = !negative;
 			s++;
 		} else {
 			if (negative)
@@ -56,7 +56,6 @@ unsigned int stringToInt(char *s) {
 	}
 }
 
-
 char *getPrefsFilename(char *filename) {
 	// Yes, this trashes the original string, but
 	// we also free it at the end (warning!)...
@@ -92,7 +91,8 @@ void readIniFile(char *filename) {
 
 	Common::File fd;
 	if (!fd.open(langName)) {
-		debug(kSludgeDebugDataLoad, "Fail to open language file : %s", langName);
+		debug(kSludgeDebugDataLoad, "Fail to open language file : %s",
+				langName);
 		return;
 	}
 
@@ -127,7 +127,7 @@ void readIniFile(char *filename) {
 				if (strcmp(lineSoFar, "LANGUAGE") == 0) {
 					gameSettings.languageID = stringToInt(secondSoFar);
 				} else if (strcmp(lineSoFar, "WINDOW") == 0) {
-					gameSettings.userFullScreen = ! stringToInt(secondSoFar);
+					gameSettings.userFullScreen = !stringToInt(secondSoFar);
 				} else if (strcmp(lineSoFar, "REFRESH") == 0) {
 					gameSettings.refreshRate = stringToInt(secondSoFar);
 				} else if (strcmp(lineSoFar, "ANTIALIAS") == 0) {
@@ -153,10 +153,10 @@ void readIniFile(char *filename) {
 
 		default:
 			if (doingSecond) {
-				secondSoFar[here ++] = readChar;
+				secondSoFar[here++] = readChar;
 				secondSoFar[here] = 0;
 			} else {
-				lineSoFar[here ++] = readChar;
+				lineSoFar[here++] = readChar;
 				lineSoFar[here] = 0;
 			}
 			break;
@@ -185,19 +185,23 @@ void saveIniFile(char *filename) {
 
 void makeLanguageTable(Common::File *table) {
 	languageTable = new int[gameSettings.numLanguages + 1];
-	if (! checkNew(languageTable)) return;
+	if (!checkNew(languageTable))
+		return;
 
 	languageName = new char *[gameSettings.numLanguages + 1];
-	if (! checkNew(languageName)) return;
+	if (!checkNew(languageName))
+		return;
 
-	for (unsigned int i = 0; i <= gameSettings.numLanguages; i ++) {
+	for (unsigned int i = 0; i <= gameSettings.numLanguages; i++) {
 		languageTable[i] = i ? get2bytes(table) : 0;
-		debug(kSludgeDebugDataLoad, "languageTable %i: %i", i, languageTable[i]);
+		debug(kSludgeDebugDataLoad, "languageTable %i: %i", i,
+				languageTable[i]);
 		languageName[i] = 0;
 		if (gameVersion >= VERSION(2, 0)) {
 			if (gameSettings.numLanguages) {
 				languageName[i] = readString(table);
-				debug(kSludgeDebugDataLoad, "languageName %i: %s\n", i, languageName[i]);
+				debug(kSludgeDebugDataLoad, "languageName %i: %s\n", i,
+						languageName[i]);
 			}
 		}
 	}
@@ -206,8 +210,9 @@ void makeLanguageTable(Common::File *table) {
 int getLanguageForFileB() {
 	int indexNum = -1;
 
-	for (unsigned int i = 0; i <= gameSettings.numLanguages; i ++) {
-		if (languageTable[i] == gameSettings.languageID) indexNum = i;
+	for (unsigned int i = 0; i <= gameSettings.numLanguages; i++) {
+		if (languageTable[i] == gameSettings.languageID)
+			indexNum = i;
 	}
 
 	return indexNum;
diff --git a/engines/sludge/line.cpp b/engines/sludge/line.cpp
index bcb1343..1feba03 100644
--- a/engines/sludge/line.cpp
+++ b/engines/sludge/line.cpp
@@ -37,10 +37,10 @@ void drawLine(int x1, int y1, int x2, int y2) {
 	int x, y;
 	bool backwards = false;
 #if 0
-	if (x1 < 0)  x1 = 0;
-	if (y1 < 0)  y1 = 0;
-	if (x2 < 0)  x2 = 0;
-	if (y2 < 0)  y2 = 0;
+	if (x1 < 0) x1 = 0;
+	if (y1 < 0) y1 = 0;
+	if (x2 < 0) x2 = 0;
+	if (y2 < 0) y2 = 0;
 	if (x1 > sceneWidth) x1 = sceneWidth - 1;
 	if (x2 > sceneWidth) x2 = sceneWidth - 1;
 	if (y1 > sceneHeight) y1 = sceneHeight - 1;
@@ -69,10 +69,8 @@ void drawLine(int x1, int y1, int x2, int y2) {
 	}
 	setPixelCoords(true);
 
-
 	glLineWidth(2.0);
 
-
 	int xoffset = 0;
 	while (xoffset < diffX) {
 		int w = (diffX - xoffset < viewportWidth) ? diffX - xoffset : viewportWidth;
@@ -98,7 +96,6 @@ void drawLine(int x1, int y1, int x2, int y2) {
 				backdropTexW, backdropTexH
 			};
 
-
 			glUseProgram(shader.texture);
 
 			setPMVMatrix(shader.texture);
@@ -118,7 +115,6 @@ void drawLine(int x1, int y1, int x2, int y2) {
 				xo2, -yoffset + diffY, 0,
 			};
 
-
 			glUseProgram(shader.color);
 
 			setPMVMatrix(shader.color);
diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index 959885f..125e318 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -78,7 +78,6 @@ extern parallaxLayer *parallaxStuff;                //      "
 extern int lightMapMode;                    //      "
 extern int languageNum;
 
-
 //----------------------------------------------------------------------
 // Globals (so we know what's saved already and what's a reference
 //----------------------------------------------------------------------
@@ -100,7 +99,7 @@ void saveStack(variableStack *vs, Common::WriteStream *stream) {
 
 	variableStack *search = vs;
 	while (search) {
-		elements ++;
+		elements++;
 		search = search->next;
 	}
 
@@ -114,7 +113,8 @@ void saveStack(variableStack *vs, Common::WriteStream *stream) {
 	}
 }
 
-variableStack *loadStack(Common::SeekableReadStream *stream, variableStack **last) {
+variableStack *loadStack(Common::SeekableReadStream *stream,
+		variableStack **last) {
 	int elements = get2bytes(stream);
 	int a;
 	variableStack *first = NULL;
@@ -122,14 +122,15 @@ variableStack *loadStack(Common::SeekableReadStream *stream, variableStack **las
 
 	for (a = 0; a < elements; ++a) {
 		variableStack *nS = new variableStack;
-		if (!checkNew(nS)) return NULL;
+		if (!checkNew(nS))
+			return NULL;
 		loadVariable(&(nS->thisVar), stream);
 		if (last && a == elements - 1) {
 			stackDebug((stackfp, "Setting last to %p\n", nS));
 			*last = nS;
 		}
 		nS->next = NULL;
-		(* changeMe) = nS;
+		(*changeMe) = nS;
 		changeMe = &(nS->next);
 	}
 
@@ -151,8 +152,9 @@ bool saveStackRef(stackHandler *vs, Common::WriteStream *stream) {
 	putch(0, stream);
 	saveStack(vs->first, stream);
 	s = new stackLibrary;
-	stackLibTotal ++;
-	if (! checkNew(s)) return false;
+	stackLibTotal++;
+	if (!checkNew(s))
+		return false;
 	s->next = stackLib;
 	s->stack = vs;
 	stackLib = s;
@@ -173,7 +175,7 @@ stackHandler *getStackFromLibrary(int n) {
 	n = stackLibTotal - n;
 	while (n) {
 		stackLib = stackLib->next;
-		n --;
+		n--;
 	}
 	return stackLib->stack;
 }
@@ -185,14 +187,15 @@ stackHandler *loadStackRef(Common::SeekableReadStream *stream) {
 		stackDebug((stackfp, "loadStackRef (duplicate, get from library)\n"));
 
 		nsh = getStackFromLibrary(get2bytes(stream));
-		nsh->timesUsed ++;
+		nsh->timesUsed++;
 	} else {
 		stackDebug((stackfp, "loadStackRef (new one)\n"));
 
 		// Load the new stack
 
 		nsh = new stackHandler;
-		if (! checkNew(nsh)) return NULL;
+		if (!checkNew(nsh))
+			return NULL;
 		nsh->last = NULL;
 		nsh->first = loadStack(stream, &nsh->last);
 		nsh->timesUsed = 1;
@@ -206,11 +209,12 @@ stackHandler *loadStackRef(Common::SeekableReadStream *stream) {
 		// Add it to the library of loaded stacks
 
 		stackLibrary *s = new stackLibrary;
-		if (! checkNew(s)) return NULL;
+		if (!checkNew(s))
+			return NULL;
 		s->stack = nsh;
 		s->next = stackLib;
 		stackLib = s;
-		stackLibTotal ++;
+		stackLibTotal++;
 	}
 	return nsh;
 }
@@ -257,15 +261,14 @@ bool saveVariable(variable *from, Common::WriteStream *stream) {
 
 	default:
 		fatal("Can't save variables of this type:",
-		      (from->varType < SVT_NUM_TYPES) ?
-		      typeName[from->varType] :
-		      "bad ID");
+				(from->varType < SVT_NUM_TYPES) ?
+						typeName[from->varType] : "bad ID");
 	}
 	return true;
 }
 
 bool loadVariable(variable *to, Common::SeekableReadStream *stream) {
-	to->varType = (variableType)getch(stream);
+	to->varType = (variableType) getch(stream);
 	switch (to->varType) {
 	case SVT_INT:
 	case SVT_FUNC:
@@ -292,13 +295,15 @@ bool loadVariable(variable *to, Common::SeekableReadStream *stream) {
 
 	case SVT_COSTUME:
 		to->varData.costumeHandler = new persona;
-		if (! checkNew(to->varData.costumeHandler)) return false;
+		if (!checkNew(to->varData.costumeHandler))
+			return false;
 		loadCostume(to->varData.costumeHandler, stream);
 		return true;
 
 	case SVT_ANIM:
 		to->varData.animHandler = new personaAnimation;
-		if (! checkNew(to->varData.animHandler)) return false;
+		if (!checkNew(to->varData.animHandler))
+			return false;
 		loadAnim(to->varData.animHandler, stream);
 		return true;
 
@@ -342,7 +347,8 @@ loadedFunction *loadFunction(Common::SeekableReadStream *stream) {
 	// Reserve memory...
 
 	loadedFunction *buildFunc = new loadedFunction;
-	if (! checkNew(buildFunc)) return NULL;
+	if (!checkNew(buildFunc))
+		return NULL;
 
 	// See what it was called by and load if we need to...
 
@@ -350,7 +356,8 @@ loadedFunction *loadFunction(Common::SeekableReadStream *stream) {
 	buildFunc->calledBy = NULL;
 	if (getch(stream)) {
 		buildFunc->calledBy = loadFunction(stream);
-		if (! buildFunc->calledBy) return NULL;
+		if (!buildFunc->calledBy)
+			return NULL;
 	}
 
 	buildFunc->timeLeft = get4bytes(stream);
@@ -396,7 +403,7 @@ bool saveGame(char *fname) {
 
 	fputc(allowAnyFilename, fp);
 	fputc(captureAllKeys, fp);
-	fputc(true, fp);  // updateDisplay
+	fputc(true, fp);// updateDisplay
 	fputc(fontTableSize > 0, fp);
 
 	if (fontTableSize > 0) {
@@ -515,7 +522,7 @@ bool loadGame(char *fname) {
 	}
 
 	if (savedGameTime.dwLowDateTime != fileTime.dwLowDateTime ||
-	        savedGameTime.dwHighDateTime != fileTime.dwHighDateTime) {
+			savedGameTime.dwHighDateTime != fileTime.dwHighDateTime) {
 		return fatal(ERROR_GAME_LOAD_WRONG, fname);
 	}
 
@@ -579,7 +586,6 @@ bool loadGame(char *fname) {
 	loadedFunction *rFunc;
 	loadedFunction * * buildList = &allRunningFunctions;
 
-
 	int countFunctions = get2bytes(fp);
 	while (countFunctions --) {
 		rFunc = loadFunction(fp);
@@ -595,7 +601,6 @@ bool loadGame(char *fname) {
 
 	loadPeople(fp);
 
-
 	if (fgetc(fp)) {
 		if (! setFloor(get2bytes(fp))) return false;
 	} else setFloorNull();
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index 283a228..8496a9b 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -36,7 +36,6 @@
 
 #include <iostream>
 
-
 #include <stdexcept>
 
 #include <time.h>
@@ -159,19 +158,19 @@ void checkInput() {
 	while (SDL_PollEvent(&event)) {
 		switch (event.type) {
 
-		case SDL_VIDEORESIZE:
+			case SDL_VIDEORESIZE:
 			realWinWidth = event.resize.w;
 			realWinHeight = event.resize.h;
 			setGraphicsWindow(false, true, true);
 			break;
 
-		case SDL_MOUSEMOTION:
+			case SDL_MOUSEMOTION:
 			input.justMoved = true;
 			input.mouseX = event.motion.x * ((float)winWidth / cameraZoom) / realWinWidth;
 			input.mouseY = event.motion.y * ((float)winHeight / cameraZoom) / realWinHeight;
 			break;
 
-		case SDL_MOUSEBUTTONDOWN:
+			case SDL_MOUSEBUTTONDOWN:
 			if (event.button.button == SDL_BUTTON_LEFT) {
 				if (SDL_GetModState() & KMOD_CTRL) {
 					input.rightClick = true;
@@ -186,7 +185,7 @@ void checkInput() {
 			input.mouseY = event.motion.y * ((float)winHeight / cameraZoom) / realWinHeight;
 			break;
 
-		case SDL_MOUSEBUTTONUP:
+			case SDL_MOUSEBUTTONUP:
 			if (event.button.button == SDL_BUTTON_LEFT) {
 				if (fakeRightclick) {
 					fakeRightclick = false;
@@ -200,7 +199,7 @@ void checkInput() {
 			input.mouseY = event.motion.y * ((float)winHeight / cameraZoom) / realWinHeight;
 			break;
 
-		case SDL_KEYDOWN:
+			case SDL_KEYDOWN:
 			// A Windows key is pressed - let's leave fullscreen.
 			if (runningFullscreen) {
 				if (event.key.keysym.sym == SDLK_LSUPER || event.key.keysym.sym == SDLK_LSUPER) {
@@ -224,7 +223,7 @@ void checkInput() {
 					break;
 				}
 				// Allow Alt+F4 to quit
-				if (SDLK_F4 ==  event.key.keysym.sym) {
+				if (SDLK_F4 == event.key.keysym.sym) {
 					SDL_Event event;
 					event.type = SDL_QUIT;
 					SDL_PushEvent(&event);
@@ -233,86 +232,86 @@ void checkInput() {
 				break;
 			}
 			switch (event.key.keysym.sym) {
-			case SDLK_BACKSPACE:
-			case SDLK_DELETE:   // Ok, mapping these to the same key is weird, I admit. But good?
+				case SDLK_BACKSPACE:
+				case SDLK_DELETE: // Ok, mapping these to the same key is weird, I admit. But good?
 				input.keyPressed = 127;
 				break;
-			case SDLK_TAB:
+				case SDLK_TAB:
 				input.keyPressed = 9;
 				break;
-			case SDLK_RETURN:
+				case SDLK_RETURN:
 				input.keyPressed = 13;
 				break;
-			case SDLK_ESCAPE:
+				case SDLK_ESCAPE:
 				input.keyPressed = 27;
 				break;
-			case SDLK_PAGEUP:
+				case SDLK_PAGEUP:
 				input.keyPressed = 63276;
 				break;
-			case SDLK_PAGEDOWN:
+				case SDLK_PAGEDOWN:
 				input.keyPressed = 63277;
 				break;
-			case SDLK_END:
+				case SDLK_END:
 				input.keyPressed = 63275;
 				break;
-			case SDLK_HOME:
+				case SDLK_HOME:
 				input.keyPressed = 63273;
 				break;
-			case SDLK_LEFT:
+				case SDLK_LEFT:
 				input.keyPressed = 63234;
 				break;
-			case SDLK_UP:
+				case SDLK_UP:
 				input.keyPressed = 63232;
 				break;
-			case SDLK_RIGHT:
+				case SDLK_RIGHT:
 				input.keyPressed = 63235;
 				break;
-			case SDLK_DOWN:
+				case SDLK_DOWN:
 				input.keyPressed = 63233;
 				break;
-			case SDLK_F1:
+				case SDLK_F1:
 				input.keyPressed = 63236;
 				break;
-			case SDLK_F2:
+				case SDLK_F2:
 				input.keyPressed = 63237;
 				break;
-			case SDLK_F3:
+				case SDLK_F3:
 				input.keyPressed = 63238;
 				break;
-			case SDLK_F4:
+				case SDLK_F4:
 				input.keyPressed = 63239;
 				break;
-			case SDLK_F5:
+				case SDLK_F5:
 				input.keyPressed = 63240;
 				break;
-			case SDLK_F6:
+				case SDLK_F6:
 				input.keyPressed = 63241;
 				break;
-			case SDLK_F7:
+				case SDLK_F7:
 				input.keyPressed = 63242;
 				break;
-			case SDLK_F8:
+				case SDLK_F8:
 				input.keyPressed = 63243;
 				break;
-			case SDLK_F9:
+				case SDLK_F9:
 				input.keyPressed = 63244;
 				break;
-			case SDLK_F10:
+				case SDLK_F10:
 				input.keyPressed = 63245;
 				break;
-			case SDLK_F11:
+				case SDLK_F11:
 				input.keyPressed = 63246;
 				break;
-			case SDLK_F12:
+				case SDLK_F12:
 				input.keyPressed = 63247;
 				break;
-			default:
+				default:
 				input.keyPressed = event.key.keysym.unicode;
 				break;
 			}
 			break;
 
-		case SDL_QUIT:
+			case SDL_QUIT:
 			if (reallyWantToQuit) {
 				// The game file has requested that we quit
 				weAreDoneSoQuit = 1;
@@ -326,7 +325,7 @@ void checkInput() {
 			}
 			break;
 
-		default:
+			default:
 			break;
 		}
 	}
@@ -335,9 +334,9 @@ void checkInput() {
 
 int main_loop(char *filename)
 #if 0
-try
+		try
 #endif
-{
+		{
 	/* Dimensions of our window. */
 	winWidth = 640;
 	winHeight = 480;
@@ -348,7 +347,6 @@ try
 	time_t t;
 	srand((unsigned) time(&t));
 
-
 	// bundleFolder is used to look for the game file
 	// and later to find the shader programs
 #ifdef __APPLE__
@@ -392,11 +390,13 @@ try
 
 	// The player pressed cancel in the file selection dialogue,
 	// so we should quit now.
-	if (!sludgeFile) return 0;
+	if (!sludgeFile)
+		return 0;
 
 	// OK, so we DO want to start up, then...
 	setGameFilePath(sludgeFile);
-	if (!initSludge(sludgeFile)) return 0;
+	if (!initSludge(sludgeFile))
+		return 0;
 
 #if 0
 	/* Initialize the SDL library */
@@ -430,12 +430,16 @@ try
 
 	registerWindowForFatal();
 
-	if (!resizeBackdrop(winWidth, winHeight)) return fatal("Couldn't allocate memory for backdrop");
+	if (!resizeBackdrop(winWidth, winHeight))
+		return fatal("Couldn't allocate memory for backdrop");
 
 	blankScreen(0, 0, winWidth, winHeight);
-	if (!initPeople()) return fatal("Couldn't initialise people stuff");
-	if (!initFloor()) return fatal("Couldn't initialise floor stuff");
-	if (!initObjectTypes()) return fatal("Couldn't initialise object type stuff");
+	if (!initPeople())
+		return fatal("Couldn't initialise people stuff");
+	if (!initFloor())
+		return fatal("Couldn't initialise floor stuff");
+	if (!initObjectTypes())
+		return fatal("Couldn't initialise object type stuff");
 	initSpeech();
 	initStatusBar();
 	resetRandW();
@@ -473,7 +477,9 @@ try
 		walkAllPeople();
 		handleInput();
 		sludgeDisplay();
-		g_system->copyRectToScreen(backdropSurface.getPixels(), backdropSurface.pitch, 0, 0, backdropSurface.w, backdropSurface.h);
+		g_system->copyRectToScreen(backdropSurface.getPixels(),
+				backdropSurface.pitch, 0, 0, backdropSurface.w,
+				backdropSurface.h);
 		g_system->updateScreen();
 #if 0
 		Wait_Frame();
@@ -509,4 +515,5 @@ catch (std::exception &ex) { //NOTE by reference, not value
 }
 #endif
 
-} // End of namespace Sludge
+}
+ // End of namespace Sludge
diff --git a/engines/sludge/memwatch.cpp b/engines/sludge/memwatch.cpp
index 34e8605..f9148c5 100644
--- a/engines/sludge/memwatch.cpp
+++ b/engines/sludge/memwatch.cpp
@@ -43,7 +43,7 @@ void outputKnownMem() {
 
 void adding(void *mem) {
 	allKnownMem[allKnownNum] = mem;
-	allKnownNum ++;
+	allKnownNum++;
 
 	outputKnownMem();
 	if (allKnownNum == 3000) {
@@ -55,8 +55,8 @@ void adding(void *mem) {
 }
 
 void deleting(void *mem) {
-	allKnownNum --;
-	for (int i = 0; i <= allKnownNum; i ++) {
+	allKnownNum--;
+	for (int i = 0; i <= allKnownNum; i++) {
 		if (allKnownMem[i] == mem) {
 			allKnownMem[i] = allKnownMem[allKnownNum];
 			outputKnownMem();
diff --git a/engines/sludge/moreio.cpp b/engines/sludge/moreio.cpp
index 8bb0d77..754f22c 100644
--- a/engines/sludge/moreio.cpp
+++ b/engines/sludge/moreio.cpp
@@ -58,8 +58,8 @@ int get2bytes(Common::SeekableReadStream *stream) {
 }
 
 void put2bytes(int numtoput, Common::WriteStream *stream) {
-	putch((char)(numtoput / 256), stream);
-	putch((char)(numtoput % 256), stream);
+	putch((char) (numtoput / 256), stream);
+	putch((char) (numtoput % 256), stream);
 }
 
 void writeString(char *s, Common::WriteStream *stream) {
@@ -70,7 +70,6 @@ void writeString(char *s, Common::WriteStream *stream) {
 	}
 }
 
-
 char *readString(Common::SeekableReadStream *stream) {
 	int a, len = get2bytes(stream);
 	char *s = new char[len + 1];
@@ -78,7 +77,7 @@ char *readString(Common::SeekableReadStream *stream) {
 		return NULL;
 	}
 	for (a = 0; a < len; ++a) {
-		s[a] = (char)(getch(stream) - 1);
+		s[a] = (char) (getch(stream) - 1);
 	}
 	s[len] = 0;
 	debug(kSludgeDebugDataLoad, "Read string of length %i: %s", len, s);
@@ -99,11 +98,10 @@ float floatSwap(float f) {
 	return dat2.f;
 }
 
-
 float getFloat(Common::SeekableReadStream *stream) {
 	float f;
 	size_t bytes_read = stream->read(&f, sizeof(float));
-			//fread(& f, sizeof(float), 1, fp);
+	//fread(& f, sizeof(float), 1, fp);
 	if (bytes_read != sizeof(float) && stream->err()) {
 		debug("Reading error in getFloat.\n");
 	}
@@ -119,7 +117,7 @@ void putFloat(float f, Common::WriteStream *stream) {
 #ifdef  __BIG_ENDIAN__
 	f = floatSwap(f);
 #endif
-	stream->write(&f,sizeof(float));
+	stream->write(&f, sizeof(float));
 	//fwrite(& f, sizeof(float), 1, fp);
 }
 
@@ -132,7 +130,6 @@ short shortSwap(short s) {
 	return (b1 << 8) + b2;
 }
 
-
 short getSigned(Common::SeekableReadStream *stream) {
 	short f;
 	size_t bytes_read = stream->read(&f, sizeof(short));
@@ -152,7 +149,6 @@ void putSigned(short f, Common::WriteStream *stream) {
 	stream->write(&f, sizeof(short));
 }
 
-
 // The following two functions treat signed integers as unsigned.
 // That's done on purpose.
 
@@ -169,7 +165,6 @@ int32_t get4bytes(Common::SeekableReadStream *stream) {
 	return x;
 }
 
-
 void put4bytes(unsigned int i, Common::WriteStream *stream) {
 	unsigned char f1, f2, f3, f4;
 
@@ -187,10 +182,12 @@ void put4bytes(unsigned int i, Common::WriteStream *stream) {
 }
 
 char *encodeFilename(char *nameIn) {
-	if (!nameIn) return NULL;
+	if (!nameIn)
+		return NULL;
 	if (allowAnyFilename) {
 		char *newName = new char[strlen(nameIn) * 2 + 1];
-		if (!checkNew(newName)) return NULL;
+		if (!checkNew(newName))
+			return NULL;
 
 		int i = 0;
 		while (*nameIn) {
@@ -241,7 +238,7 @@ char *encodeFilename(char *nameIn) {
 				break;
 			}
 			newName[i] = 0;
-			nameIn ++;
+			nameIn++;
 		}
 		return newName;
 	} else {
@@ -250,7 +247,8 @@ char *encodeFilename(char *nameIn) {
 #ifdef _WIN32
 			if (nameIn[a] == '/') nameIn[a] = '\\';
 #else
-			if (nameIn[a] == '\\') nameIn[a] = '/';
+			if (nameIn[a] == '\\')
+				nameIn[a] = '/';
 #endif
 		}
 
@@ -261,61 +259,62 @@ char *encodeFilename(char *nameIn) {
 char *decodeFilename(char *nameIn) {
 	if (allowAnyFilename) {
 		char *newName = new char[strlen(nameIn) + 1];
-		if (!checkNew(newName)) return NULL;
+		if (!checkNew(newName))
+			return NULL;
 
 		int i = 0;
-		while (* nameIn) {
-			if (* nameIn == '_') {
-				nameIn ++;
-				switch (* nameIn) {
+		while (*nameIn) {
+			if (*nameIn == '_') {
+				nameIn++;
+				switch (*nameIn) {
 				case 'L':
 					newName[i] = '<';
-					nameIn ++;
+					nameIn++;
 					break;
 				case 'G':
 					newName[i] = '>';
-					nameIn ++;
+					nameIn++;
 					break;
 				case 'P':
 					newName[i] = '|';
-					nameIn ++;
+					nameIn++;
 					break;
 				case 'U':
 					newName[i] = '_';
-					nameIn ++;
+					nameIn++;
 					break;
 				case 'S':
 					newName[i] = '\"';
-					nameIn ++;
+					nameIn++;
 					break;
 				case 'B':
 					newName[i] = '\\';
-					nameIn ++;
+					nameIn++;
 					break;
 				case 'F':
 					newName[i] = '/';
-					nameIn ++;
+					nameIn++;
 					break;
 				case 'C':
 					newName[i] = ':';
-					nameIn ++;
+					nameIn++;
 					break;
 				case 'A':
 					newName[i] = '*';
-					nameIn ++;
+					nameIn++;
 					break;
 				case 'Q':
 					newName[i] = '?';
-					nameIn ++;
+					nameIn++;
 					break;
 				default:
 					newName[i] = '_';
 				}
 			} else {
 				newName[i] = *nameIn;
-				nameIn ++;
+				nameIn++;
 			}
-			i ++;
+			i++;
 
 		}
 		newName[i] = 0;
diff --git a/engines/sludge/movie.cpp b/engines/sludge/movie.cpp
index 3f02f73..cd4ef1b 100644
--- a/engines/sludge/movie.cpp
+++ b/engines/sludge/movie.cpp
@@ -71,7 +71,7 @@ bool handleInput();
 void playMovieStream(int a);
 #if 0
 int initMovieSound(int f, ALenum format, int audioChannels, ALuint samplerate,
-                   ALuint(*callback)(void *userdata, ALubyte *data, ALuint bytes));
+		ALuint(*callback)(void *userdata, ALubyte *data, ALuint bytes));
 #endif
 
 movieStates movieIsPlaying = nothing;
@@ -85,14 +85,14 @@ typedef struct audioBuffers {
 	unsigned int size;
 	audioBuffers *next;
 	Uint32 time_ms;
-} audioBuffers;
+}audioBuffers;
 
 typedef struct audioQueue {
 	audioBuffers *first, *last;
 	int size;
 	SDL_mutex *mutex;
 	SDL_cond *cond;
-} audioQueue;
+}audioQueue;
 
 audioQueue audioQ;
 
@@ -115,18 +115,17 @@ typedef struct videoBuffers {
 	videoBuffers *next;
 	GLsizei w, h;
 	Uint32 time_ms;
-} videoBuffers;
+}videoBuffers;
 
 typedef struct videoQueue {
 	videoBuffers *first, *last;
 	int size;
 	SDL_mutex *mutex;
 	SDL_cond *cond;
-} videoQueue;
+}videoQueue;
 
 videoQueue videoQ;
 
-
 void audio_queue_init(audioQueue *q) {
 	memset(q, 0, sizeof(audioQueue));
 
@@ -138,7 +137,7 @@ int audio_queue_put(audioQueue *q, char *buffer, unsigned int size, long long ti
 
 	audioBuffers *audioBuf = new audioBuffers;
 	if (!audioBuf)
-		return -1;
+	return -1;
 	audioBuf->buffer = buffer;
 	audioBuf->next = NULL;
 	audioBuf->size = size;
@@ -147,9 +146,9 @@ int audio_queue_put(audioQueue *q, char *buffer, unsigned int size, long long ti
 	SDL_LockMutex(q->mutex);
 
 	if (!q->last)
-		q->first = audioBuf;
+	q->first = audioBuf;
 	else
-		q->last->next = audioBuf;
+	q->last->next = audioBuf;
 	q->last = audioBuf;
 	q->size ++;
 	SDL_CondSignal(q->cond);
@@ -161,7 +160,6 @@ int audio_queue_put(audioQueue *q, char *buffer, unsigned int size, long long ti
 inline static int audio_queue_get(audioQueue *q, char **buffer) {
 	int ret = 0;
 
-
 	audioBuffers *audioBuf;
 
 	SDL_LockMutex(q->mutex);
@@ -176,7 +174,7 @@ inline static int audio_queue_get(audioQueue *q, char **buffer) {
 
 		q->first = audioBuf->next;
 		if (!q->first)
-			q->last = NULL;
+		q->last = NULL;
 		q->size--;
 		*buffer = audioBuf->buffer;
 		ret = audioBuf->size;
@@ -194,14 +192,14 @@ void video_queue_init(videoQueue *q) {
 	q->cond = SDL_CreateCond();
 }
 int video_queue_put(videoQueue *q, GLubyte *ytex,
-                    GLubyte *utex,
-                    GLubyte *vtex,
-                    GLsizei w, GLsizei h,
-                    long long time_ms) {
+		GLubyte *utex,
+		GLubyte *vtex,
+		GLsizei w, GLsizei h,
+		long long time_ms) {
 
 	videoBuffers *videoBuf = new videoBuffers;
 	if (!videoBuf)
-		return -1;
+	return -1;
 	videoBuf->ytex = ytex;
 	videoBuf->utex = utex;
 	videoBuf->vtex = vtex;
@@ -213,9 +211,9 @@ int video_queue_put(videoQueue *q, GLubyte *ytex,
 	SDL_LockMutex(q->mutex);
 
 	if (!q->last)
-		q->first = videoBuf;
+	q->first = videoBuf;
 	else
-		q->last->next = videoBuf;
+	q->last->next = videoBuf;
 	q->last = videoBuf;
 	q->size ++;
 	SDL_CondSignal(q->cond);
@@ -224,10 +222,10 @@ int video_queue_put(videoQueue *q, GLubyte *ytex,
 	return 0;
 }
 inline static int video_queue_get(videoQueue *q,
-                                  GLubyte **ytex,
-                                  GLubyte **utex,
-                                  GLubyte **vtex,
-                                  GLsizei *w, GLsizei *h) {
+		GLubyte **ytex,
+		GLubyte **utex,
+		GLubyte **vtex,
+		GLsizei *w, GLsizei *h) {
 	videoBuffers *videoBuf;
 	int ret = 0;
 
@@ -237,7 +235,7 @@ inline static int video_queue_get(videoQueue *q,
 	if (videoBuf) {
 		q->first = videoBuf->next;
 		if (!q->first)
-			q->last = NULL;
+		q->last = NULL;
 		q->size--;
 		*ytex = videoBuf->ytex;
 		*utex = videoBuf->utex;
@@ -279,10 +277,10 @@ void setMovieViewport() {
 	glViewport(vpOffsetX, vpOffsetY, vpWidth, vpHeight);
 #endif
 	const GLfloat bPMVMatrix[] = {
-		2.0f / 640.f,          .0,   .0,  .0,
-		.0, -2.0f / 400.f,   .0,  .0,
-		.0,          .0, 1.0f,  .0,
-		-1.0,        1.0f,   .0, 1.0f
+		2.0f / 640.f, .0, .0, .0,
+		.0, -2.0f / 400.f, .0, .0,
+		.0, .0, 1.0f, .0,
+		-1.0, 1.0f, .0, 1.0f
 
 	};
 	for (int i = 0; i < 16; i++) {
@@ -341,9 +339,9 @@ ALuint feedAudio(void *userdata, ALubyte *data, ALuint length) {
 	fakeAudio = false;
 
 	if (length > bufSize - bufOffset)
-		bufLen = bufSize - bufOffset;
+	bufLen = bufSize - bufOffset;
 	else
-		bufLen = length;
+	bufLen = length;
 
 	memcpy(data, buffer + bufOffset, bufLen);
 
@@ -364,13 +362,13 @@ ALuint feedAudio(void *userdata, ALubyte *data, ALuint length) {
 int playMovie(int fileNumber) {
 #if 0
 	if (specialSettings & SPECIAL_SILENT)
-		return 0;
+	return 0;
 
 	if (movieIsPlaying) return 0;
 
 	movieSoundPlaying = false;
 
-	vpx_codec_ctx_t  codec;
+	vpx_codec_ctx_t codec;
 
 	float pausefade = 1.0;
 
@@ -396,7 +394,7 @@ int playMovie(int fileNumber) {
 		fatal("Movie error: Segment::CreateInstance() failed.\n");
 	}
 
-	ret  = pSegment->Load();
+	ret = pSegment->Load();
 	if (ret < 0) {
 		fatal("Movie error: Segment::Load() failed.\n");
 	}
@@ -413,7 +411,7 @@ int playMovie(int fileNumber) {
 	unsigned long i = 0;
 	const unsigned long j = pTracks->GetTracksCount();
 
-	enum { VIDEO_TRACK = 1, AUDIO_TRACK = 2 };
+	enum {VIDEO_TRACK = 1, AUDIO_TRACK = 2};
 	int videoTrack = -1;
 	int audioTrack = -1;
 	long long audioBitDepth;
@@ -427,7 +425,7 @@ int playMovie(int fileNumber) {
 		const Track *const pTrack = pTracks->GetTrackByIndex(i++);
 
 		if (pTrack == NULL)
-			continue;
+		continue;
 
 		const long long trackType = pTrack->GetType();
 		//const unsigned long long trackUid = pTrack->GetUid();
@@ -436,15 +434,15 @@ int playMovie(int fileNumber) {
 		if (trackType == VIDEO_TRACK && videoTrack < 0) {
 			videoTrack = pTrack->GetNumber();
 			const VideoTrack *const pVideoTrack =
-			    static_cast<const VideoTrack *>(pTrack);
+			static_cast<const VideoTrack *>(pTrack);
 
-			const long long width =  pVideoTrack->GetWidth();
+			const long long width = pVideoTrack->GetWidth();
 			const long long height = pVideoTrack->GetHeight();
 
 			const double rate = pVideoTrack->GetFrameRate();
 
 			if (rate > 0)
-				Init_Special_Timer(rate);
+			Init_Special_Timer(rate);
 
 			movieAspect = (float)width / height;
 		}
@@ -452,9 +450,9 @@ int playMovie(int fileNumber) {
 		if (trackType == AUDIO_TRACK && audioTrack < 0) {
 			audioTrack = pTrack->GetNumber();
 			const AudioTrack *const pAudioTrack =
-			    static_cast<const AudioTrack *>(pTrack);
+			static_cast<const AudioTrack *>(pTrack);
 
-			audioChannels =  pAudioTrack->GetChannels();
+			audioChannels = pAudioTrack->GetChannels();
 			audioBitDepth = pAudioTrack->GetBitDepth();
 			audioSampleRate = pAudioTrack->GetSamplingRate();
 
@@ -503,17 +501,17 @@ int playMovie(int fileNumber) {
 				oggPacket.b_o_s = oggPacket.packetno == 0;
 				r = vorbis_synthesis_headerin(&vorbisInfo, &vorbisComment, &oggPacket);
 				if (r)
-					fprintf(stderr, "vorbis_synthesis_headerin failed, error: %d", r);
+				fprintf(stderr, "vorbis_synthesis_headerin failed, error: %d", r);
 				oggPacket.packetno++;
 				p += sizes[i];
 			}
 
 			r = vorbis_synthesis_init(&vorbisDspState, &vorbisInfo);
 			if (r)
-				fprintf(stderr, "vorbis_synthesis_init failed, error: %d", r);
+			fprintf(stderr, "vorbis_synthesis_init failed, error: %d", r);
 			r = vorbis_block_init(&vorbisDspState, &vorbisBlock);
 			if (r)
-				fprintf(stderr, "vorbis_block_init failed, error: %d", r);
+			fprintf(stderr, "vorbis_block_init failed, error: %d", r);
 
 			ALenum audioFormat = alureGetSampleFormat(audioChannels, 16, 0);
 			movieAudioIndex = initMovieSound(fileNumber, audioFormat, audioChannels, (ALuint) audioSampleRate, feedAudio);
@@ -527,10 +525,10 @@ int playMovie(int fileNumber) {
 	}
 
 	if (videoTrack < 0)
-		fatal("Movie error: No video in movie file.");
+	fatal("Movie error: No video in movie file.");
 
 	if (audioTrack < 0)
-		fatal("Movie error: No sound found.");
+	fatal("Movie error: No sound found.");
 
 	video_queue_init(&videoQ);
 
@@ -540,11 +538,9 @@ int playMovie(int fileNumber) {
 		fatal("Movie error: Segment has no clusters.\n");
 	}
 
-
 	/* Initialize video codec */
 	if (vpx_codec_dec_init(&codec, interface, NULL, 0))
-		die_codec(&codec, "Failed to initialize decoder for movie.");
-
+	die_codec(&codec, "Failed to initialize decoder for movie.");
 
 	unsigned char *frame = new unsigned char[256 * 1024];
 	if (! checkNew(frame)) return false;
@@ -571,7 +567,7 @@ int playMovie(int fileNumber) {
 		}
 		pBlockEntry = pCluster->GetFirst();
 	}
-	const Block *pBlock  = pBlockEntry->GetBlock();
+	const Block *pBlock = pBlockEntry->GetBlock();
 	long long trackNum = pBlock->GetTrackNumber();
 	unsigned long tn = static_cast<unsigned long>(trackNum);
 	const Track *pTrack = pTracks->GetTrackByNumber(tn);
@@ -634,7 +630,7 @@ int playMovie(int fileNumber) {
 
 		checkInput();
 		if (weAreDoneSoQuit)
-			break;
+		break;
 		handleInput();
 
 		if (movieIsPlaying && (! movieIsEnding) && (videoQ.size < 100 || audioQ.size < 100)) {
@@ -652,7 +648,7 @@ int playMovie(int fileNumber) {
 						}
 						pBlockEntry = pCluster->GetFirst();
 					}
-					pBlock  = pBlockEntry->GetBlock();
+					pBlock = pBlockEntry->GetBlock();
 					trackNum = pBlock->GetTrackNumber();
 					tn = static_cast<unsigned long>(trackNum);
 					pTrack = pTracks->GetTrackByNumber(tn);
@@ -673,28 +669,27 @@ int playMovie(int fileNumber) {
 					if (! checkNew(frame)) return 0;
 				}
 				/*
-				                fprintf (stderr, "Block :%s,%s,%15lld\n",
-				                 (trackType == VIDEO_TRACK) ? "V" : "A",
-				                 pBlock->IsKey() ? "I" : "P",
-				                 time_ns);
+				 fprintf (stderr, "Block :%s,%s,%15lld\n",
+				 (trackType == VIDEO_TRACK) ? "V" : "A",
+				 pBlock->IsKey() ? "I" : "P",
+				 time_ns);
 				 */
 
 				if (trackNum == videoTrack) {
 
 					theFrame.Read(&reader, frame);
 
-
 					/* Decode the frame */
 					if (vpx_codec_decode(&codec, frame, size, NULL, 0))
-						die_codec(&codec, "Failed to decode frame");
+					die_codec(&codec, "Failed to decode frame");
 
 					// Let's decode an image frame!
-					vpx_codec_iter_t  iter = NULL;
-					vpx_image_t      *img;
+					vpx_codec_iter_t iter = NULL;
+					vpx_image_t *img;
 					/* Get frame data */
 					while ((img = vpx_codec_get_frame(&codec, &iter))) {
 						if (img->fmt != VPX_IMG_FMT_I420)
-							fatal("Movie error. The movie is not in I420 colour format, which is the only one I can hanlde at the moment.");
+						fatal("Movie error. The movie is not in I420 colour format, which is the only one I can hanlde at the moment.");
 
 						unsigned int y;
 
@@ -707,7 +702,7 @@ int playMovie(int fileNumber) {
 							utex = new GLubyte [(img->d_w >> 1) * (img->d_h >> 1)];
 							vtex = new GLubyte [(img->d_w >> 1) * (img->d_h >> 1)];
 							if (!ytex || !utex || !vtex)
-								fatal(ERROR_OUT_OF_MEMORY);
+							fatal(ERROR_OUT_OF_MEMORY);
 
 						}
 
@@ -728,8 +723,7 @@ int playMovie(int fileNumber) {
 						}
 
 						video_queue_put(&videoQ, ytex, utex, vtex,
-						                img->d_w, img->d_h, time_ns / 1000000);
-
+								img->d_w, img->d_h, time_ns / 1000000);
 
 					}
 
@@ -744,7 +738,7 @@ int playMovie(int fileNumber) {
 						oggPacket.granulepos = -1;
 						if (! vorbis_synthesis(&vorbisBlock, &oggPacket)) {
 							if (vorbis_synthesis_blockin(&vorbisDspState, &vorbisBlock))
-								fprintf(stderr, "Vorbis Synthesis block in error.\n");
+							fprintf(stderr, "Vorbis Synthesis block in error.\n");
 
 						} else {
 							fprintf(stderr, "Vorbis Synthesis error.\n");
@@ -771,12 +765,12 @@ int playMovie(int fileNumber) {
 									int off = (sgned ? 0 : 128);
 									vorbis_fpu_setround(&fpu);
 									for (j = 0; j < numSamples; j++)
-										for (i = 0; i < audioChannels; i++) {
-											val = vorbis_ftoi(pcm[i][j] * 128.f);
-											if (val > 127)val = 127;
-											else if (val < -128)val = -128;
-											*buffer++ = val + off;
-										}
+									for (i = 0; i < audioChannels; i++) {
+										val = vorbis_ftoi(pcm[i][j] * 128.f);
+										if (val > 127)val = 127;
+										else if (val < -128)val = -128;
+										*buffer++ = val + off;
+									}
 									vorbis_fpu_restore(fpu);
 								} else {
 									int off = (sgned ? 0 : 32768);
@@ -835,7 +829,7 @@ int playMovie(int fileNumber) {
 				++frameCounter;
 
 			} else {
-movieHasEnded:
+				movieHasEnded:
 				movieIsEnding = 1;
 			}
 		}
@@ -865,30 +859,29 @@ movieHasEnded:
 						if (! vTextureName) glGenTextures(1, &vTextureName);
 						glBindTexture(GL_TEXTURE_2D, yTextureName);
 						glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0,
-						             GL_ALPHA, GL_UNSIGNED_BYTE, ytex);
+								GL_ALPHA, GL_UNSIGNED_BYTE, ytex);
 						glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
 						glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
 						glBindTexture(GL_TEXTURE_2D, uTextureName);
 						glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w >> 1, h >> 1, 0,
-						             GL_ALPHA, GL_UNSIGNED_BYTE, utex);
+								GL_ALPHA, GL_UNSIGNED_BYTE, utex);
 						glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
 						glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
 						glBindTexture(GL_TEXTURE_2D, vTextureName);
 						glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w >> 1, h >> 1, 0,
-						             GL_ALPHA, GL_UNSIGNED_BYTE, vtex);
+								GL_ALPHA, GL_UNSIGNED_BYTE, vtex);
 						glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
 						glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
 
-
 						glBindTexture(GL_TEXTURE_2D, yTextureName);
 						glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h,
-						                GL_ALPHA, GL_UNSIGNED_BYTE, ytex);
+								GL_ALPHA, GL_UNSIGNED_BYTE, ytex);
 						glBindTexture(GL_TEXTURE_2D, uTextureName);
 						glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w >> 1, h >> 1,
-						                GL_ALPHA, GL_UNSIGNED_BYTE, utex);
+								GL_ALPHA, GL_UNSIGNED_BYTE, utex);
 						glBindTexture(GL_TEXTURE_2D, vTextureName);
 						glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w >> 1, h >> 1,
-						                GL_ALPHA, GL_UNSIGNED_BYTE, vtex);
+								GL_ALPHA, GL_UNSIGNED_BYTE, vtex);
 
 						delete [] ytex;
 						delete [] utex;
@@ -946,7 +939,6 @@ movieHasEnded:
 
 				glUseProgram(0);
 
-
 				glDisable(GL_BLEND);
 
 				Wait_Frame();
@@ -971,10 +963,8 @@ movieHasEnded:
 	for (int i = 0; i < 10; i++) Wait_Frame();
 	huntKillFreeSound(fileNumber);
 
-
 	if (vpx_codec_destroy(&codec))
-		die_codec(&codec, "Failed to destroy codec");
-
+	die_codec(&codec, "Failed to destroy codec");
 
 	vorbis_dsp_clear(&vorbisDspState);
 	vorbis_block_clear(&vorbisBlock);
diff --git a/engines/sludge/movie.h b/engines/sludge/movie.h
index 100439a..c34322f 100644
--- a/engines/sludge/movie.h
+++ b/engines/sludge/movie.h
@@ -28,9 +28,7 @@ namespace Sludge {
  movieIsPlaying tracks the state of movie playing
  */
 enum movieStates {
-	nothing = 0,
-	playing,
-	paused
+	nothing = 0, playing, paused
 };
 extern movieStates movieIsPlaying;
 
diff --git a/engines/sludge/newfatal.cpp b/engines/sludge/newfatal.cpp
index 5c8a36d..477a7f9 100644
--- a/engines/sludge/newfatal.cpp
+++ b/engines/sludge/newfatal.cpp
@@ -41,7 +41,9 @@ namespace Sludge {
 const char emergencyMemoryMessage[] = "Out of memory displaying error message!";
 
 static char *fatalMessage = NULL;
-static char *fatalInfo = joinStrings("Initialisation error! Something went wrong before we even got started!", "");
+static char *fatalInfo =
+		joinStrings("Initialisation error! Something went wrong before we even got started!",
+					"");
 
 extern int numResourceNames /* = 0*/;
 extern char * *allResourceNames /*= NULL*/;
@@ -49,14 +51,18 @@ extern char * *allResourceNames /*= NULL*/;
 int resourceForFatal = -1;
 
 const char *resourceNameFromNum(int i) {
-	if (i == -1) return NULL;
-	if (numResourceNames == 0) return "RESOURCE";
-	if (i < numResourceNames) return allResourceNames[i];
+	if (i == -1)
+		return NULL;
+	if (numResourceNames == 0)
+		return "RESOURCE";
+	if (i < numResourceNames)
+		return allResourceNames[i];
 	return "Unknown resource";
 }
 
 bool hasFatal() {
-	if (fatalMessage) return true;
+	if (fatalMessage)
+		return true;
 	return false;
 }
 
@@ -77,7 +83,10 @@ void warning(const char *l) {
 
 void registerWindowForFatal() {
 	delete fatalInfo;
-	fatalInfo = joinStrings("There's an error with this SLUDGE game! If you're designing this game, please turn on verbose error messages in the project manager and recompile. If not, please contact the author saying where and how this problem occured.", "");
+	fatalInfo =
+			joinStrings(
+					"There's an error with this SLUDGE game! If you're designing this game, please turn on verbose error messages in the project manager and recompile. If not, please contact the author saying where and how this problem occured.",
+					"");
 }
 
 #if 0
@@ -93,8 +102,8 @@ int inFatal(const char *str) {
 	}
 #endif
 	fatalMessage = copyString(str);
-	if (fatalMessage == NULL) fatalMessage = copyString("Out of memory");
-
+	if (fatalMessage == NULL)
+		fatalMessage = copyString("Out of memory");
 
 	killSoundStuff();
 
@@ -120,8 +129,10 @@ int checkNew(const void *mem) {
 
 void setFatalInfo(const char *userFunc, const char *BIF) {
 	delete fatalInfo;
-	fatalInfo = new char [strlen(userFunc) + strlen(BIF) + 38];
-	if (fatalInfo) sprintf(fatalInfo, "Currently in this sub: %s\nCalling: %s", userFunc, BIF);
+	fatalInfo = new char[strlen(userFunc) + strlen(BIF) + 38];
+	if (fatalInfo)
+		sprintf(fatalInfo, "Currently in this sub: %s\nCalling: %s", userFunc,
+				BIF);
 	debug("%s", fatalInfo);
 }
 
@@ -132,17 +143,20 @@ void setResourceForFatal(int n) {
 int fatal(const char *str1) {
 	if (numResourceNames && resourceForFatal != -1) {
 		const char *r = resourceNameFromNum(resourceForFatal);
-		char *newStr = new char[strlen(str1) + strlen(r) + strlen(fatalInfo) + 14];
+		char *newStr = new char[strlen(str1) + strlen(r) + strlen(fatalInfo)
+				+ 14];
 		if (checkNew(newStr)) {
 			sprintf(newStr, "%s\nResource: %s\n\n%s", fatalInfo, r, str1);
 			inFatal(newStr);
-		} else fatal(emergencyMemoryMessage);
+		} else
+			fatal(emergencyMemoryMessage);
 	} else {
 		char *newStr = new char[strlen(str1) + strlen(fatalInfo) + 3];
 		if (checkNew(newStr)) {
 			sprintf(newStr, "%s\n\n%s", fatalInfo, str1);
 			inFatal(newStr);
-		} else fatal(emergencyMemoryMessage);
+		} else
+			fatal(emergencyMemoryMessage);
 	}
 	return 0;
 }
@@ -152,7 +166,8 @@ int fatal(const char *str1, const char *str2) {
 	if (checkNew(newStr)) {
 		sprintf(newStr, "%s %s", str1, str2);
 		fatal(newStr);
-	} else fatal(emergencyMemoryMessage);
+	} else
+		fatal(emergencyMemoryMessage);
 	return 0;
 }
 
diff --git a/engines/sludge/objtypes.cpp b/engines/sludge/objtypes.cpp
index ba70977..5f82fb0 100644
--- a/engines/sludge/objtypes.cpp
+++ b/engines/sludge/objtypes.cpp
@@ -42,8 +42,9 @@ objectType *findObjectType(int i) {
 	objectType *huntType = allObjectTypes;
 
 	while (huntType) {
-		if (huntType -> objectNum == i) return huntType;
-		huntType = huntType -> next;
+		if (huntType->objectNum == i)
+			return huntType;
+		huntType = huntType->next;
 	}
 
 	return loadObjectType(i);
@@ -56,13 +57,13 @@ objectType *loadObjectType(int i) {
 	if (checkNew(newType)) {
 		if (openObjectSlice(i)) {
 			nameNum = get2bytes(bigDataFile);
-			newType -> r = (byte) getch(bigDataFile);
-			newType -> g = (byte) getch(bigDataFile);
-			newType -> b = (byte) getch(bigDataFile);
-			newType -> speechGap = getch(bigDataFile);
-			newType -> walkSpeed = getch(bigDataFile);
-			newType -> wrapSpeech = get4bytes(bigDataFile);
-			newType -> spinSpeed = get2bytes(bigDataFile);
+			newType->r = (byte) getch(bigDataFile);
+			newType->g = (byte) getch(bigDataFile);
+			newType->b = (byte) getch(bigDataFile);
+			newType->speechGap = getch(bigDataFile);
+			newType->walkSpeed = getch(bigDataFile);
+			newType->wrapSpeech = get4bytes(bigDataFile);
+			newType->spinSpeed = get2bytes(bigDataFile);
 
 			if (gameVersion >= VERSION(1, 6)) {
 				// aaLoad
@@ -72,13 +73,14 @@ objectType *loadObjectType(int i) {
 			}
 
 			if (gameVersion >= VERSION(1, 4)) {
-				newType -> flags = get2bytes(bigDataFile);
+				newType->flags = get2bytes(bigDataFile);
 			} else {
-				newType -> flags = 0;
+				newType->flags = 0;
 			}
 
-			newType -> numCom = get2bytes(bigDataFile);
-			newType -> allCombis = (newType -> numCom) ? new combination[newType -> numCom] : NULL;
+			newType->numCom = get2bytes(bigDataFile);
+			newType->allCombis =
+					(newType->numCom) ? new combination[newType->numCom] : NULL;
 
 #if DEBUG_COMBINATIONS
 			FILE *callEventLog = fopen("callEventLog.txt", "at");
@@ -87,9 +89,9 @@ objectType *loadObjectType(int i) {
 			}
 #endif
 
-			for (a = 0; a < newType -> numCom; a ++) {
-				newType -> allCombis[a].withObj = get2bytes(bigDataFile);
-				newType -> allCombis[a].funcNum = get2bytes(bigDataFile);
+			for (a = 0; a < newType->numCom; a++) {
+				newType->allCombis[a].withObj = get2bytes(bigDataFile);
+				newType->allCombis[a].funcNum = get2bytes(bigDataFile);
 #if DEBUG_COMBINATIONS
 				if (callEventLog) {
 					fprintf(callEventLog, "%d(%d) ", newType -> allCombis[a].withObj, newType -> allCombis[a].funcNum);
@@ -103,9 +105,9 @@ objectType *loadObjectType(int i) {
 			}
 #endif
 			finishAccess();
-			newType -> screenName = getNumberedString(nameNum);
-			newType -> objectNum = i;
-			newType -> next = allObjectTypes;
+			newType->screenName = getNumberedString(nameNum);
+			newType->objectNum = i;
+			newType->next = allObjectTypes;
 			allObjectTypes = newType;
 			return newType;
 		}
@@ -116,14 +118,14 @@ objectType *loadObjectType(int i) {
 
 objectType *loadObjectRef(Common::SeekableReadStream *stream) {
 	objectType *r = loadObjectType(get2bytes(stream));
-	delete r -> screenName;
-	r -> screenName = readString(stream);
+	delete r->screenName;
+	r->screenName = readString(stream);
 	return r;
 }
 
 void saveObjectRef(objectType *r, Common::WriteStream *stream) {
-	put2bytes(r -> objectNum, stream);
-	writeString(r -> screenName, stream);
+	put2bytes(r->objectNum, stream);
+	writeString(r->screenName, stream);
 }
 
 int getCombinationFunction(int withThis, int thisObject) {
@@ -137,9 +139,9 @@ int getCombinationFunction(int withThis, int thisObject) {
 	}
 #endif
 
-	for (i = 0; i < obj -> numCom; i ++) {
-		if (obj -> allCombis[i].withObj == withThis) {
-			num = obj -> allCombis[i].funcNum;
+	for (i = 0; i < obj->numCom; i++) {
+		if (obj->allCombis[i].withObj == withThis) {
+			num = obj->allCombis[i].funcNum;
 			break;
 		}
 	}
@@ -155,21 +157,21 @@ int getCombinationFunction(int withThis, int thisObject) {
 }
 
 void removeObjectType(objectType *oT) {
-	objectType * * huntRegion = & allObjectTypes;
+	objectType * * huntRegion = &allObjectTypes;
 
-	while (* huntRegion) {
-		if ((* huntRegion) == oT) {
+	while (*huntRegion) {
+		if ((*huntRegion) == oT) {
 //			FILE * debuggy2 = fopen ("debug.txt", "at");
 //			fprintf (debuggy2, "DELETING OBJECT TYPE: %p %s\n", oT, oT -> screenName);
 //			fclose (debuggy2);
 
-			* huntRegion = oT -> next;
-			delete oT -> allCombis;
-			delete oT -> screenName;
+			*huntRegion = oT->next;
+			delete oT->allCombis;
+			delete oT->screenName;
 			delete oT;
 			return;
 		} else {
-			huntRegion = & ((* huntRegion) -> next);
+			huntRegion = &((*huntRegion)->next);
 		}
 	}
 	fatal("Can't delete object type: bad pointer");
diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index 6430d35..93f1d6c 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -71,7 +71,8 @@ inline int TF_abs(int a) {
 }
 
 void setFrames(onScreenPerson &m, int a) {
-	m.myAnim = m.myPersona->animation[(a * m.myPersona->numDirections) + m.direction];
+	m.myAnim = m.myPersona->animation[(a * m.myPersona->numDirections)
+			+ m.direction];
 }
 
 personaAnimation *createPersonaAnim(int num, variableStack *&stacky) {
@@ -85,15 +86,17 @@ personaAnimation *createPersonaAnim(int num, variableStack *&stacky) {
 	int a = num, frameNum, howMany;
 
 	while (a) {
-		a --;
+		a--;
 		newP->frames[a].noise = 0;
 		if (stacky->thisVar.varType == SVT_FILE) {
 			newP->frames[a].noise = stacky->thisVar.varData.intValue;
 		} else if (stacky->thisVar.varType == SVT_FUNC) {
-			newP->frames[a].noise = - stacky->thisVar.varData.intValue;
+			newP->frames[a].noise = -stacky->thisVar.varData.intValue;
 		} else if (stacky->thisVar.varType == SVT_STACK) {
-			getValueType(frameNum, SVT_INT, stacky->thisVar.varData.theStack->first->thisVar);
-			getValueType(howMany, SVT_INT, stacky->thisVar.varData.theStack->first->next->thisVar);
+			getValueType(frameNum, SVT_INT,
+					stacky->thisVar.varData.theStack->first->thisVar);
+			getValueType(howMany, SVT_INT,
+					stacky->thisVar.varData.theStack->first->next->thisVar);
 		} else {
 			getValueType(frameNum, SVT_INT, stacky->thisVar);
 			howMany = 1;
@@ -107,32 +110,34 @@ personaAnimation *createPersonaAnim(int num, variableStack *&stacky) {
 }
 
 personaAnimation *makeNullAnim() {
-	personaAnimation *newAnim  = new personaAnimation;
-	if (!checkNew(newAnim)) return NULL;
+	personaAnimation *newAnim = new personaAnimation;
+	if (!checkNew(newAnim))
+		return NULL;
 
-
-	newAnim->theSprites       = NULL;
-	newAnim->numFrames        = 0;
-	newAnim->frames           = NULL;
+	newAnim->theSprites = NULL;
+	newAnim->numFrames = 0;
+	newAnim->frames = NULL;
 	return newAnim;
 }
 
 personaAnimation *copyAnim(personaAnimation *orig) {
 	int num = orig->numFrames;
 
-	personaAnimation *newAnim  = new personaAnimation;
-	if (!checkNew(newAnim)) return NULL;
+	personaAnimation *newAnim = new personaAnimation;
+	if (!checkNew(newAnim))
+		return NULL;
 
 	// Copy the easy bits...
-	newAnim->theSprites       = orig->theSprites;
-	newAnim->numFrames        = num;
+	newAnim->theSprites = orig->theSprites;
+	newAnim->numFrames = num;
 
 	if (num) {
 
 		// Argh!Frames!We need a whole NEW array of animFrame structures...
 
 		newAnim->frames = new animFrame[num];
-		if (!checkNew(newAnim->frames)) return NULL;
+		if (!checkNew(newAnim->frames))
+			return NULL;
 
 		for (int a = 0; a < num; ++a) {
 			newAnim->frames[a].frameNum = orig->frames[a].frameNum;
@@ -161,7 +166,8 @@ void turnMeAngle(onScreenPerson *thisPerson, int direc) {
 	int d = thisPerson->myPersona->numDirections;
 	thisPerson->angle = direc;
 	direc += (180 / d) + 180 + thisPerson->angleOffset;
-	while (direc >= 360) direc -= 360;
+	while (direc >= 360)
+		direc -= 360;
 	thisPerson->direction = (direc * d) / 360;
 }
 
@@ -176,14 +182,17 @@ bool initPeople() {
 
 void spinStep(onScreenPerson *thisPerson) {
 	int diff = (thisPerson->angle + 360) - thisPerson->wantAngle;
-	int eachSlice = thisPerson->spinSpeed ? thisPerson->spinSpeed : (360 / thisPerson->myPersona->numDirections);
+	int eachSlice =
+			thisPerson->spinSpeed ?
+					thisPerson->spinSpeed :
+					(360 / thisPerson->myPersona->numDirections);
 	while (diff > 180) {
 		diff -= 360;
 	}
 
 	if (diff >= eachSlice) {
 		turnMeAngle(thisPerson, thisPerson->angle - eachSlice);
-	} else if (diff <= - eachSlice) {
+	} else if (diff <= -eachSlice) {
 		turnMeAngle(thisPerson, thisPerson->angle + eachSlice);
 	} else {
 		turnMeAngle(thisPerson, thisPerson->wantAngle);
@@ -194,19 +203,22 @@ void spinStep(onScreenPerson *thisPerson) {
 void rethinkAngle(onScreenPerson *thisPerson) {
 	int d = thisPerson->myPersona->numDirections;
 	int direc = thisPerson->angle + (180 / d) + 180 + thisPerson->angleOffset;
-	while (direc >= 360) direc -= 360;
+	while (direc >= 360)
+		direc -= 360;
 	thisPerson->direction = (direc * d) / 360;
 }
 
 bool turnPersonToFace(int thisNum, int direc) {
 	onScreenPerson *thisPerson = findPerson(thisNum);
 	if (thisPerson) {
-		if (thisPerson->continueAfterWalking) abortFunction(thisPerson->continueAfterWalking);
+		if (thisPerson->continueAfterWalking)
+			abortFunction(thisPerson->continueAfterWalking);
 		thisPerson->continueAfterWalking = NULL;
 		thisPerson->walking = false;
 		thisPerson->spinning = false;
 		turnMeAngle(thisPerson, direc);
-		setFrames(* thisPerson, (thisPerson == speech->currentTalker) ? ANI_TALK : ANI_STAND);
+		setFrames(*thisPerson,
+				(thisPerson == speech->currentTalker) ? ANI_TALK : ANI_STAND);
 		return true;
 	}
 	return false;
@@ -216,7 +228,8 @@ bool setPersonExtra(int thisNum, int extra) {
 	onScreenPerson *thisPerson = findPerson(thisNum);
 	if (thisPerson) {
 		thisPerson->extra = extra;
-		if (extra & EXTRA_NOSCALE) thisPerson->scale = 1;
+		if (extra & EXTRA_NOSCALE)
+			thisPerson->scale = 1;
 		return true;
 	}
 	return false;
@@ -230,13 +243,15 @@ void setScale(short int h, short int d) {
 void moveAndScale(onScreenPerson &me, float x, float y) {
 	me.x = x;
 	me.y = y;
-	if (!(me.extra & EXTRA_NOSCALE) && scaleDivide) me.scale = (me.y - scaleHorizon) / scaleDivide;
+	if (!(me.extra & EXTRA_NOSCALE) && scaleDivide)
+		me.scale = (me.y - scaleHorizon) / scaleDivide;
 }
 
 onScreenPerson *findPerson(int v) {
 	onScreenPerson *thisPerson = allPeople;
 	while (thisPerson) {
-		if (v == thisPerson->thisType->objectNum) break;
+		if (v == thisPerson->thisType->objectNum)
+			break;
 		thisPerson = thisPerson->next;
 	}
 	return thisPerson;
@@ -244,12 +259,14 @@ onScreenPerson *findPerson(int v) {
 
 void movePerson(int x, int y, int objNum) {
 	onScreenPerson *moveMe = findPerson(objNum);
-	if (moveMe) moveAndScale(* moveMe, x, y);
+	if (moveMe)
+		moveAndScale(*moveMe, x, y);
 }
 
 void setShown(bool h, int ob) {
 	onScreenPerson *moveMe = findPerson(ob);
-	if (moveMe) moveMe->show = h;
+	if (moveMe)
+		moveMe->show = h;
 }
 
 enum drawModes {
@@ -318,57 +335,57 @@ void setMyDrawMode(onScreenPerson *moveMe, int h) {
 		moveMe->colourmix = 255;
 		moveMe->transparency = 0;
 		break;
-	case    drawModeShadow1:
+	case drawModeShadow1:
 		moveMe->r = moveMe->g = moveMe->b = 0;
 		moveMe->colourmix = 255;
 		moveMe->transparency = 64;
 		break;
-	case    drawModeShadow2:
+	case drawModeShadow2:
 		moveMe->r = moveMe->g = moveMe->b = 0;
 		moveMe->colourmix = 255;
 		moveMe->transparency = 128;
 		break;
-	case    drawModeShadow3:
+	case drawModeShadow3:
 		moveMe->r = moveMe->g = moveMe->b = 0;
 		moveMe->colourmix = 255;
 		moveMe->transparency = 192;
 		break;
-	case    drawModeFoggy3:
+	case drawModeFoggy3:
 		moveMe->r = moveMe->g = moveMe->b = 128;
 		moveMe->colourmix = 192;
 		moveMe->transparency = 0;
 		break;
-	case    drawModeFoggy2:
+	case drawModeFoggy2:
 		moveMe->r = moveMe->g = moveMe->b = 128;
 		moveMe->colourmix = 128;
 		moveMe->transparency = 0;
 		break;
-	case    drawModeFoggy1:
+	case drawModeFoggy1:
 		moveMe->r = moveMe->g = moveMe->b = 128;
 		moveMe->colourmix = 64;
 		moveMe->transparency = 0;
 		break;
-	case    drawModeFoggy4:
+	case drawModeFoggy4:
 		moveMe->r = moveMe->g = moveMe->b = 128;
 		moveMe->colourmix = 255;
 		moveMe->transparency = 0;
 		break;
-	case    drawModeGlow3:
+	case drawModeGlow3:
 		moveMe->r = moveMe->g = moveMe->b = 255;
 		moveMe->colourmix = 192;
 		moveMe->transparency = 0;
 		break;
-	case    drawModeGlow2:
+	case drawModeGlow2:
 		moveMe->r = moveMe->g = moveMe->b = 255;
 		moveMe->colourmix = 128;
 		moveMe->transparency = 0;
 		break;
-	case    drawModeGlow1:
+	case drawModeGlow1:
 		moveMe->r = moveMe->g = moveMe->b = 255;
 		moveMe->colourmix = 64;
 		moveMe->transparency = 0;
 		break;
-	case    drawModeGlow4:
+	case drawModeGlow4:
 		moveMe->r = moveMe->g = moveMe->b = 255;
 		moveMe->colourmix = 255;
 		moveMe->transparency = 0;
@@ -384,22 +401,27 @@ void setMyDrawMode(onScreenPerson *moveMe, int h) {
 
 void setDrawMode(int h, int ob) {
 	onScreenPerson *moveMe = findPerson(ob);
-	if (!moveMe) return;
+	if (!moveMe)
+		return;
 
 	setMyDrawMode(moveMe, h);
 }
 
 void setPersonTransparency(int ob, unsigned char x) {
 	onScreenPerson *moveMe = findPerson(ob);
-	if (!moveMe) return;
+	if (!moveMe)
+		return;
 
-	if (x > 254) x = 254;
+	if (x > 254)
+		x = 254;
 	moveMe->transparency = x;
 }
 
-void setPersonColourise(int ob, unsigned char r, unsigned char g, unsigned char b, unsigned char colourmix) {
+void setPersonColourise(int ob, unsigned char r, unsigned char g,
+		unsigned char b, unsigned char colourmix) {
 	onScreenPerson *moveMe = findPerson(ob);
-	if (!moveMe) return;
+	if (!moveMe)
+		return;
 
 	moveMe->r = r;
 	moveMe->g = g;
@@ -407,37 +429,36 @@ void setPersonColourise(int ob, unsigned char r, unsigned char g, unsigned char
 	moveMe->colourmix = colourmix;
 }
 
-
-
 extern screenRegion *overRegion;
 
 void shufflePeople() {
-	onScreenPerson * * thisReference = & allPeople;
-	onScreenPerson *A, * B;
+	onScreenPerson * * thisReference = &allPeople;
+	onScreenPerson *A, *B;
 
-	if (!allPeople) return;
+	if (!allPeople)
+		return;
 
-	while ((* thisReference)->next) {
-		float y1 = (* thisReference)->y;
-		if ((* thisReference)->extra & EXTRA_FRONT) y1 += 1000;
+	while ((*thisReference)->next) {
+		float y1 = (*thisReference)->y;
+		if ((*thisReference)->extra & EXTRA_FRONT)
+			y1 += 1000;
 
-		float y2 = (* thisReference)->next->y;
-		if ((* thisReference)->next->extra & EXTRA_FRONT) y2 += 1000;
+		float y2 = (*thisReference)->next->y;
+		if ((*thisReference)->next->extra & EXTRA_FRONT)
+			y2 += 1000;
 
 		if (y1 > y2) {
-			A = (* thisReference);
-			B = (* thisReference)->next;
+			A = (*thisReference);
+			B = (*thisReference)->next;
 			A->next = B->next;
 			B->next = A;
-			(* thisReference) = B;
+			(*thisReference) = B;
 		} else {
-			thisReference = & ((* thisReference)->next);
+			thisReference = &((*thisReference)->next);
 		}
 	}
 }
 
-
-
 void drawPeople() {
 	shufflePeople();
 
@@ -453,15 +474,20 @@ void drawPeople() {
 				thisPerson->frameNum = 0;
 				thisPerson->frameTick = myAnim->frames[0].howMany;
 				if (myAnim->frames[thisPerson->frameNum].noise > 0) {
-					startSound(myAnim->frames[thisPerson->frameNum].noise, false);
-					thisPerson->frameNum ++;
+					startSound(myAnim->frames[thisPerson->frameNum].noise,
+							false);
+					thisPerson->frameNum++;
 					thisPerson->frameNum %= thisPerson->myAnim->numFrames;
-					thisPerson->frameTick = thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
+					thisPerson->frameTick =
+							thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
 				} else if (myAnim->frames[thisPerson->frameNum].noise) {
-					startNewFunctionNum(- myAnim->frames[thisPerson->frameNum].noise, 0, NULL, noStack);
-					thisPerson->frameNum ++;
+					startNewFunctionNum(
+							-myAnim->frames[thisPerson->frameNum].noise, 0,
+							NULL, noStack);
+					thisPerson->frameNum++;
 					thisPerson->frameNum %= thisPerson->myAnim->numFrames;
-					thisPerson->frameTick = thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
+					thisPerson->frameTick =
+							thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
 				}
 			}
 			int fNumSign = myAnim->frames[thisPerson->frameNum].frameNum;
@@ -473,31 +499,39 @@ void drawPeople() {
 			}
 			if (m != 2) {
 				bool r = false;
-				r = scaleSprite(myAnim->theSprites->bank.sprites[fNum], myAnim->theSprites->bank.myPalette, thisPerson, m);
+				r = scaleSprite(myAnim->theSprites->bank.sprites[fNum],
+						myAnim->theSprites->bank.myPalette, thisPerson, m);
 				if (r) {
 					if (thisPerson->thisType->screenName[0]) {
-						if (personRegion.thisType != thisPerson->thisType) lastRegion = NULL;
+						if (personRegion.thisType != thisPerson->thisType)
+							lastRegion = NULL;
 						personRegion.thisType = thisPerson->thisType;
-						overRegion = & personRegion;
+						overRegion = &personRegion;
 					}
 				}
 			}
 		}
-		if (!-- thisPerson->frameTick) {
-			thisPerson->frameNum ++;
+		if (!--thisPerson->frameTick) {
+			thisPerson->frameNum++;
 			thisPerson->frameNum %= thisPerson->myAnim->numFrames;
-			thisPerson->frameTick = thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
+			thisPerson->frameTick =
+					thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
 			if (thisPerson->show && myAnim && myAnim->frames) {
 				if (myAnim->frames[thisPerson->frameNum].noise > 0) {
-					startSound(myAnim->frames[thisPerson->frameNum].noise, false);
-					thisPerson->frameNum ++;
+					startSound(myAnim->frames[thisPerson->frameNum].noise,
+							false);
+					thisPerson->frameNum++;
 					thisPerson->frameNum %= thisPerson->myAnim->numFrames;
-					thisPerson->frameTick = thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
+					thisPerson->frameTick =
+							thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
 				} else if (myAnim->frames[thisPerson->frameNum].noise) {
-					startNewFunctionNum(- myAnim->frames[thisPerson->frameNum].noise, 0, NULL, noStack);
-					thisPerson->frameNum ++;
+					startNewFunctionNum(
+							-myAnim->frames[thisPerson->frameNum].noise, 0,
+							NULL, noStack);
+					thisPerson->frameNum++;
 					thisPerson->frameNum %= thisPerson->myAnim->numFrames;
-					thisPerson->frameTick = thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
+					thisPerson->frameTick =
+							thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
 				}
 			}
 		}
@@ -514,22 +548,27 @@ void makeSilent(onScreenPerson &me) {
 }
 
 bool handleClosestPoint(int &setX, int &setY, int &setPoly) {
-	int gotX = 320, gotY = 200, gotPoly = -1, i, j, xTest1, yTest1,
-	    xTest2, yTest2, closestX, closestY, oldJ, currentDistance = 0xFFFFF,
-	                                              thisDistance;
+	int gotX = 320, gotY = 200, gotPoly = -1, i, j, xTest1, yTest1, xTest2,
+			yTest2, closestX, closestY, oldJ, currentDistance = 0xFFFFF,
+			thisDistance;
 
 //	FILE * dbug = fopen ("debug_closest.txt", "at");
 //	fprintf (dbug, "\nGetting closest point to %i, %i\n", setX, setY);
 
-	for (i = 0; i < currentFloor->numPolygons; i ++) {
+	for (i = 0; i < currentFloor->numPolygons; i++) {
 		oldJ = currentFloor->polygon[i].numVertices - 1;
-		for (j = 0; j < currentFloor->polygon[i].numVertices; j ++) {
+		for (j = 0; j < currentFloor->polygon[i].numVertices; j++) {
 //			fprintf (dbug, "Polygon %i, line %i... ", i, j);
-			xTest1 = currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].x;
-			yTest1 = currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].y;
-			xTest2 = currentFloor->vertex[currentFloor->polygon[i].vertexID[oldJ]].x;
-			yTest2 = currentFloor->vertex[currentFloor->polygon[i].vertexID[oldJ]].y;
-			closestPointOnLine(closestX, closestY, xTest1, yTest1, xTest2, yTest2, setX, setY);
+			xTest1 =
+					currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].x;
+			yTest1 =
+					currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].y;
+			xTest2 =
+					currentFloor->vertex[currentFloor->polygon[i].vertexID[oldJ]].x;
+			yTest2 =
+					currentFloor->vertex[currentFloor->polygon[i].vertexID[oldJ]].y;
+			closestPointOnLine(closestX, closestY, xTest1, yTest1, xTest2,
+					yTest2, setX, setY);
 //			fprintf (dbug, "closest point is %i, %i... ", closestX, closestY);
 			xTest1 = setX - closestX;
 			yTest1 = setY - closestY;
@@ -549,7 +588,8 @@ bool handleClosestPoint(int &setX, int &setY, int &setPoly) {
 	}
 //	fclose (dbug);
 
-	if (gotPoly == -1) return false;
+	if (gotPoly == -1)
+		return false;
 	setX = gotX;
 	setY = gotY;
 	setPoly = gotPoly;
@@ -565,11 +605,13 @@ bool doBorderStuff(onScreenPerson *moveMe) {
 	} else {
 		// The section in which we need to be next...
 		int newPoly = currentFloor->matrix[moveMe->inPoly][moveMe->walkToPoly];
-		if (newPoly == -1) return false;
+		if (newPoly == -1)
+			return false;
 
 		// Grab the index of the second matching corner...
 		int ID, ID2;
-		if (!getMatchingCorners(currentFloor->polygon[moveMe->inPoly], currentFloor->polygon[newPoly], ID, ID2))
+		if (!getMatchingCorners(currentFloor->polygon[moveMe->inPoly],
+				currentFloor->polygon[newPoly], ID, ID2))
 			return fatal("Not a valid floor plan!");
 
 		// Remember that we're walking to the new polygon...
@@ -605,8 +647,8 @@ bool doBorderStuff(onScreenPerson *moveMe) {
 			dy23 *= dy23;
 			dy24 *= dy24;
 
-			if (sqrt((double) dx13 + dy13) + sqrt((double) dx23 + dy23) <
-			        sqrt((double) dx14 + dy14) + sqrt((double) dx24 + dy24)) {
+			if (sqrt((double) dx13 + dy13) + sqrt((double) dx23 + dy23)
+					< sqrt((double) dx14 + dy14) + sqrt((double) dx24 + dy24)) {
 				moveMe->thisStepX = x3;
 				moveMe->thisStepY = y3;
 			} else {
@@ -623,7 +665,7 @@ bool doBorderStuff(onScreenPerson *moveMe) {
 		moveMe->spinning = true;
 	}
 
-	setFrames(* moveMe, ANI_WALK);
+	setFrames(*moveMe, ANI_WALK);
 	return true;
 }
 
@@ -634,20 +676,22 @@ bool walkMe(onScreenPerson *thisPerson, bool move = true) {
 		xDiff = thisPerson->thisStepX - thisPerson->x;
 		yDiff = (thisPerson->thisStepY - thisPerson->y) * 2;
 		s = thisPerson->scale * thisPerson->walkSpeed;
-		if (s < 0.2) s = 0.2;
+		if (s < 0.2)
+			s = 0.2;
 
-		maxDiff = (TF_abs(xDiff) >= TF_abs(yDiff)) ? TF_abs(xDiff) : TF_abs(yDiff);
+		maxDiff =
+				(TF_abs(xDiff) >= TF_abs(yDiff)) ?
+						TF_abs(xDiff) : TF_abs(yDiff);
 
 		if (TF_abs(maxDiff) > s) {
 			if (thisPerson->spinning) {
 				spinStep(thisPerson);
-				setFrames(* thisPerson, ANI_WALK);
+				setFrames(*thisPerson, ANI_WALK);
 			}
 			s = maxDiff / s;
 			if (move)
-				moveAndScale(* thisPerson,
-				             thisPerson->x + xDiff / s,
-				             thisPerson->y + yDiff / (s * 2));
+				moveAndScale(*thisPerson, thisPerson->x + xDiff / s,
+						thisPerson->y + yDiff / (s * 2));
 			return true;
 		}
 
@@ -659,24 +703,27 @@ bool walkMe(onScreenPerson *thisPerson, bool move = true) {
 			}
 			break;
 		}
-		if (!doBorderStuff(thisPerson)) break;
+		if (!doBorderStuff(thisPerson))
+			break;
 	}
 
 	thisPerson->walking = false;
-	setFrames(* thisPerson, ANI_STAND);
-	moveAndScale(* thisPerson,
-	             thisPerson->walkToX,
-	             thisPerson->walkToY);
+	setFrames(*thisPerson, ANI_STAND);
+	moveAndScale(*thisPerson, thisPerson->walkToX, thisPerson->walkToY);
 	return false;
 }
 
 bool makeWalkingPerson(int x, int y, int objNum, loadedFunction *func, int di) {
-	if (x == 0 && y == 0) return false;
-	if (currentFloor->numPolygons == 0) return false;
+	if (x == 0 && y == 0)
+		return false;
+	if (currentFloor->numPolygons == 0)
+		return false;
 	onScreenPerson *moveMe = findPerson(objNum);
-	if (!moveMe) return false;
+	if (!moveMe)
+		return false;
 
-	if (moveMe->continueAfterWalking) abortFunction(moveMe->continueAfterWalking);
+	if (moveMe->continueAfterWalking)
+		abortFunction(moveMe->continueAfterWalking);
 	moveMe->continueAfterWalking = NULL;
 	moveMe->walking = true;
 	moveMe->directionWhenDoneWalking = di;
@@ -685,13 +732,16 @@ bool makeWalkingPerson(int x, int y, int objNum, loadedFunction *func, int di) {
 	moveMe->walkToY = y;
 	moveMe->walkToPoly = inFloor(x, y);
 	if (moveMe->walkToPoly == -1) {
-		if (!handleClosestPoint(moveMe->walkToX, moveMe->walkToY, moveMe->walkToPoly)) return false;
+		if (!handleClosestPoint(moveMe->walkToX, moveMe->walkToY,
+				moveMe->walkToPoly))
+			return false;
 	}
 
 	moveMe->inPoly = inFloor(moveMe->x, moveMe->y);
 	if (moveMe->inPoly == -1) {
 		int xxx = moveMe->x, yyy = moveMe->y;
-		if (!handleClosestPoint(xxx, yyy, moveMe->inPoly)) return false;
+		if (!handleClosestPoint(xxx, yyy, moveMe->inPoly))
+			return false;
 	}
 
 	doBorderStuff(moveMe);
@@ -711,18 +761,22 @@ bool stopPerson(int o) {
 			moveMe->continueAfterWalking = NULL;
 			moveMe->walking = false;
 			moveMe->spinning = false;
-			setFrames(* moveMe, ANI_STAND);
+			setFrames(*moveMe, ANI_STAND);
 			return true;
 		}
 	return false;
 }
 
-bool forceWalkingPerson(int x, int y, int objNum, loadedFunction *func, int di) {
-	if (x == 0 && y == 0) return false;
+bool forceWalkingPerson(int x, int y, int objNum, loadedFunction *func,
+		int di) {
+	if (x == 0 && y == 0)
+		return false;
 	onScreenPerson *moveMe = findPerson(objNum);
-	if (!moveMe) return false;
+	if (!moveMe)
+		return false;
 
-	if (moveMe->continueAfterWalking) abortFunction(moveMe->continueAfterWalking);
+	if (moveMe->continueAfterWalking)
+		abortFunction(moveMe->continueAfterWalking);
 	moveMe->walking = true;
 	moveMe->continueAfterWalking = NULL;
 	moveMe->directionWhenDoneWalking = di;
@@ -745,27 +799,33 @@ bool forceWalkingPerson(int x, int y, int objNum, loadedFunction *func, int di)
 }
 
 void jumpPerson(int x, int y, int objNum) {
-	if (x == 0 && y == 0) return;
+	if (x == 0 && y == 0)
+		return;
 	onScreenPerson *moveMe = findPerson(objNum);
-	if (!moveMe) return;
-	if (moveMe->continueAfterWalking) abortFunction(moveMe->continueAfterWalking);
+	if (!moveMe)
+		return;
+	if (moveMe->continueAfterWalking)
+		abortFunction(moveMe->continueAfterWalking);
 	moveMe->continueAfterWalking = NULL;
 	moveMe->walking = false;
 	moveMe->spinning = false;
-	moveAndScale(* moveMe, x, y);
+	moveAndScale(*moveMe, x, y);
 }
 
 bool floatCharacter(int f, int objNum) {
 	onScreenPerson *moveMe = findPerson(objNum);
-	if (!moveMe) return false;
+	if (!moveMe)
+		return false;
 	moveMe->floaty = f;
 	return true;
 }
 
 bool setCharacterWalkSpeed(int f, int objNum) {
-	if (f <= 0) return false;
+	if (f <= 0)
+		return false;
 	onScreenPerson *moveMe = findPerson(objNum);
-	if (!moveMe) return false;
+	if (!moveMe)
+		return false;
 	moveMe->walkSpeed = f;
 	return true;
 }
@@ -778,9 +838,10 @@ void walkAllPeople() {
 			walkMe(thisPerson);
 		} else if (thisPerson->spinning) {
 			spinStep(thisPerson);
-			setFrames(* thisPerson, ANI_STAND);
+			setFrames(*thisPerson, ANI_STAND);
 		}
-		if ((!thisPerson->walking) && (!thisPerson->spinning) && thisPerson->continueAfterWalking) {
+		if ((!thisPerson->walking) && (!thisPerson->spinning)
+				&& thisPerson->continueAfterWalking) {
 			restartFunction(thisPerson->continueAfterWalking);
 			thisPerson->continueAfterWalking = NULL;
 		}
@@ -790,14 +851,15 @@ void walkAllPeople() {
 
 bool addPerson(int x, int y, int objNum, persona *p) {
 	onScreenPerson *newPerson = new onScreenPerson;
-	if (!checkNew(newPerson)) return false;
+	if (!checkNew(newPerson))
+		return false;
 
 	// EASY STUFF
 	newPerson->thisType = loadObjectType(objNum);
 	newPerson->scale = 1;
 	newPerson->extra = 0;
 	newPerson->continueAfterWalking = NULL;
-	moveAndScale(* newPerson, x, y);
+	moveAndScale(*newPerson, x, y);
 	newPerson->frameNum = 0;
 	newPerson->walkToX = x;
 	newPerson->walkToY = y;
@@ -819,7 +881,7 @@ bool addPerson(int x, int y, int objNum, persona *p) {
 	newPerson->transparency = 0;
 	newPerson->myPersona = p;
 
-	setFrames(* newPerson, ANI_STAND);
+	setFrames(*newPerson, ANI_STAND);
 
 	// HEIGHT (BASED ON 1st FRAME OF 1st ANIMATION... INC. SPECIAL CASES)
 	int fNumSigned = p->animation[0]->frames[0].frameNum;
@@ -828,22 +890,24 @@ bool addPerson(int x, int y, int objNum, persona *p) {
 		if (fNumSigned < 0) {
 			newPerson->height = 5;
 		} else {
-			newPerson->height = p->animation[0]->theSprites->bank.sprites[0].yhot + 5;
+			newPerson->height =
+					p->animation[0]->theSprites->bank.sprites[0].yhot + 5;
 		}
 	} else {
-		newPerson->height = p->animation[0]->theSprites->bank.sprites[fNum].yhot + 5;
+		newPerson->height = p->animation[0]->theSprites->bank.sprites[fNum].yhot
+				+ 5;
 	}
 
 	// NOW ADD IT IN THE RIGHT PLACE
-	onScreenPerson * * changethat = & allPeople;
+	onScreenPerson * * changethat = &allPeople;
 
-	while (((* changethat) != NULL) && ((* changethat)->y < y))
-		changethat = & ((* changethat)->next);
+	while (((*changethat) != NULL) && ((*changethat)->y < y))
+		changethat = &((*changethat)->next);
 
-	newPerson->next = (* changethat);
-	(* changethat) = newPerson;
+	newPerson->next = (*changethat);
+	(*changethat) = newPerson;
 
-	return (bool)(newPerson->thisType != NULL);
+	return (bool) (newPerson->thisType != NULL);
 }
 
 int timeForAnim(personaAnimation *fram) {
@@ -854,10 +918,11 @@ int timeForAnim(personaAnimation *fram) {
 	return total;
 }
 
-void animatePerson(int obj, personaAnimation *fram) {   // Set a new SINGLE animation
+void animatePerson(int obj, personaAnimation *fram) { // Set a new SINGLE animation
 	onScreenPerson *moveMe = findPerson(obj);
 	if (moveMe) {
-		if (moveMe->continueAfterWalking) abortFunction(moveMe->continueAfterWalking);
+		if (moveMe->continueAfterWalking)
+			abortFunction(moveMe->continueAfterWalking);
 		moveMe->continueAfterWalking = NULL;
 		moveMe->walking = false;
 		moveMe->spinning = false;
@@ -874,10 +939,10 @@ void animatePerson(int obj, persona *per) {             // Set a new costume
 		moveMe->spinning = false;
 		moveMe->myPersona = per;
 		rethinkAngle(moveMe);
-		if (moveMe-> walking) {
-			setFrames(* moveMe, ANI_WALK);
+		if (moveMe->walking) {
+			setFrames(*moveMe, ANI_WALK);
 		} else {
-			setFrames(* moveMe, ANI_STAND);
+			setFrames(*moveMe, ANI_STAND);
 		}
 	}
 }
@@ -885,7 +950,8 @@ void animatePerson(int obj, persona *per) {             // Set a new costume
 void killAllPeople() {
 	onScreenPerson *killPeople;
 	while (allPeople) {
-		if (allPeople->continueAfterWalking) abortFunction(allPeople->continueAfterWalking);
+		if (allPeople->continueAfterWalking)
+			abortFunction(allPeople->continueAfterWalking);
 		allPeople->continueAfterWalking = NULL;
 		killPeople = allPeople;
 		allPeople = allPeople->next;
@@ -896,19 +962,20 @@ void killAllPeople() {
 
 void killMostPeople() {
 	onScreenPerson *killPeople;
-	onScreenPerson * * lookyHere = & allPeople;
+	onScreenPerson * * lookyHere = &allPeople;
 
-	while (* lookyHere) {
-		if ((* lookyHere)->extra & EXTRA_NOREMOVE) {
-			lookyHere = & (* lookyHere)->next;
+	while (*lookyHere) {
+		if ((*lookyHere)->extra & EXTRA_NOREMOVE) {
+			lookyHere = &(*lookyHere)->next;
 		} else {
-			killPeople = (* lookyHere);
+			killPeople = (*lookyHere);
 
 			// Change last pointer to NEXT in the list instead
-			(* lookyHere) = killPeople->next;
+			(*lookyHere) = killPeople->next;
 
 			// Gone from the list... now free some memory
-			if (killPeople->continueAfterWalking) abortFunction(killPeople->continueAfterWalking);
+			if (killPeople->continueAfterWalking)
+				abortFunction(killPeople->continueAfterWalking);
 			killPeople->continueAfterWalking = NULL;
 			removeObjectType(killPeople->thisType);
 			delete killPeople;
@@ -920,21 +987,22 @@ void removeOneCharacter(int i) {
 	onScreenPerson *p = findPerson(i);
 
 	if (p) {
-		if (overRegion == &personRegion && overRegion->thisType == p->thisType) {
+		if (overRegion == &personRegion
+				&& overRegion->thisType == p->thisType) {
 			overRegion = NULL;
 		}
 
-		if (p->continueAfterWalking) abortFunction(p->continueAfterWalking);
+		if (p->continueAfterWalking)
+			abortFunction(p->continueAfterWalking);
 		p->continueAfterWalking = NULL;
 		onScreenPerson * * killPeople;
 
-		for (killPeople = & allPeople;
-		        * killPeople != p;
-		        killPeople = & ((* killPeople)->next)) {
+		for (killPeople = &allPeople; *killPeople != p; killPeople =
+				&((*killPeople)->next)) {
 			;
 		}
 
-		* killPeople = p->next;
+		*killPeople = p->next;
 		removeObjectType(p->thisType);
 		delete p;
 	}
@@ -960,7 +1028,8 @@ bool loadAnim(personaAnimation *p, Common::SeekableReadStream *stream) {
 	if (p->numFrames) {
 		int a = get4bytes(stream);
 		p->frames = new animFrame[p->numFrames];
-		if (!checkNew(p->frames)) return false;
+		if (!checkNew(p->frames))
+			return false;
 		p->theSprites = loadBankForAnim(a);
 
 		for (a = 0; a < p->numFrames; ++a) {
@@ -979,25 +1048,26 @@ bool loadAnim(personaAnimation *p, Common::SeekableReadStream *stream) {
 	return true;
 }
 /*
-void debugCostume (char * message, persona * cossy) {
-    FILE * db = fopen ("debuTURN.txt", "at");
-    fprintf (db, "  %s costume with %i directions...\n", message, cossy->numDirections);
-    for (int a = 0; a < cossy->numDirections * 3; ++a) {
-        fprintf (db, "      %i frames:", cossy->animation[a]->numFrames);
-        for (int b = 0; b < cossy->animation[a]->numFrames; b ++) {
-            fprintf (db, " %i", cossy->animation[a]->frames[b]);
-        }
-        fprintf (db, "\n");
-
-    }
-    fclose (db);
-}
-*/
+ void debugCostume (char * message, persona * cossy) {
+ FILE * db = fopen ("debuTURN.txt", "at");
+ fprintf (db, "  %s costume with %i directions...\n", message, cossy->numDirections);
+ for (int a = 0; a < cossy->numDirections * 3; ++a) {
+ fprintf (db, "      %i frames:", cossy->animation[a]->numFrames);
+ for (int b = 0; b < cossy->animation[a]->numFrames; b ++) {
+ fprintf (db, " %i", cossy->animation[a]->frames[b]);
+ }
+ fprintf (db, "\n");
+
+ }
+ fclose (db);
+ }
+ */
 bool saveCostume(persona *cossy, Common::WriteStream *stream) {
 	int a;
 	put2bytes(cossy->numDirections, stream);
 	for (a = 0; a < cossy->numDirections * 3; ++a) {
-		if (!saveAnim(cossy->animation[a], stream)) return false;
+		if (!saveAnim(cossy->animation[a], stream))
+			return false;
 	}
 //	debugCostume ("Saved", cossy);
 	return true;
@@ -1006,13 +1076,16 @@ bool saveCostume(persona *cossy, Common::WriteStream *stream) {
 bool loadCostume(persona *cossy, Common::SeekableReadStream *stream) {
 	int a;
 	cossy->numDirections = get2bytes(stream);
-	cossy->animation = new personaAnimation * [cossy->numDirections * 3];
-	if (!checkNew(cossy->animation)) return false;
+	cossy->animation = new personaAnimation *[cossy->numDirections * 3];
+	if (!checkNew(cossy->animation))
+		return false;
 	for (a = 0; a < cossy->numDirections * 3; ++a) {
 		cossy->animation[a] = new personaAnimation;
-		if (!checkNew(cossy->animation[a])) return false;
+		if (!checkNew(cossy->animation[a]))
+			return false;
 
-		if (!loadAnim(cossy->animation[a], stream)) return false;
+		if (!loadAnim(cossy->animation[a], stream))
+			return false;
 	}
 //	debugCostume ("Loaded", cossy);
 	return true;
@@ -1026,7 +1099,7 @@ bool savePeople(Common::WriteStream *stream) {
 	putSigned(scaleDivide, stream);
 
 	while (me) {
-		countPeople ++;
+		countPeople++;
 		me = me->next;
 	}
 
@@ -1086,7 +1159,7 @@ bool savePeople(Common::WriteStream *stream) {
 }
 
 bool loadPeople(Common::SeekableReadStream *stream) {
-	onScreenPerson * * pointy = & allPeople;
+	onScreenPerson * * pointy = &allPeople;
 	onScreenPerson *me;
 
 	scaleHorizon = getSigned(stream);
@@ -1098,13 +1171,16 @@ bool loadPeople(Common::SeekableReadStream *stream) {
 	allPeople = NULL;
 	for (a = 0; a < countPeople; ++a) {
 		me = new onScreenPerson;
-		if (!checkNew(me)) return false;
+		if (!checkNew(me))
+			return false;
 
 		me->myPersona = new persona;
-		if (!checkNew(me->myPersona)) return false;
+		if (!checkNew(me->myPersona))
+			return false;
 
 		me->myAnim = new personaAnimation;
-		if (!checkNew(me->myAnim)) return false;
+		if (!checkNew(me->myAnim))
+			return false;
 
 		me->x = getFloat(stream);
 		me->y = getFloat(stream);
@@ -1132,7 +1208,8 @@ bool loadPeople(Common::SeekableReadStream *stream) {
 		me->spinning = getch(stream);
 		if (getch(stream)) {
 			me->continueAfterWalking = loadFunction(stream);
-			if (!me->continueAfterWalking) return false;
+			if (!me->continueAfterWalking)
+				return false;
 		} else {
 			me->continueAfterWalking = NULL;
 		}
@@ -1169,8 +1246,8 @@ bool loadPeople(Common::SeekableReadStream *stream) {
 		}
 
 		me->next = NULL;
-		* pointy = me;
-		pointy = & (me->next);
+		*pointy = me;
+		pointy = &(me->next);
 	}
 //	db ("End of loadPeople");
 	return true;
diff --git a/engines/sludge/people.h b/engines/sludge/people.h
index ba726b0..f6d8784 100644
--- a/engines/sludge/people.h
+++ b/engines/sludge/people.h
@@ -96,13 +96,16 @@ void makeSilent(onScreenPerson &me);
 void setShown(bool h, int ob);
 void setDrawMode(int h, int ob);
 void setPersonTransparency(int ob, unsigned char x);
-void setPersonColourise(int ob, unsigned char r, unsigned char g, unsigned char b, unsigned char colourmix);
+void setPersonColourise(int ob, unsigned char r, unsigned char g,
+		unsigned char b, unsigned char colourmix);
 
 // Moving 'em
 
 void movePerson(int x, int y, int objNum);
-bool makeWalkingPerson(int x, int y, int objNum, struct loadedFunction *func, int di);
-bool forceWalkingPerson(int x, int y, int objNum, struct loadedFunction *func, int di);
+bool makeWalkingPerson(int x, int y, int objNum, struct loadedFunction *func,
+		int di);
+bool forceWalkingPerson(int x, int y, int objNum, struct loadedFunction *func,
+		int di);
 void jumpPerson(int x, int y, int objNum);
 void walkAllPeople();
 bool turnPersonToFace(int thisNum, int direc);
@@ -116,7 +119,7 @@ void animatePerson(int obj, personaAnimation *);
 void animatePerson(int obj, persona *per);
 personaAnimation *createPersonaAnim(int num, struct variableStack *&stacky);
 inline void setBankFile(personaAnimation *newP, loadedSpriteBank *sB) {
-	newP -> theSprites = sB;
+	newP->theSprites = sB;
 }
 bool setPersonExtra(int f, int newSetting);
 int timeForAnim(personaAnimation *fram);
diff --git a/engines/sludge/region.cpp b/engines/sludge/region.cpp
index eebcb57..f837d32 100644
--- a/engines/sludge/region.cpp
+++ b/engines/sludge/region.cpp
@@ -47,19 +47,20 @@ void showBoxes() {
 }
 
 void removeScreenRegion(int objectNum) {
-	screenRegion * * huntRegion = & allScreenRegions;
+	screenRegion * * huntRegion = &allScreenRegions;
 	screenRegion *killMe;
 
-	while (* huntRegion) {
-		if ((* huntRegion)->thisType->objectNum == objectNum) {
-			killMe = * huntRegion;
-			* huntRegion = killMe->next;
+	while (*huntRegion) {
+		if ((*huntRegion)->thisType->objectNum == objectNum) {
+			killMe = *huntRegion;
+			*huntRegion = killMe->next;
 			removeObjectType(killMe->thisType);
-			if (killMe == overRegion) overRegion = NULL;
+			if (killMe == overRegion)
+				overRegion = NULL;
 			delete killMe;
 			killMe = NULL;
 		} else {
-			huntRegion = & ((* huntRegion)->next);
+			huntRegion = &((*huntRegion)->next);
 		}
 	}
 }
@@ -69,7 +70,7 @@ void saveRegions(Common::WriteStream *stream) {
 	screenRegion *thisRegion = allScreenRegions;
 	while (thisRegion) {
 		thisRegion = thisRegion->next;
-		numRegions ++;
+		numRegions++;
 	}
 	put2bytes(numRegions, stream);
 	thisRegion = allScreenRegions;
@@ -91,12 +92,12 @@ void loadRegions(Common::SeekableReadStream *stream) {
 	int numRegions = get2bytes(stream);
 
 	screenRegion *newRegion;
-	screenRegion * * pointy = & allScreenRegions;
+	screenRegion * * pointy = &allScreenRegions;
 
-	while (numRegions --) {
+	while (numRegions--) {
 		newRegion = new screenRegion;
-		* pointy = newRegion;
-		pointy = & (newRegion->next);
+		*pointy = newRegion;
+		pointy = &(newRegion->next);
 
 		newRegion->x1 = get2bytes(stream);
 		newRegion->y1 = get2bytes(stream);
@@ -107,7 +108,7 @@ void loadRegions(Common::SeekableReadStream *stream) {
 		newRegion->di = get2bytes(stream);
 		newRegion->thisType = loadObjectRef(stream);
 	}
-	* pointy = NULL;
+	*pointy = NULL;
 }
 
 void killAllRegions() {
@@ -121,9 +122,11 @@ void killAllRegions() {
 	overRegion = NULL;
 }
 
-bool addScreenRegion(int x1, int y1, int x2, int y2, int sX, int sY, int di, int objectNum) {
+bool addScreenRegion(int x1, int y1, int x2, int y2, int sX, int sY, int di,
+		int objectNum) {
 	screenRegion *newRegion = new screenRegion;
-	if (!checkNew(newRegion)) return false;
+	if (!checkNew(newRegion))
+		return false;
 	newRegion->di = di;
 	newRegion->x1 = x1;
 	newRegion->y1 = y1;
@@ -134,14 +137,16 @@ bool addScreenRegion(int x1, int y1, int x2, int y2, int sX, int sY, int di, int
 	newRegion->thisType = loadObjectType(objectNum);
 	newRegion->next = allScreenRegions;
 	allScreenRegions = newRegion;
-	return (bool)(newRegion->thisType != NULL);
+	return (bool) (newRegion->thisType != NULL);
 }
 
 void getOverRegion() {
 	screenRegion *thisRegion = allScreenRegions;
 	while (thisRegion) {
-		if ((input.mouseX >= thisRegion->x1 - cameraX) && (input.mouseY >= thisRegion->y1 - cameraY) &&
-		        (input.mouseX <= thisRegion->x2 - cameraX) && (input.mouseY <= thisRegion->y2 - cameraY)) {
+		if ((input.mouseX >= thisRegion->x1 - cameraX)
+				&& (input.mouseY >= thisRegion->y1 - cameraY)
+				&& (input.mouseX <= thisRegion->x2 - cameraX)
+				&& (input.mouseY <= thisRegion->y2 - cameraY)) {
 			overRegion = thisRegion;
 			return;
 		}
diff --git a/engines/sludge/savedata.cpp b/engines/sludge/savedata.cpp
index dc061c6..805f006 100644
--- a/engines/sludge/savedata.cpp
+++ b/engines/sludge/savedata.cpp
@@ -42,30 +42,30 @@ char encode2 = 0;
 extern char *gamePath;
 
 /*
-void loadSaveDebug (char * com) {
-    FILE * ffpp = fopen ("debuggy.txt", "at");
-    fprintf (ffpp, "%s\n", com);
-    fclose (ffpp);
-}
-
-void loadSaveDebug (char com) {
-    FILE * ffpp = fopen ("debuggy.txt", "at");
-    fprintf (ffpp, "%c\n", com);
-    fclose (ffpp);
-}
-
-void loadSaveDebug (int com) {
-    FILE * ffpp = fopen ("debuggy.txt", "at");
-    fprintf (ffpp, "%d\n", com);
-    fclose (ffpp);
-}
-*/
+ void loadSaveDebug (char * com) {
+ FILE * ffpp = fopen ("debuggy.txt", "at");
+ fprintf (ffpp, "%s\n", com);
+ fclose (ffpp);
+ }
+
+ void loadSaveDebug (char com) {
+ FILE * ffpp = fopen ("debuggy.txt", "at");
+ fprintf (ffpp, "%c\n", com);
+ fclose (ffpp);
+ }
+
+ void loadSaveDebug (int com) {
+ FILE * ffpp = fopen ("debuggy.txt", "at");
+ fprintf (ffpp, "%d\n", com);
+ fclose (ffpp);
+ }
+ */
 
 void writeStringEncoded(const char *s, Common::WriteStream *stream) {
 	int a, len = strlen(s);
 
 	put2bytes(len, stream);
-	for (a = 0; a < len; a ++) {
+	for (a = 0; a < len; a++) {
 		putch(s[a] ^ encode1, stream);
 		encode1 += encode2;
 	}
@@ -74,9 +74,10 @@ void writeStringEncoded(const char *s, Common::WriteStream *stream) {
 char *readStringEncoded(Common::File *fp) {
 	int a, len = get2bytes(fp);
 	char *s = new char[len + 1];
-	if (!checkNew(s)) return NULL;
-	for (a = 0; a < len; a ++) {
-		s[a] = (char)(getch(fp) ^ encode1);
+	if (!checkNew(s))
+		return NULL;
+	for (a = 0; a < len; a++) {
+		s[a] = (char) (getch(fp) ^ encode1);
 		encode1 += encode2;
 	}
 	s[len] = 0;
@@ -98,7 +99,7 @@ char *readTextPlain(Common::File *fp) {
 		if ((gotChar == '\n') || (fp->eos())) {
 			keepGoing = false;
 		} else {
-			stringSize ++;
+			stringSize++;
 		}
 	}
 
@@ -107,7 +108,8 @@ char *readTextPlain(Common::File *fp) {
 	} else {
 		fp->seek(startPos, SEEK_SET);
 		reply = new char[stringSize + 1];
-		if (reply == NULL) return NULL;
+		if (reply == NULL)
+			return NULL;
 		size_t bytes_read = fp->read(reply, stringSize);
 		if (bytes_read != stringSize && fp->err()) {
 			debugOut("Reading error in readTextPlain.\n");
@@ -123,7 +125,9 @@ bool fileToStack(char *filename, stackHandler *sH) {
 
 	variable stringVar;
 	stringVar.varType = SVT_NULL;
-	const char *checker = saveEncoding ? "[Custom data (encoded)]\r\n" : "[Custom data (ASCII)]\n";
+	const char *checker =
+			saveEncoding ?
+					"[Custom data (encoded)]\r\n" : "[Custom data (ASCII)]\n";
 
 	Common::File fd;
 
@@ -150,39 +154,42 @@ bool fileToStack(char *filename, stackHandler *sH) {
 	}
 
 	encode1 = (unsigned char) saveEncoding & 255;
-	encode2 = (unsigned char)(saveEncoding >> 8);
+	encode2 = (unsigned char) (saveEncoding >> 8);
 
-	while (* checker) {
-		if (getch(&fd) != * checker) {
+	while (*checker) {
+		if (getch(&fd) != *checker) {
 			fd.close();
-			return fatal(LOAD_ERROR "This isn't a SLUDGE custom data file:", filename);
+			return fatal(LOAD_ERROR "This isn't a SLUDGE custom data file:",
+					filename);
 		}
-		checker ++;
+		checker++;
 	}
 
 	if (saveEncoding) {
 		char *checker = readStringEncoded(&fd);
 		if (strcmp(checker, "UN�LO�CKED")) {
 			fd.close();
-			return fatal(LOAD_ERROR "The current file encoding setting does not match the encoding setting used when this file was created:", filename);
+			return fatal(
+					LOAD_ERROR "The current file encoding setting does not match the encoding setting used when this file was created:",
+					filename);
 		}
 		delete checker;
 		checker = NULL;
 	}
 
-
 	for (;;) {
 		if (saveEncoding) {
 			char i = getch(&fd) ^ encode1;
 
-			if (fd.eos()) break;
+			if (fd.eos())
+				break;
 			switch (i) {
 			case 0: {
 				char *g = readStringEncoded(&fd);
 				makeTextVar(stringVar, g);
 				delete g;
 			}
-			break;
+				break;
 
 			case 1:
 				setVariable(stringVar, SVT_INT, get4bytes(&fd));
@@ -199,18 +206,21 @@ bool fileToStack(char *filename, stackHandler *sH) {
 			}
 		} else {
 			char *line = readTextPlain(&fd);
-			if (!line) break;
+			if (!line)
+				break;
 			makeTextVar(stringVar, line);
 		}
 
-		if (sH -> first == NULL) {
+		if (sH->first == NULL) {
 			// Adds to the TOP of the array... oops!
-			if (!addVarToStackQuick(stringVar, sH -> first)) return false;
-			sH -> last = sH -> first;
+			if (!addVarToStackQuick(stringVar, sH->first))
+				return false;
+			sH->last = sH->first;
 		} else {
 			// Adds to the END of the array... much better
-			if (!addVarToStackQuick(stringVar, sH -> last -> next)) return false;
-			sH -> last = sH -> last -> next;
+			if (!addVarToStackQuick(stringVar, sH->last->next))
+				return false;
+			sH->last = sH->last->next;
 		}
 	}
 	fd.close();
@@ -238,12 +248,12 @@ bool stackToFile(char *filename, const variable &from) {
 	while (hereWeAre) {
 		if (saveEncoding) {
 			switch (hereWeAre -> thisVar.varType) {
-			case SVT_STRING:
+				case SVT_STRING:
 				fputc(encode1, fp);
 				writeStringEncoded(hereWeAre -> thisVar.varData.theString, fp);
 				break;
 
-			case SVT_INT:
+				case SVT_INT:
 				// Small enough to be stored as a char
 				if (hereWeAre -> thisVar.varData.intValue >= 0 && hereWeAre -> thisVar.varData.intValue < 256) {
 					fputc(2 ^ encode1, fp);
@@ -254,7 +264,7 @@ bool stackToFile(char *filename, const variable &from) {
 				}
 				break;
 
-			default:
+				default:
 				fatal("Can't create an encoded custom data file containing anything other than numbers and strings", filename);
 				fclose(fp);
 				return false;
diff --git a/engines/sludge/sludge.h b/engines/sludge/sludge.h
index 734a856..73105c4 100644
--- a/engines/sludge/sludge.h
+++ b/engines/sludge/sludge.h
@@ -30,7 +30,7 @@
 #include "sludge/console.h"
 
 namespace Sludge {
- 
+
 class SludgeConsole;
 
 struct SludgeGameDescription;
@@ -43,8 +43,8 @@ enum {
 	kSludgeDebugBuiltin = 1 << 3,
 	kSludgeDebugGraphics = 1 << 4
 };
- 
-class SludgeEngine : public Engine {
+
+class SludgeEngine: public Engine {
 protected:
 	// Engine APIs
 	virtual Common::Error run();
@@ -52,19 +52,19 @@ protected:
 public:
 	SludgeEngine(OSystem *syst, const SludgeGameDescription *gameDesc);
 	virtual ~SludgeEngine();
- 
+
 	int getGameType() const;
 	const char *getGameId() const;
 	uint32 getFeatures() const;
 	Common::Language getLanguage() const;
 
 	const SludgeGameDescription *_gameDescription;
- 
+
 private:
 	SludgeConsole *_console;
- 	Common::RandomSource *_rnd;
+	Common::RandomSource *_rnd;
 };
 
 } // End of namespace Sludge
- 
+
 #endif
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index 5202168..c7ffd9d 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -101,7 +101,7 @@ bool captureAllKeys = false;
 unsigned char brightnessLevel = 255;
 
 eventHandlers mainHandlers;
-eventHandlers *currentEvents = & mainHandlers;
+eventHandlers *currentEvents = &mainHandlers;
 
 extern HWND hMainWindow;
 extern screenRegion *overRegion;
@@ -117,50 +117,55 @@ inputType input;
 variable *globalVars;
 int numGlobals;
 
-const char *sludgeText[] = { "?????", "RETURN", "BRANCH", "BR_ZERO", "SET_GLOBAL",
-                             "SET_LOCAL", "LOAD_GLOBAL", "LOAD_LOCAL",
-                             "PLUS", "MINUS", "MULT", "DIVIDE",
-                             "AND", "OR", "EQUALS", "NOT_EQ", "MODULUS", "LOAD_VALUE",
-                             "LOAD_BUILT", "LOAD_FUNC", "CALLIT", "LOAD_STRING", "LOAD_FILE",
-                             "LOAD_OBJTYPE", "NOT", "LOAD_NULL", "STACK_PUSH",
-                             "LESSTHAN", "MORETHAN", "NEGATIVE", "U", "LESS_EQUAL", "MORE_EQUAL",
-                             "INC_LOCAL", "DEC_LOCAL", "INC_GLOBAL", "DEC_GLOBAL", "INDEXSET", "INDEXGET",
-                             "INC_INDEX", "DEC_INDEX", "QUICK_PUSH"
-                           };
+const char *sludgeText[] = { "?????", "RETURN", "BRANCH", "BR_ZERO",
+		"SET_GLOBAL", "SET_LOCAL", "LOAD_GLOBAL", "LOAD_LOCAL", "PLUS", "MINUS",
+		"MULT", "DIVIDE", "AND", "OR", "EQUALS", "NOT_EQ", "MODULUS",
+		"LOAD_VALUE", "LOAD_BUILT", "LOAD_FUNC", "CALLIT", "LOAD_STRING",
+		"LOAD_FILE", "LOAD_OBJTYPE", "NOT", "LOAD_NULL", "STACK_PUSH",
+		"LESSTHAN", "MORETHAN", "NEGATIVE", "U", "LESS_EQUAL", "MORE_EQUAL",
+		"INC_LOCAL", "DEC_LOCAL", "INC_GLOBAL", "DEC_GLOBAL", "INDEXSET",
+		"INDEXGET", "INC_INDEX", "DEC_INDEX", "QUICK_PUSH" };
 
 void loadHandlers(Common::SeekableReadStream *stream) {
-	currentEvents->leftMouseFunction      = get2bytes(stream);
-	currentEvents->leftMouseUpFunction    = get2bytes(stream);
-	currentEvents->rightMouseFunction     = get2bytes(stream);
-	currentEvents->rightMouseUpFunction   = get2bytes(stream);
-	currentEvents->moveMouseFunction      = get2bytes(stream);
-	currentEvents->focusFunction          = get2bytes(stream);
-	currentEvents->spaceFunction          = get2bytes(stream);
+	currentEvents->leftMouseFunction = get2bytes(stream);
+	currentEvents->leftMouseUpFunction = get2bytes(stream);
+	currentEvents->rightMouseFunction = get2bytes(stream);
+	currentEvents->rightMouseUpFunction = get2bytes(stream);
+	currentEvents->moveMouseFunction = get2bytes(stream);
+	currentEvents->focusFunction = get2bytes(stream);
+	currentEvents->spaceFunction = get2bytes(stream);
 }
 
 void saveHandlers(Common::WriteStream *stream) {
-	put2bytes(currentEvents->leftMouseFunction,      stream);
-	put2bytes(currentEvents->leftMouseUpFunction,    stream);
-	put2bytes(currentEvents->rightMouseFunction,     stream);
-	put2bytes(currentEvents->rightMouseUpFunction,   stream);
-	put2bytes(currentEvents->moveMouseFunction,      stream);
-	put2bytes(currentEvents->focusFunction,          stream);
-	put2bytes(currentEvents->spaceFunction,          stream);
+	put2bytes(currentEvents->leftMouseFunction, stream);
+	put2bytes(currentEvents->leftMouseUpFunction, stream);
+	put2bytes(currentEvents->rightMouseFunction, stream);
+	put2bytes(currentEvents->rightMouseUpFunction, stream);
+	put2bytes(currentEvents->moveMouseFunction, stream);
+	put2bytes(currentEvents->focusFunction, stream);
+	put2bytes(currentEvents->spaceFunction, stream);
 }
 
-Common::File *openAndVerify(char *filename, char extra1, char extra2, const char *er, int &fileVersion) {
+Common::File *openAndVerify(char *filename, char extra1, char extra2,
+		const char *er, int &fileVersion) {
 	Common::File *fp = new Common::File();
 	if (!fp->open(filename)) {
 		fatal("Can't open file", filename);
 		return NULL;
 	}
 	bool headerBad = false;
-	if (getch(fp) != 'S') headerBad = true;
-	if (getch(fp) != 'L') headerBad = true;
-	if (getch(fp) != 'U') headerBad = true;
-	if (getch(fp) != 'D') headerBad = true;
-	if (getch(fp) != extra1) headerBad = true;
-	if (getch(fp) != extra2) headerBad = true;
+	if (getch(fp) != 'S')
+		headerBad = true;
+	if (getch(fp) != 'L')
+		headerBad = true;
+	if (getch(fp) != 'U')
+		headerBad = true;
+	if (getch(fp) != 'D')
+		headerBad = true;
+	if (getch(fp) != extra1)
+		headerBad = true;
+	if (getch(fp) != extra2)
+		headerBad = true;
 	if (headerBad) {
 		fatal(er, filename);
 		return NULL;
@@ -196,34 +201,40 @@ bool initSludge(char *filename) {
 	int a = 0;
 	mouseCursorAnim = makeNullAnim();
 
-	Common::File *fp = openAndVerify(filename, 'G', 'E', ERROR_BAD_HEADER, gameVersion);
-	if (!fp) return false;
+	Common::File *fp = openAndVerify(filename, 'G', 'E', ERROR_BAD_HEADER,
+			gameVersion);
+	if (!fp)
+		return false;
 
 	char c = getch(fp);
 	if (c) {
 		numBIFNames = get2bytes(fp);
 		debug(kSludgeDebugDataLoad, "numBIFNames %i", numBIFNames);
 		allBIFNames = new char *[numBIFNames];
-		if (!checkNew(allBIFNames)) return false;
+		if (!checkNew(allBIFNames))
+			return false;
 
-		for (int fn = 0; fn < numBIFNames; fn ++) {
+		for (int fn = 0; fn < numBIFNames; fn++) {
 			allBIFNames[fn] = readString(fp);
 		}
 		numUserFunc = get2bytes(fp);
 		debug(kSludgeDebugDataLoad, "numUserFunc %i", numUserFunc);
 		allUserFunc = new char *[numUserFunc];
-		if (!checkNew(allUserFunc)) return false;
+		if (!checkNew(allUserFunc))
+			return false;
 
-		for (int fn = 0; fn < numUserFunc; fn ++) {
+		for (int fn = 0; fn < numUserFunc; fn++) {
 			allUserFunc[fn] = readString(fp);
 		}
 		if (gameVersion >= VERSION(1, 3)) {
 			numResourceNames = get2bytes(fp);
-			debug(kSludgeDebugDataLoad, "numResourceNames %i", numResourceNames);
+			debug(kSludgeDebugDataLoad, "numResourceNames %i",
+					numResourceNames);
 			allResourceNames = new char *[numResourceNames];
-			if (!checkNew(allResourceNames)) return false;
+			if (!checkNew(allResourceNames))
+				return false;
 
-			for (int fn = 0; fn < numResourceNames; fn ++) {
+			for (int fn = 0; fn < numResourceNames; fn++) {
 				allResourceNames[fn] = readString(fp);
 			}
 		}
@@ -244,10 +255,13 @@ bool initSludge(char *filename) {
 		debug("Reading error in initSludge.");
 	}
 
-	char *dataFol = (gameVersion >= VERSION(1, 3)) ? readString(fp) : joinStrings("", "");
+	char *dataFol =
+			(gameVersion >= VERSION(1, 3)) ?
+					readString(fp) : joinStrings("", "");
 	debug(kSludgeDebugDataLoad, "dataFol : %s", dataFol);
 
-	gameSettings.numLanguages = (gameVersion >= VERSION(1, 3)) ? (getch(fp)) : 0;
+	gameSettings.numLanguages =
+			(gameVersion >= VERSION(1, 3)) ? (getch(fp)) : 0;
 	debug(kSludgeDebugDataLoad, "numLanguages : %c", gameSettings.numLanguages);
 	makeLanguageTable(fp);
 
@@ -262,7 +276,8 @@ bool initSludge(char *filename) {
 	char *checker = readString(fp);
 	debug(kSludgeDebugDataLoad, "checker : %s", checker);
 
-	if (strcmp(checker, "okSoFar")) return fatal(ERROR_BAD_HEADER, filename);
+	if (strcmp(checker, "okSoFar"))
+		return fatal(ERROR_BAD_HEADER, filename);
 	delete checker;
 	checker = NULL;
 
@@ -316,7 +331,7 @@ bool initSludge(char *filename) {
 				return false;
 			}
 			png_init_io(png_ptr, fp);       // Tell libpng which file to read
-			png_set_sig_bytes(png_ptr, 8);  // 8 bytes already read
+			png_set_sig_bytes(png_ptr, 8);// 8 bytes already read
 
 			png_read_info(png_ptr, info_ptr);
 
@@ -348,7 +363,7 @@ bool initSludge(char *filename) {
 		if (fileIsPNG) {
 			unsigned char *row_pointers[iconH];
 			for (int i = 0; i < iconH; i++)
-				row_pointers[i] = p + 4 * i * iconW;
+			row_pointers[i] = p + 4 * i * iconW;
 
 			png_read_image(png_ptr, (png_byte **) row_pointers);
 			png_read_end(png_ptr, NULL);
@@ -425,7 +440,7 @@ bool initSludge(char *filename) {
 				return false;
 			}
 			png_init_io(png_ptr, fp);       // Tell libpng which file to read
-			png_set_sig_bytes(png_ptr, 8);  // 8 bytes already read
+			png_set_sig_bytes(png_ptr, 8);// 8 bytes already read
 
 			png_read_info(png_ptr, info_ptr);
 
@@ -443,8 +458,8 @@ bool initSludge(char *filename) {
 #ifdef WIN32
 			// Windows wants a BGR bitmap
 			if (color_type == PNG_COLOR_TYPE_RGB ||
-			        color_type == PNG_COLOR_TYPE_RGB_ALPHA)
-				png_set_bgr(png_ptr);
+					color_type == PNG_COLOR_TYPE_RGB_ALPHA)
+			png_set_bgr(png_ptr);
 #endif
 
 			png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER);
@@ -465,7 +480,7 @@ bool initSludge(char *filename) {
 		if (fileIsPNG) {
 			unsigned char *row_pointers[logoH];
 			for (int i = 0; i < logoH; i++)
-				row_pointers[i] = p + 4 * i * logoW;
+			row_pointers[i] = p + 4 * i * logoW;
 
 			png_read_image(png_ptr, (png_byte **) row_pointers);
 			png_read_end(png_ptr, NULL);
@@ -493,7 +508,7 @@ bool initSludge(char *filename) {
 						*p++ = (Uint8) greenValue(c);
 						*p++ = (Uint8) blueValue(c);
 #endif
-						*p++ = (Uint8) /*(c == transCol) ? 0 :*/ 255;
+						*p++ = (Uint8) /*(c == transCol) ? 0 :*/255;
 
 						t1++;
 					}
@@ -507,8 +522,10 @@ bool initSludge(char *filename) {
 	debug("numGlobals : %i", numGlobals);
 
 	globalVars = new variable[numGlobals];
-	if (!checkNew(globalVars)) return false;
-	for (a = 0; a < numGlobals; a ++) initVarNew(globalVars[a]);
+	if (!checkNew(globalVars))
+		return false;
+	for (a = 0; a < numGlobals; a++)
+		initVarNew(globalVars[a]);
 
 	// Get the original (untranslated) name of the game and convert it to Unicode.
 	// We use this to find saved preferences and saved games.
@@ -530,7 +547,7 @@ bool initSludge(char *filename) {
 
 	if (chdir(gameName)) return fatal("This game's preference folder is inaccessible!\nI can't access the following directory (maybe there's a file with the same name, or maybe it's read-protected):", gameName);
 #endif
-	delete [] gameName;
+	delete[] gameName;
 
 	// Get user settings
 	readIniFile(filename);
@@ -551,7 +568,8 @@ bool initSludge(char *filename) {
 
 	// Now set file indices properly to the chosen language.
 	languageNum = getLanguageForFileB();
-	if (languageNum < 0) return fatal("Can't find the translation data specified!");
+	if (languageNum < 0)
+		return fatal("Can't find the translation data specified!");
 	setFileIndices(NULL, gameSettings.numLanguages, languageNum);
 
 	if (dataFol[0]) {
@@ -581,8 +599,8 @@ bool checkColourChange(bool reset) {
 	static GLuint oldPixel;
 	static GLuint pixel;
 	glReadPixels((GLint)(viewportOffsetX + input.mouseX * viewportWidth / ((float)winWidth / cameraZoom)),
-	             (GLint)(viewportOffsetY + (((float)winHeight / cameraZoom) - input.mouseY)*viewportHeight / ((float)winHeight / cameraZoom)),
-	             1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixel);
+			(GLint)(viewportOffsetY + (((float)winHeight / cameraZoom) - input.mouseY)*viewportHeight / ((float)winHeight / cameraZoom)),
+			1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixel);
 
 	if (reset || oldPixel != pixel) {
 		oldPixel = pixel;
@@ -631,21 +649,21 @@ void sludgeDisplay() {
 		fbo_tex_w = (float)realWinWidth / width;
 		fbo_tex_h = (float)realWinHeight / height;
 		// create shader for blitting the fbo...
-		const char _blit_vsh[] = "                              \n\t" \
-		                         "attribute highp vec2 aPosition;                        \n\t" \
-		                         "attribute highp vec2 aTexCoord;                        \n\t" \
-		                         "varying mediump vec2 vTexCoord;                        \n\t" \
-		                         "void main(){                                           \n\t" \
-		                         "gl_Position = vec4(aPosition.x, aPosition.y, 0.0, 1.0);\n\t" \
-		                         "vTexCoord = aTexCoord;                                 \n\t" \
-		                         "}                                                      \n\t";
-
-		const char _blit_fsh[] = "                              \n\t" \
-		                         "uniform sampler2D uTex;                                \n\t" \
-		                         "varying mediump vec2 vTexCoord;                        \n\t" \
-		                         "void main(){                                           \n\t" \
-		                         "gl_FragColor = texture2D(uTex, vTexCoord);             \n\t" \
-		                         "}                                                      \n\t";
+		const char _blit_vsh[] = "                              \n\t"
+		"attribute highp vec2 aPosition;                        \n\t"
+		"attribute highp vec2 aTexCoord;                        \n\t"
+		"varying mediump vec2 vTexCoord;                        \n\t"
+		"void main(){                                           \n\t"
+		"gl_Position = vec4(aPosition.x, aPosition.y, 0.0, 1.0);\n\t"
+		"vTexCoord = aTexCoord;                                 \n\t"
+		"}                                                      \n\t";
+
+		const char _blit_fsh[] = "                              \n\t"
+		"uniform sampler2D uTex;                                \n\t"
+		"varying mediump vec2 vTexCoord;                        \n\t"
+		"void main(){                                           \n\t"
+		"gl_FragColor = texture2D(uTex, vTexCoord);             \n\t"
+		"}                                                      \n\t";
 
 		GLint success;
 		fbo_frag = glCreateShader(GL_FRAGMENT_SHADER);
@@ -682,20 +700,20 @@ void sludgeDisplay() {
 
 	glDepthMask(GL_TRUE);
 //	glClearColor(0.5, 0.5, 1.0, 0.0);
-	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen
+	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Clear The Screen
 	glDepthMask(GL_FALSE);
 
-	drawBackDrop();                 // Draw the room
+	drawBackDrop();// Draw the room
 	drawZBuffer(cameraX, cameraY, false);
 
 	glEnable(GL_DEPTH_TEST);
-	drawPeople();                   // Then add any moving characters...
+	drawPeople();// Then add any moving characters...
 	glDisable(GL_DEPTH_TEST);
-	viewSpeech();                   // ...and anything being said
+	viewSpeech();// ...and anything being said
 	drawStatusBar();
 	displayCursor();
 
-	if (brightnessLevel < 255) fixBrightness();     // This is for transitionLevel special effects
+	if (brightnessLevel < 255) fixBrightness();// This is for transitionLevel special effects
 
 	glFlush();
 #if !defined(HAVE_GLES2)
@@ -735,13 +753,13 @@ void sludgeDisplay() {
 }
 
 void pauseFunction(loadedFunction *fun) {
-	loadedFunction * * huntAndDestroy = & allRunningFunctions;
-	while (* huntAndDestroy) {
-		if (fun == * huntAndDestroy) {
-			(* huntAndDestroy) = (* huntAndDestroy)->next;
+	loadedFunction * * huntAndDestroy = &allRunningFunctions;
+	while (*huntAndDestroy) {
+		if (fun == *huntAndDestroy) {
+			(*huntAndDestroy) = (*huntAndDestroy)->next;
 			fun->next = NULL;
 		} else {
-			huntAndDestroy = & (* huntAndDestroy)->next;
+			huntAndDestroy = &(*huntAndDestroy)->next;
 		}
 	}
 }
@@ -755,7 +773,8 @@ void killSpeechTimers() {
 	loadedFunction *thisFunction = allRunningFunctions;
 
 	while (thisFunction) {
-		if (thisFunction->freezerLevel == 0 && thisFunction->isSpeech && thisFunction->timeLeft) {
+		if (thisFunction->freezerLevel == 0 && thisFunction->isSpeech
+				&& thisFunction->timeLeft) {
 			thisFunction->timeLeft = 0;
 			thisFunction->isSpeech = false;
 		}
@@ -769,7 +788,8 @@ void completeTimers() {
 	loadedFunction *thisFunction = allRunningFunctions;
 
 	while (thisFunction) {
-		if (thisFunction->freezerLevel == 0) thisFunction->timeLeft = 0;
+		if (thisFunction->freezerLevel == 0)
+			thisFunction->timeLeft = 0;
 		thisFunction = thisFunction->next;
 	}
 }
@@ -778,9 +798,11 @@ void finishFunction(loadedFunction *fun) {
 	int a;
 
 	pauseFunction(fun);
-	if (fun->stack) fatal(ERROR_NON_EMPTY_STACK);
+	if (fun->stack)
+		fatal(ERROR_NON_EMPTY_STACK);
 	delete fun->compiledLines;
-	for (a = 0; a < fun->numLocals; a ++) unlinkVar(fun->localVars[a]);
+	for (a = 0; a < fun->numLocals; a++)
+		unlinkVar(fun->localVars[a]);
 	delete fun->localVars;
 	unlinkVar(fun->reg);
 	delete fun;
@@ -791,12 +813,15 @@ void abortFunction(loadedFunction *fun) {
 	int a;
 
 	pauseFunction(fun);
-	while (fun->stack) trimStack(fun->stack);
+	while (fun->stack)
+		trimStack(fun->stack);
 	delete fun->compiledLines;
-	for (a = 0; a < fun->numLocals; a ++) unlinkVar(fun->localVars[a]);
+	for (a = 0; a < fun->numLocals; a++)
+		unlinkVar(fun->localVars[a]);
 	delete fun->localVars;
 	unlinkVar(fun->reg);
-	if (fun->calledBy) abortFunction(fun->calledBy);
+	if (fun->calledBy)
+		abortFunction(fun->calledBy);
 	delete fun;
 	fun = NULL;
 }
@@ -809,8 +834,9 @@ int cancelAFunction(int funcNum, loadedFunction *myself, bool &killedMyself) {
 	while (fun) {
 		if (fun->originalNumber == funcNum) {
 			fun->cancelMe = true;
-			n ++;
-			if (fun == myself) killedMyself = true;
+			n++;
+			if (fun == myself)
+				killedMyself = true;
 		}
 		fun = fun->next;
 	}
@@ -824,7 +850,7 @@ void freezeSubs() {
 		if (thisFunction->unfreezable) {
 			//msgBox ("SLUDGE debugging bollocks!", "Trying to freeze an unfreezable function!");
 		} else {
-			thisFunction->freezerLevel ++;
+			thisFunction->freezerLevel++;
 		}
 		thisFunction = thisFunction->next;
 	}
@@ -834,12 +860,12 @@ void unfreezeSubs() {
 	loadedFunction *thisFunction = allRunningFunctions;
 
 	while (thisFunction) {
-		if (thisFunction->freezerLevel) thisFunction->freezerLevel --;
+		if (thisFunction->freezerLevel)
+			thisFunction->freezerLevel--;
 		thisFunction = thisFunction->next;
 	}
 }
 
-
 bool continueFunction(loadedFunction *fun) {
 	bool keepLooping = true;
 	bool advanceNow;
@@ -864,8 +890,11 @@ bool continueFunction(loadedFunction *fun) {
 
 		if (numBIFNames) {
 			setFatalInfo(
-			    (fun->originalNumber < numUserFunc) ? allUserFunc[fun->originalNumber] : "Unknown user function",
-			    (com < numSludgeCommands) ? sludgeText[com] : ERROR_UNKNOWN_MCODE);
+					(fun->originalNumber < numUserFunc) ?
+							allUserFunc[fun->originalNumber] :
+							"Unknown user function",
+					(com < numSludgeCommands) ?
+							sludgeText[com] : ERROR_UNKNOWN_MCODE);
 //			newDebug (
 //				(com < numSludgeCommands) ? sludgeText[com] : "Unknown SLUDGE machine code",
 //				param);
@@ -877,13 +906,14 @@ bool continueFunction(loadedFunction *fun) {
 		case SLU_RETURN:
 			if (fun->calledBy) {
 				loadedFunction *returnTo = fun->calledBy;
-				if (fun->returnSomething) copyVariable(fun->reg, returnTo->reg);
+				if (fun->returnSomething)
+					copyVariable(fun->reg, returnTo->reg);
 				finishFunction(fun);
 				fun = returnTo;
 				restartFunction(fun);
 			} else {
 				finishFunction(fun);
-				advanceNow = false;     // So we don't do anything else with "fun"
+				advanceNow = false;   // So we don't do anything else with "fun"
 				keepLooping = false;    // So we drop out of the loop
 			}
 			break;
@@ -892,26 +922,36 @@ bool continueFunction(loadedFunction *fun) {
 			switch (fun->reg.varType) {
 			case SVT_FUNC:
 				pauseFunction(fun);
-				if (numBIFNames) setFatalInfo(
-					    (fun->originalNumber < numUserFunc) ? allUserFunc[fun->originalNumber] : "Unknown user function",
-					    (fun->reg.varData.intValue < numUserFunc) ? allUserFunc[fun->reg.varData.intValue] : "Unknown user function");
-
-				if (!startNewFunctionNum(fun->reg.varData.intValue, param, fun, fun->stack)) return false;
+				if (numBIFNames)
+					setFatalInfo(
+							(fun->originalNumber < numUserFunc) ?
+									allUserFunc[fun->originalNumber] :
+									"Unknown user function",
+							(fun->reg.varData.intValue < numUserFunc) ?
+									allUserFunc[fun->reg.varData.intValue] :
+									"Unknown user function");
+
+				if (!startNewFunctionNum(fun->reg.varData.intValue, param, fun,
+						fun->stack))
+					return false;
 				fun = allRunningFunctions;
-				advanceNow = false;     // So we don't do anything else with "fun"
+				advanceNow = false;   // So we don't do anything else with "fun"
 				break;
 
 			case SVT_BUILT: {
-				debug(kSludgeDebugStackMachine, "Built-in init value: %i", fun->reg.varData.intValue);
-				builtReturn br = callBuiltIn(fun->reg.varData.intValue, param, fun);
+				debug(kSludgeDebugStackMachine, "Built-in init value: %i",
+						fun->reg.varData.intValue);
+				builtReturn br = callBuiltIn(fun->reg.varData.intValue, param,
+						fun);
 
 				switch (br) {
 				case BR_ERROR:
-					return fatal("Unknown error. This shouldn't happen. Please notify the SLUDGE developers.");
+					return fatal(
+							"Unknown error. This shouldn't happen. Please notify the SLUDGE developers.");
 
 				case BR_PAUSE:
 					pauseFunction(fun);
-				// No break!
+					// No break!
 
 				case BR_KEEP_AND_PAUSE:
 					keepLooping = false;
@@ -926,27 +966,33 @@ bool continueFunction(loadedFunction *fun) {
 					int i = fun->reg.varData.intValue;
 					setVariable(fun->reg, SVT_INT, 1);
 					pauseFunction(fun);
-					if (numBIFNames) setFatalInfo(
-						    (fun->originalNumber < numUserFunc) ? allUserFunc[fun->originalNumber] : "Unknown user function",
-						    (i < numUserFunc) ? allUserFunc[i] : "Unknown user function");
-					if (!startNewFunctionNum(i, 0, fun, noStack, false)) return false;
+					if (numBIFNames)
+						setFatalInfo(
+								(fun->originalNumber < numUserFunc) ?
+										allUserFunc[fun->originalNumber] :
+										"Unknown user function",
+								(i < numUserFunc) ?
+										allUserFunc[i] :
+										"Unknown user function");
+					if (!startNewFunctionNum(i, 0, fun, noStack, false))
+						return false;
 					fun = allRunningFunctions;
-					advanceNow = false;     // So we don't do anything else with "fun"
+					advanceNow = false; // So we don't do anything else with "fun"
 				}
-				break;
+					break;
 
 				default:
 					break;
 				}
 			}
-			break;
+				break;
 
 			default:
 				return fatal(ERROR_CALL_NONFUNCTION);
 			}
 			break;
 
-		// These all grab things and shove 'em into the register
+			// These all grab things and shove 'em into the register
 
 		case SLU_LOAD_NULL:
 			setVariable(fun->reg, SVT_NULL, 0);
@@ -961,16 +1007,19 @@ bool continueFunction(loadedFunction *fun) {
 			break;
 
 		case SLU_LOAD_LOCAL:
-			if (!copyVariable(fun->localVars[param], fun->reg)) return false;
+			if (!copyVariable(fun->localVars[param], fun->reg))
+				return false;
 			break;
 
 		case SLU_AND:
-			setVariable(fun->reg, SVT_INT, getBoolean(fun->reg) && getBoolean(fun->stack->thisVar));
+			setVariable(fun->reg, SVT_INT,
+					getBoolean(fun->reg) && getBoolean(fun->stack->thisVar));
 			trimStack(fun->stack);
 			break;
 
 		case SLU_OR:
-			setVariable(fun->reg, SVT_INT, getBoolean(fun->reg) || getBoolean(fun->stack->thisVar));
+			setVariable(fun->reg, SVT_INT,
+					getBoolean(fun->reg) || getBoolean(fun->stack->thisVar));
 			trimStack(fun->stack);
 			break;
 
@@ -987,7 +1036,8 @@ bool continueFunction(loadedFunction *fun) {
 			break;
 
 		case SLU_UNREG:
-			if (dialogValue != 1) fatal(ERROR_HACKER);
+			if (dialogValue != 1)
+				fatal(ERROR_HACKER);
 			break;
 
 		case SLU_LOAD_STRING:
@@ -1015,11 +1065,16 @@ bool continueFunction(loadedFunction *fun) {
 					return fatal(ERROR_INDEX_EMPTY);
 				} else {
 					int ii;
-					if (!getValueType(ii, SVT_INT, fun->reg)) return false;
-					variable *grab = (fun->stack->thisVar.varType == SVT_FASTARRAY) ?
-					                 fastArrayGetByIndex(fun->stack->thisVar.varData.fastArray, ii)
-					                 :
-					                 stackGetByIndex(fun->stack->thisVar.varData.theStack->first, ii);
+					if (!getValueType(ii, SVT_INT, fun->reg))
+						return false;
+					variable *grab =
+							(fun->stack->thisVar.varType == SVT_FASTARRAY) ?
+									fastArrayGetByIndex(
+											fun->stack->thisVar.varData.fastArray,
+											ii) :
+									stackGetByIndex(
+											fun->stack->thisVar.varData.theStack->first,
+											ii);
 
 					trimStack(fun->stack);
 
@@ -1029,19 +1084,22 @@ bool continueFunction(loadedFunction *fun) {
 						int ii;
 						switch (com) {
 						case SLU_INCREMENT_INDEX:
-							if (!getValueType(ii, SVT_INT, * grab)) return false;
+							if (!getValueType(ii, SVT_INT, *grab))
+								return false;
 							setVariable(fun->reg, SVT_INT, ii);
 							grab->varData.intValue = ii + 1;
 							break;
 
 						case SLU_DECREMENT_INDEX:
-							if (!getValueType(ii, SVT_INT, * grab)) return false;
+							if (!getValueType(ii, SVT_INT, *grab))
+								return false;
 							setVariable(fun->reg, SVT_INT, ii);
 							grab->varData.intValue = ii - 1;
 							break;
 
 						default:
-							if (!copyVariable(* grab, fun->reg)) return false;
+							if (!copyVariable(*grab, fun->reg))
+								return false;
 						}
 					}
 				}
@@ -1059,8 +1117,11 @@ bool continueFunction(loadedFunction *fun) {
 					return fatal(ERROR_INDEX_EMPTY);
 				} else {
 					int ii;
-					if (!getValueType(ii, SVT_INT, fun->reg)) return false;
-					if (!stackSetByIndex(fun->stack->thisVar.varData.theStack->first, ii, fun->stack->next->thisVar)) {
+					if (!getValueType(ii, SVT_INT, fun->reg))
+						return false;
+					if (!stackSetByIndex(
+							fun->stack->thisVar.varData.theStack->first, ii,
+							fun->stack->next->thisVar)) {
 						return false;
 					}
 					trimStack(fun->stack);
@@ -1070,78 +1131,91 @@ bool continueFunction(loadedFunction *fun) {
 
 			case SVT_FASTARRAY: {
 				int ii;
-				if (!getValueType(ii, SVT_INT, fun->reg)) return false;
-				variable *v = fastArrayGetByIndex(fun->stack->thisVar.varData.fastArray, ii);
-				if (v == NULL) return fatal("Not within bounds of fast array.");
-				if (!copyVariable(fun->stack->next->thisVar, * v)) return false;
+				if (!getValueType(ii, SVT_INT, fun->reg))
+					return false;
+				variable *v = fastArrayGetByIndex(
+						fun->stack->thisVar.varData.fastArray, ii);
+				if (v == NULL)
+					return fatal("Not within bounds of fast array.");
+				if (!copyVariable(fun->stack->next->thisVar, *v))
+					return false;
 				trimStack(fun->stack);
 				trimStack(fun->stack);
 			}
-			break;
+				break;
 
 			default:
 				return fatal(ERROR_INDEX_NONSTACK);
 			}
 			break;
 
-		// What can we do with the register? Well, we can copy it into a local
-		// variable, a global or onto the stack...
+			// What can we do with the register? Well, we can copy it into a local
+			// variable, a global or onto the stack...
 
 		case SLU_INCREMENT_LOCAL: {
 			int ii;
-			if (!getValueType(ii, SVT_INT, fun->localVars[param])) return false;
+			if (!getValueType(ii, SVT_INT, fun->localVars[param]))
+				return false;
 			setVariable(fun->reg, SVT_INT, ii);
 			setVariable(fun->localVars[param], SVT_INT, ii + 1);
 		}
-		break;
+			break;
 
 		case SLU_INCREMENT_GLOBAL: {
 			int ii;
-			if (!getValueType(ii, SVT_INT, globalVars[param])) return false;
+			if (!getValueType(ii, SVT_INT, globalVars[param]))
+				return false;
 			setVariable(fun->reg, SVT_INT, ii);
 			setVariable(globalVars[param], SVT_INT, ii + 1);
 		}
-		break;
+			break;
 
 		case SLU_DECREMENT_LOCAL: {
 			int ii;
-			if (!getValueType(ii, SVT_INT, fun->localVars[param])) return false;
+			if (!getValueType(ii, SVT_INT, fun->localVars[param]))
+				return false;
 			setVariable(fun->reg, SVT_INT, ii);
 			setVariable(fun->localVars[param], SVT_INT, ii - 1);
 		}
-		break;
+			break;
 
 		case SLU_DECREMENT_GLOBAL: {
 			int ii;
-			if (!getValueType(ii, SVT_INT, globalVars[param])) return false;
+			if (!getValueType(ii, SVT_INT, globalVars[param]))
+				return false;
 			setVariable(fun->reg, SVT_INT, ii);
 			setVariable(globalVars[param], SVT_INT, ii - 1);
 		}
-		break;
+			break;
 
 		case SLU_SET_LOCAL:
-			if (!copyVariable(fun->reg, fun->localVars[param])) return false;
+			if (!copyVariable(fun->reg, fun->localVars[param]))
+				return false;
 			break;
 
 		case SLU_SET_GLOBAL:
 //			newDebug ("  Copying TO global variable", param);
 //			newDebug ("  Global type at the moment", globalVars[param].varType);
-			if (!copyVariable(fun->reg, globalVars[param])) return false;
+			if (!copyVariable(fun->reg, globalVars[param]))
+				return false;
 //			newDebug ("  New type", globalVars[param].varType);
 			break;
 
 		case SLU_LOAD_GLOBAL:
 //			newDebug ("  Copying FROM global variable", param);
 //			newDebug ("  Global type at the moment", globalVars[param].varType);
-			if (!copyVariable(globalVars[param], fun->reg)) return false;
+			if (!copyVariable(globalVars[param], fun->reg))
+				return false;
 			break;
 
 		case SLU_STACK_PUSH:
-			if (!addVarToStack(fun->reg, fun->stack)) return false;
+			if (!addVarToStack(fun->reg, fun->stack))
+				return false;
 			break;
 
 		case SLU_QUICK_PUSH:
-			if (!addVarToStackQuick(fun->reg, fun->stack)) return false;
+			if (!addVarToStackQuick(fun->reg, fun->stack))
+				return false;
 			break;
 
 		case SLU_NOT:
@@ -1162,12 +1236,13 @@ bool continueFunction(loadedFunction *fun) {
 
 		case SLU_NEGATIVE: {
 			int i;
-			if (!getValueType(i, SVT_INT, fun->reg)) return false;
+			if (!getValueType(i, SVT_INT, fun->reg))
+				return false;
 			setVariable(fun->reg, SVT_INT, -i);
 		}
-		break;
+			break;
 
-		// All these things rely on there being somet' on the stack
+			// All these things rely on there being somet' on the stack
 
 		case SLU_MULT:
 		case SLU_PLUS:
@@ -1201,41 +1276,51 @@ bool continueFunction(loadedFunction *fun) {
 					break;
 
 				default:
-					if (!getValueType(firstValue, SVT_INT, fun->stack->thisVar)) return false;
-					if (!getValueType(secondValue, SVT_INT, fun->reg)) return false;
+					if (!getValueType(firstValue, SVT_INT, fun->stack->thisVar))
+						return false;
+					if (!getValueType(secondValue, SVT_INT, fun->reg))
+						return false;
 					trimStack(fun->stack);
 
 					switch (com) {
 					case SLU_MULT:
-						setVariable(fun->reg, SVT_INT, firstValue * secondValue);
+						setVariable(fun->reg, SVT_INT,
+								firstValue * secondValue);
 						break;
 
 					case SLU_MINUS:
-						setVariable(fun->reg, SVT_INT, firstValue - secondValue);
+						setVariable(fun->reg, SVT_INT,
+								firstValue - secondValue);
 						break;
 
 					case SLU_MODULUS:
-						setVariable(fun->reg, SVT_INT, firstValue % secondValue);
+						setVariable(fun->reg, SVT_INT,
+								firstValue % secondValue);
 						break;
 
 					case SLU_DIVIDE:
-						setVariable(fun->reg, SVT_INT, firstValue / secondValue);
+						setVariable(fun->reg, SVT_INT,
+								firstValue / secondValue);
 						break;
 
 					case SLU_LESSTHAN:
-						setVariable(fun->reg, SVT_INT, firstValue < secondValue);
+						setVariable(fun->reg, SVT_INT,
+								firstValue < secondValue);
 						break;
 
 					case SLU_MORETHAN:
-						setVariable(fun->reg, SVT_INT, firstValue > secondValue);
+						setVariable(fun->reg, SVT_INT,
+								firstValue > secondValue);
 						break;
 
 					case SLU_LESS_EQUAL:
-						setVariable(fun->reg, SVT_INT, firstValue <= secondValue);
+						setVariable(fun->reg, SVT_INT,
+								firstValue <= secondValue);
 						break;
 
 					case SLU_MORE_EQUAL:
-						setVariable(fun->reg, SVT_INT, firstValue >= secondValue);
+						setVariable(fun->reg, SVT_INT,
+								firstValue >= secondValue);
 						break;
 
 					default:
@@ -1251,13 +1336,13 @@ bool continueFunction(loadedFunction *fun) {
 			return fatal(ERROR_UNKNOWN_CODE);
 		}
 
-		if (advanceNow) fun->runThisLine ++;
+		if (advanceNow)
+			fun->runThisLine++;
 
 	}
 	return true;
 }
 
-
 bool runSludge() {
 
 	loadedFunction *thisFunction = allRunningFunctions;
@@ -1269,10 +1354,11 @@ bool runSludge() {
 		if (!thisFunction->freezerLevel) {
 			if (thisFunction->timeLeft) {
 				if (thisFunction->timeLeft < 0) {
-					if (!stillPlayingSound(findInSoundCache(speech->lastFile))) {
+					if (!stillPlayingSound(
+							findInSoundCache(speech->lastFile))) {
 						thisFunction->timeLeft = 0;
 					}
-				} else if (!-- (thisFunction->timeLeft)) {
+				} else if (!--(thisFunction->timeLeft)) {
 				}
 			} else {
 				if (thisFunction->isSpeech) {
@@ -1292,7 +1378,8 @@ bool runSludge() {
 			saveGame(loadNow + 1);
 			setVariable(saverFunc->reg, SVT_INT, 1);
 		} else {
-			if (!loadGame(loadNow)) return false;
+			if (!loadGame(loadNow))
+				return false;
 		}
 		delete loadNow;
 		loadNow = NULL;
@@ -1306,52 +1393,62 @@ bool loadFunctionCode(loadedFunction *newFunc) {
 	debug(kSludgeDebugDataLoad, "Current address: %i", bigDataFile->pos());
 	unsigned int numLines, numLinesRead;
 
-	if (!openSubSlice(newFunc->originalNumber)) return false;
+	if (!openSubSlice(newFunc->originalNumber))
+		return false;
 
 	debug(kSludgeDebugDataLoad, "Load function code");
 
-	newFunc->unfreezable  = getch(bigDataFile);
-	numLines                = get2bytes(bigDataFile);
+	newFunc->unfreezable = getch(bigDataFile);
+	numLines = get2bytes(bigDataFile);
 	debug(kSludgeDebugDataLoad, "numLines: %i", numLines);
-	newFunc->numArgs      = get2bytes(bigDataFile);
+	newFunc->numArgs = get2bytes(bigDataFile);
 	debug(kSludgeDebugDataLoad, "numArgs: %i", newFunc->numArgs);
-	newFunc->numLocals    = get2bytes(bigDataFile);
+	newFunc->numLocals = get2bytes(bigDataFile);
 	debug(kSludgeDebugDataLoad, "numLocals: %i", newFunc->numLocals);
 	newFunc->compiledLines = new lineOfCode[numLines];
-	if (!checkNew(newFunc->compiledLines)) return false;
+	if (!checkNew(newFunc->compiledLines))
+		return false;
 
-	for (numLinesRead = 0; numLinesRead < numLines; numLinesRead ++) {
-		newFunc->compiledLines[numLinesRead].theCommand = (sludgeCommand) getch(bigDataFile);
+	for (numLinesRead = 0; numLinesRead < numLines; numLinesRead++) {
+		newFunc->compiledLines[numLinesRead].theCommand = (sludgeCommand) getch(
+				bigDataFile);
 		newFunc->compiledLines[numLinesRead].param = get2bytes(bigDataFile);
-		debug(kSludgeDebugDataLoad, "command line %i: %i", numLinesRead, newFunc->compiledLines[numLinesRead].theCommand);
+		debug(kSludgeDebugDataLoad, "command line %i: %i", numLinesRead,
+				newFunc->compiledLines[numLinesRead].theCommand);
 	}
 	finishAccess();
 
 	// Now we need to reserve memory for the local variables
 	newFunc->localVars = new variable[newFunc->numLocals];
-	if (!checkNew(newFunc->localVars)) return false;
-	for (int a = 0; a < newFunc->numLocals; a ++) {
+	if (!checkNew(newFunc->localVars))
+		return false;
+	for (int a = 0; a < newFunc->numLocals; a++) {
 		initVarNew(newFunc->localVars[a]);
 	}
 
 	return true;
 }
 
-int startNewFunctionNum(unsigned int funcNum, unsigned int numParamsExpected, loadedFunction *calledBy, variableStack *&vStack, bool returnSommet) {
+int startNewFunctionNum(unsigned int funcNum, unsigned int numParamsExpected,
+		loadedFunction *calledBy, variableStack *&vStack, bool returnSommet) {
 	loadedFunction *newFunc = new loadedFunction;
 	checkNew(newFunc);
 	newFunc->originalNumber = funcNum;
 
 	loadFunctionCode(newFunc);
 
-	if (newFunc->numArgs != (int)numParamsExpected) return fatal("Wrong number of parameters!");
-	if (newFunc->numArgs > newFunc->numLocals) return fatal("More arguments than local variable space!");
+	if (newFunc->numArgs != (int) numParamsExpected)
+		return fatal("Wrong number of parameters!");
+	if (newFunc->numArgs > newFunc->numLocals)
+		return fatal("More arguments than local variable space!");
 
 	// Now, lets copy the parameters from the calling function's stack...
 
 	while (numParamsExpected) {
-		numParamsExpected --;
-		if (vStack == NULL) return fatal("Corrupted file!The stack's empty and there were still parameters expected");
+		numParamsExpected--;
+		if (vStack == NULL)
+			return fatal(
+					"Corrupted file!The stack's empty and there were still parameters expected");
 		copyVariable(vStack->thisVar, newFunc->localVars[numParamsExpected]);
 		trimStack(vStack);
 	}
@@ -1397,7 +1494,7 @@ bool handleInput() {
 		} else {
 			l = 1;
 
-			setVariable(* launchResult, SVT_INT, 0/*launch(launchMe) > 31*/); //TODO:false value
+			setVariable(*launchResult, SVT_INT, 0/*launch(launchMe) > 31*/); //TODO:false value
 			launchMe = NULL;
 			launchResult = NULL;
 		}
@@ -1406,38 +1503,53 @@ bool handleInput() {
 		l = 0;
 	}
 
-	if (!overRegion) getOverRegion();
+	if (!overRegion)
+		getOverRegion();
 
 	if (input.justMoved) {
 		if (currentEvents->moveMouseFunction) {
-			if (!startNewFunctionNum(currentEvents->moveMouseFunction, 0, NULL, noStack)) return false;
+			if (!startNewFunctionNum(currentEvents->moveMouseFunction, 0, NULL,
+					noStack))
+				return false;
 		}
 	}
 	input.justMoved = false;
 
 	if (lastRegion != overRegion && currentEvents->focusFunction) {
 		variableStack *tempStack = new variableStack;
-		if (!checkNew(tempStack)) return false;
+		if (!checkNew(tempStack))
+			return false;
 
 		initVarNew(tempStack->thisVar);
 		if (overRegion) {
-			setVariable(tempStack->thisVar, SVT_OBJTYPE, overRegion->thisType->objectNum);
+			setVariable(tempStack->thisVar, SVT_OBJTYPE,
+					overRegion->thisType->objectNum);
 		} else {
 			setVariable(tempStack->thisVar, SVT_INT, 0);
 		}
 		tempStack->next = NULL;
-		if (!startNewFunctionNum(currentEvents->focusFunction, 1, NULL, tempStack)) return false;
+		if (!startNewFunctionNum(currentEvents->focusFunction, 1, NULL,
+				tempStack))
+			return false;
 	}
-	if (input.leftRelease && currentEvents->leftMouseUpFunction)  {
-		if (!startNewFunctionNum(currentEvents->leftMouseUpFunction, 0, NULL, noStack)) return false;
+	if (input.leftRelease && currentEvents->leftMouseUpFunction) {
+		if (!startNewFunctionNum(currentEvents->leftMouseUpFunction, 0, NULL,
+				noStack))
+			return false;
 	}
 	if (input.rightRelease && currentEvents->rightMouseUpFunction) {
-		if (!startNewFunctionNum(currentEvents->rightMouseUpFunction, 0, NULL, noStack)) return false;
+		if (!startNewFunctionNum(currentEvents->rightMouseUpFunction, 0, NULL,
+				noStack))
+			return false;
 	}
 	if (input.leftClick && currentEvents->leftMouseFunction)
-		if (!startNewFunctionNum(currentEvents->leftMouseFunction, 0, NULL, noStack)) return false;
+		if (!startNewFunctionNum(currentEvents->leftMouseFunction, 0, NULL,
+				noStack))
+			return false;
 	if (input.rightClick && currentEvents->rightMouseFunction) {
-		if (!startNewFunctionNum(currentEvents->rightMouseFunction, 0, NULL, noStack)) return false;
+		if (!startNewFunctionNum(currentEvents->rightMouseFunction, 0, NULL,
+				noStack))
+			return false;
 	}
 	if (input.keyPressed && currentEvents->spaceFunction) {
 		char *tempString = NULL;
@@ -1454,22 +1566,22 @@ bool handleInput() {
 		case 27:
 			tempString = copyString("ESCAPE");
 			break;
-		/*
-		case 1112:  tempString = copyString ("ALT+F1");     break;
-		case 1113:  tempString = copyString ("ALT+F2");     break;
-		case 1114:  tempString = copyString ("ALT+F3");     break;
-		case 1115:  tempString = copyString ("ALT+F4");     break;
-		case 1116:  tempString = copyString ("ALT+F5");     break;
-		case 1117:  tempString = copyString ("ALT+F6");     break;
-		case 1118:  tempString = copyString ("ALT+F7");     break;
-		case 1119:  tempString = copyString ("ALT+F8");     break;
-		case 1120:  tempString = copyString ("ALT+F9");     break;
-		case 1121:  tempString = copyString ("ALT+F10");    break;
-		case 1122:  tempString = copyString ("ALT+F11");    break;
-		case 1123:  tempString = copyString ("ALT+F12");    break;
-
-		case 2019:  tempString = copyString ("PAUSE");      break;
-		*/
+			/*
+			 case 1112:  tempString = copyString ("ALT+F1");     break;
+			 case 1113:  tempString = copyString ("ALT+F2");     break;
+			 case 1114:  tempString = copyString ("ALT+F3");     break;
+			 case 1115:  tempString = copyString ("ALT+F4");     break;
+			 case 1116:  tempString = copyString ("ALT+F5");     break;
+			 case 1117:  tempString = copyString ("ALT+F6");     break;
+			 case 1118:  tempString = copyString ("ALT+F7");     break;
+			 case 1119:  tempString = copyString ("ALT+F8");     break;
+			 case 1120:  tempString = copyString ("ALT+F9");     break;
+			 case 1121:  tempString = copyString ("ALT+F10");    break;
+			 case 1122:  tempString = copyString ("ALT+F11");    break;
+			 case 1123:  tempString = copyString ("ALT+F12");    break;
+
+			 case 2019:  tempString = copyString ("PAUSE");      break;
+			 */
 		case 63276:
 			tempString = copyString("PAGE UP");
 			break;
@@ -1494,10 +1606,10 @@ bool handleInput() {
 		case 63233:
 			tempString = copyString("DOWN");
 			break;
-		/*
-		case 2045:   tempString = copyString ("INSERT");     break;
-		case 2046:   tempString = copyString ("DELETE");     break;
-		*/
+			/*
+			 case 2045:   tempString = copyString ("INSERT");     break;
+			 case 2046:   tempString = copyString ("DELETE");     break;
+			 */
 		case 63236:
 			tempString = copyString("F1");
 			break;
@@ -1549,13 +1661,16 @@ bool handleInput() {
 
 		if (tempString) {
 			variableStack *tempStack = new variableStack;
-			if (!checkNew(tempStack)) return false;
+			if (!checkNew(tempStack))
+				return false;
 			initVarNew(tempStack->thisVar);
 			makeTextVar(tempStack->thisVar, tempString);
 			delete tempString;
 			tempString = NULL;
 			tempStack->next = NULL;
-			if (!startNewFunctionNum(currentEvents->spaceFunction, 1, NULL, tempStack)) return false;
+			if (!startNewFunctionNum(currentEvents->spaceFunction, 1, NULL,
+					tempStack))
+				return false;
 		}
 	}
 	input.rightClick = false;
diff --git a/engines/sludge/sludger.h b/engines/sludge/sludger.h
index d67192d..ef319db 100644
--- a/engines/sludge/sludger.h
+++ b/engines/sludge/sludger.h
@@ -59,17 +59,17 @@ struct lineOfCode {
 };
 
 struct loadedFunction {
-	int                         originalNumber;
-	lineOfCode                 *compiledLines;
-	int                         numLocals, timeLeft, numArgs;
-	variable                   *localVars;
-	variableStack              *stack;
-	variable                    reg;
-	unsigned int                runThisLine;
-	loadedFunction             *calledBy;
-	loadedFunction             *next;
-	bool                        returnSomething, isSpeech, unfreezable, cancelMe;
-	unsigned char               freezerLevel;
+	int originalNumber;
+	lineOfCode *compiledLines;
+	int numLocals, timeLeft, numArgs;
+	variable *localVars;
+	variableStack *stack;
+	variable reg;
+	unsigned int runThisLine;
+	loadedFunction *calledBy;
+	loadedFunction *next;
+	bool returnSomething, isSpeech, unfreezable, cancelMe;
+	unsigned char freezerLevel;
 };
 
 struct inputType {
@@ -80,10 +80,10 @@ struct inputType {
 extern unsigned char *gameIcon;
 extern int iconW, iconH;
 
-
 bool initSludge(char *);
 void sludgeDisplay();
-int startNewFunctionNum(unsigned int, unsigned int, loadedFunction *, variableStack*&, bool = true);
+int startNewFunctionNum(unsigned int, unsigned int, loadedFunction *,
+		variableStack*&, bool = true);
 bool handleInput();
 void restartFunction(loadedFunction *fun);
 bool loadFunctionCode(loadedFunction *newFunc);
@@ -92,7 +92,8 @@ void saveHandlers(Common::WriteStream *stream);
 
 void finishFunction(loadedFunction *fun);
 void abortFunction(loadedFunction *fun);
-Common::File *openAndVerify(char *filename, char extra1, char extra2, const char *er, int &fileVersion);
+Common::File *openAndVerify(char *filename, char extra1, char extra2,
+		const char *er, int &fileVersion);
 
 void freezeSubs();
 void unfreezeSubs();
diff --git a/engines/sludge/sound_bass.cpp b/engines/sludge/sound_bass.cpp
index 6f16d66..5bb4e79 100644
--- a/engines/sludge/sound_bass.cpp
+++ b/engines/sludge/sound_bass.cpp
@@ -49,9 +49,11 @@ soundThing soundCache[MAX_SAMPLES];
 int defVol = 128;
 int defSoundVol = 255;
 
-char *loadEntireFileToMemory(Common::SeekableReadStream *inputFile, uint32_t size) {
+char *loadEntireFileToMemory(Common::SeekableReadStream *inputFile,
+		uint32_t size) {
 	char *allData = new char[size];
-	if (!allData) return NULL;
+	if (!allData)
+		return NULL;
 	inputFile->read(allData, size);
 	finishAccess();
 
@@ -68,15 +70,17 @@ void stopMOD(int i) {
 
 int findInSoundCache(int a) {
 	int i;
-	for (i = 0; i < MAX_SAMPLES; i ++) {
-		if (soundCache[i].fileLoaded == a) return i;
+	for (i = 0; i < MAX_SAMPLES; i++) {
+		if (soundCache[i].fileLoaded == a)
+			return i;
 	}
 	return -1;
 }
 
 void huntKillSound(int filenum) {
 	int gotSlot = findInSoundCache(filenum);
-	if (gotSlot == -1) return;
+	if (gotSlot == -1)
+		return;
 	soundCache[gotSlot].looping = false;
 	BASS_SampleStop(soundCache[gotSlot].sample);
 }
@@ -90,7 +94,8 @@ void freeSound(int a) {
 
 void huntKillFreeSound(int filenum) {
 	int gotSlot = findInSoundCache(filenum);
-	if (gotSlot != -1) freeSound(gotSlot);
+	if (gotSlot != -1)
+		freeSound(gotSlot);
 }
 
 bool initSoundStuff(HWND hwnd) {
@@ -119,8 +124,10 @@ bool initSoundStuff(HWND hwnd) {
 void killSoundStuff() {
 	if (soundOK) {
 		int a;
-		for (a = 0; a < MAX_MODS;       a ++) stopMOD(a);
-		for (a = 0; a < MAX_SAMPLES;    a ++) freeSound(a);
+		for (a = 0; a < MAX_MODS; a++)
+			stopMOD(a);
+		for (a = 0; a < MAX_SAMPLES; a++)
+			freeSound(a);
 		BASS_Free();
 	}
 }
@@ -132,13 +139,19 @@ bool playMOD(int f, int a, int fromTrack) {
 
 		setResourceForFatal(f);
 		uint32_t length = openFileFromNum(f);
-		if (length == 0) return NULL;
+		if (length == 0)
+			return NULL;
 
 		char *memImage;
 		memImage = loadEntireFileToMemory(bigDataFile, length);
-		if (!memImage) return fatal(ERROR_MUSIC_MEMORY_LOW);
-
-		mod[a] = BASS_MusicLoad(true, memImage, 0, length, BASS_MUSIC_LOOP | BASS_MUSIC_RAMP/*|BASS_MUSIC_PRESCAN needed too if we're going to set the position in bytes*/, 0);
+		if (!memImage)
+			return fatal(ERROR_MUSIC_MEMORY_LOW);
+
+		mod[a] =
+				BASS_MusicLoad(true, memImage, 0, length,
+						BASS_MUSIC_LOOP
+								| BASS_MUSIC_RAMP/*|BASS_MUSIC_PRESCAN needed too if we're going to set the position in bytes*/,
+						0);
 		delete memImage;
 
 		if (!mod[a]) {
@@ -149,8 +162,10 @@ bool playMOD(int f, int a, int fromTrack) {
 			if (!BASS_ChannelPlay(mod[a], true))
 				debugOut("playMOD: Error %d!\n", BASS_ErrorGetCode());
 
-			BASS_ChannelSetPosition(mod[a], MAKELONG(fromTrack, 0), BASS_POS_MUSIC_ORDER);
-			BASS_ChannelFlags(mod[a], BASS_SAMPLE_LOOP | BASS_MUSIC_RAMP, BASS_SAMPLE_LOOP | BASS_MUSIC_RAMP);
+			BASS_ChannelSetPosition(mod[a], MAKELONG(fromTrack, 0),
+					BASS_POS_MUSIC_ORDER);
+			BASS_ChannelFlags(mod[a], BASS_SAMPLE_LOOP | BASS_MUSIC_RAMP,
+					BASS_SAMPLE_LOOP | BASS_MUSIC_RAMP);
 		}
 		setResourceForFatal(-1);
 	}
@@ -160,7 +175,8 @@ bool playMOD(int f, int a, int fromTrack) {
 void setMusicVolume(int a, int v) {
 	int ret;
 	if (soundOK && mod[a]) {
-		ret = BASS_ChannelSetAttribute(mod[a], BASS_ATTRIB_VOL, (float) v / 256);
+		ret = BASS_ChannelSetAttribute(mod[a], BASS_ATTRIB_VOL,
+				(float) v / 256);
 		if (!ret) {
 			debugOut("setMusicVolume: Error %d\n", BASS_ErrorGetCode());
 		}
@@ -176,7 +192,8 @@ void setSoundVolume(int a, int v) {
 		int ch = findInSoundCache(a);
 		if (ch != -1) {
 			if (BASS_ChannelIsActive(soundCache[ch].mostRecentChannel)) {
-				BASS_ChannelSetAttribute(soundCache[ch].mostRecentChannel, BASS_ATTRIB_VOL, (float) v / 256);
+				BASS_ChannelSetAttribute(soundCache[ch].mostRecentChannel,
+						BASS_ATTRIB_VOL, (float) v / 256);
 			}
 		}
 	}
@@ -186,7 +203,8 @@ bool stillPlayingSound(int ch) {
 	if (soundOK)
 		if (ch != -1)
 			if (soundCache[ch].fileLoaded != -1)
-				if (BASS_ChannelIsActive(soundCache[ch].mostRecentChannel) != BASS_ACTIVE_STOPPED)
+				if (BASS_ChannelIsActive(soundCache[ch].mostRecentChannel)
+						!= BASS_ACTIVE_STOPPED)
 					return true;
 	return false;
 }
@@ -212,8 +230,8 @@ int emptySoundSlot = 0;
 
 int findEmptySoundSlot() {
 	int t;
-	for (t = 0; t < MAX_SAMPLES; t ++) {
-		emptySoundSlot ++;
+	for (t = 0; t < MAX_SAMPLES; t++) {
+		emptySoundSlot++;
 		emptySoundSlot %= MAX_SAMPLES;
 		if (!soundCache[emptySoundSlot].sample)
 			return emptySoundSlot;
@@ -221,15 +239,16 @@ int findEmptySoundSlot() {
 
 	// Argh!They're all playing!Let's trash the oldest that's not looping...
 
-	for (t = 0; t < MAX_SAMPLES; t ++) {
-		emptySoundSlot ++;
+	for (t = 0; t < MAX_SAMPLES; t++) {
+		emptySoundSlot++;
 		emptySoundSlot %= MAX_SAMPLES;
-		if (!soundCache[emptySoundSlot].looping) return emptySoundSlot;
+		if (!soundCache[emptySoundSlot].looping)
+			return emptySoundSlot;
 	}
 
 	// Holy crap, they're all looping!What's this twat playing at?
 
-	emptySoundSlot ++;
+	emptySoundSlot++;
 	emptySoundSlot %= MAX_SAMPLES;
 	return emptySoundSlot;
 }
@@ -237,15 +256,15 @@ int findEmptySoundSlot() {
 int guessSoundFree = 0;
 
 /*
-void soundWarning (char * t, int i) {
-    FILE * u = fopen ("soundlog.txt", "at");
-    fprintf (u, "%s: %i\n", t, i);
-    fclose (u);
-}
-*/
+ void soundWarning (char * t, int i) {
+ FILE * u = fopen ("soundlog.txt", "at");
+ fprintf (u, "%s: %i\n", t, i);
+ fclose (u);
+ }
+ */
 
 bool forceRemoveSound() {
-	for (int a = 0; a < 8; a ++) {
+	for (int a = 0; a < 8; a++) {
 		if (soundCache[a].fileLoaded != -1 && !stillPlayingSound(a)) {
 //			soundWarning ("Deleting silent sound", a);
 			freeSound(a);
@@ -253,7 +272,7 @@ bool forceRemoveSound() {
 		}
 	}
 
-	for (int a = 0; a < 8; a ++) {
+	for (int a = 0; a < 8; a++) {
 		if (soundCache[a].fileLoaded != -1) {
 //			soundWarning ("Deleting playing sound", a);
 			freeSound(a);
@@ -267,16 +286,20 @@ bool forceRemoveSound() {
 int cacheSound(int f) {
 	setResourceForFatal(f);
 
-	if (!soundOK) return 0;
+	if (!soundOK)
+		return 0;
 
 	int a = findInSoundCache(f);
-	if (a != -1) return a;
-	if (f == -2) return -1;
+	if (a != -1)
+		return a;
+	if (f == -2)
+		return -1;
 	a = findEmptySoundSlot();
 	freeSound(a);
 
 	uint32_t length = openFileFromNum(f);
-	if (!length) return -1;
+	if (!length)
+		return -1;
 
 	char *memImage;
 
@@ -295,7 +318,8 @@ int cacheSound(int f) {
 
 	for (;;) {
 //		soundWarning ("  Trying to load sound into slot", a);
-		soundCache[a].sample = BASS_SampleLoad(true, memImage, 0, length, 65535, 0);
+		soundCache[a].sample = BASS_SampleLoad(true, memImage, 0, length, 65535,
+				0);
 
 		if (soundCache[a].sample) {
 			soundCache[a].fileLoaded = f;
@@ -315,17 +339,21 @@ int cacheSound(int f) {
 bool startSound(int f, bool loopy) {
 	if (soundOK) {
 		int a = cacheSound(f);
-		if (a == -1) return false;
+		if (a == -1)
+			return false;
 
 		soundCache[a].looping = loopy;
 		soundCache[a].vol = defSoundVol;
 
-		soundCache[a].mostRecentChannel = BASS_SampleGetChannel(soundCache[a].sample, false);
+		soundCache[a].mostRecentChannel = BASS_SampleGetChannel(
+				soundCache[a].sample, false);
 		if (soundCache[a].mostRecentChannel) {
 			BASS_ChannelPlay(soundCache[a].mostRecentChannel, true);
-			BASS_ChannelSetAttribute(soundCache[a].mostRecentChannel, BASS_ATTRIB_VOL, defSoundVol);
+			BASS_ChannelSetAttribute(soundCache[a].mostRecentChannel,
+					BASS_ATTRIB_VOL, defSoundVol);
 			if (loopy) {
-				BASS_ChannelFlags(soundCache[a].mostRecentChannel, BASS_SAMPLE_LOOP, BASS_SAMPLE_LOOP); // set LOOP flag
+				BASS_ChannelFlags(soundCache[a].mostRecentChannel,
+						BASS_SAMPLE_LOOP, BASS_SAMPLE_LOOP); // set LOOP flag
 			}
 		}
 
@@ -334,22 +362,22 @@ bool startSound(int f, bool loopy) {
 }
 
 /*
-void debugSounds () {
-    FILE * fp = fopen ("newdebug.txt", "at");
-    if (fp) {
-        for (int aa = 0; aa < 32; aa ++) {
-            if (aa == EFFECT_CHANNELS) fprintf (fp, "|");
-            fprintf (fp, FSOUND_IsPlaying (aa) ? "#" : ".");
-        }
-        fprintf (fp, "\n");
-        fclose (fp);
-    }
-}
-// */
+ void debugSounds () {
+ FILE * fp = fopen ("newdebug.txt", "at");
+ if (fp) {
+ for (int aa = 0; aa < 32; aa ++) {
+ if (aa == EFFECT_CHANNELS) fprintf (fp, "|");
+ fprintf (fp, FSOUND_IsPlaying (aa) ? "#" : ".");
+ }
+ fprintf (fp, "\n");
+ fclose (fp);
+ }
+ }
+ // */
 
 void saveSounds(Common::WriteStream *stream) {
 	if (soundOK) {
-		for (int i = 0; i < MAX_SAMPLES; i ++) {
+		for (int i = 0; i < MAX_SAMPLES; i++) {
 			if (soundCache[i].looping) {
 				putch(1, stream);
 				put2bytes(soundCache[i].fileLoaded, stream);
@@ -363,7 +391,8 @@ void saveSounds(Common::WriteStream *stream) {
 }
 
 void loadSounds(Common::SeekableReadStream *stream) {
-	for (int i = 0; i < MAX_SAMPLES; i ++) freeSound(i);
+	for (int i = 0; i < MAX_SAMPLES; i++)
+		freeSound(i);
 
 	while (getch(stream)) {
 		int fileLoaded = get2bytes(stream);
@@ -379,11 +408,13 @@ bool getSoundCacheStack(stackHandler *sH) {
 	variable newFileHandle;
 	newFileHandle.varType = SVT_NULL;
 
-	for (int a = 0; a < MAX_SAMPLES; a ++) {
+	for (int a = 0; a < MAX_SAMPLES; a++) {
 		if (soundCache[a].fileLoaded != -1) {
 			setVariable(newFileHandle, SVT_FILE, soundCache[a].fileLoaded);
-			if (!addVarToStackQuick(newFileHandle, sH -> first)) return false;
-			if (sH -> last == NULL) sH -> last = sH -> first;
+			if (!addVarToStackQuick(newFileHandle, sH->first))
+				return false;
+			if (sH->last == NULL)
+				sH->last = sH->first;
 		}
 	}
 	return true;
diff --git a/engines/sludge/sound_openal.cpp b/engines/sludge/sound_openal.cpp
index 5faefdb..72824d3 100644
--- a/engines/sludge/sound_openal.cpp
+++ b/engines/sludge/sound_openal.cpp
@@ -97,7 +97,8 @@ bool initSoundStuff(HWND hwnd) {
 }
 
 void killSoundStuff() {
-	if (! soundOK) return;
+	if (!soundOK)
+		return;
 #if 0
 	SilenceIKillYou = true;
 	for (int i = 0; i < MAX_SAMPLES; i ++) {
@@ -105,7 +106,7 @@ void killSoundStuff() {
 
 			if (! alureStopSource(soundCache[i].playingOnSource, AL_TRUE)) {
 				debugOut("Failed to stop source: %s\n",
-				         alureGetErrorString());
+						alureGetErrorString());
 			}
 
 		}
@@ -114,7 +115,7 @@ void killSoundStuff() {
 
 			if (! alureDestroyStream(soundCache[i].stream, 0, NULL)) {
 				debugOut("Failed to destroy stream: %s\n",
-				         alureGetErrorString());
+						alureGetErrorString());
 			}
 
 		}
@@ -125,7 +126,7 @@ void killSoundStuff() {
 
 			if (! alureStopSource(modCache[i].playingOnSource, AL_TRUE)) {
 				debugOut("Failed to stop source: %s\n",
-				         alureGetErrorString());
+						alureGetErrorString());
 			}
 
 		}
@@ -134,7 +135,7 @@ void killSoundStuff() {
 
 			if (! alureDestroyStream(modCache[i].stream, 0, NULL)) {
 				debugOut("Failed to destroy stream: %s\n",
-				         alureGetErrorString());
+						alureGetErrorString());
 			}
 
 		}
@@ -151,7 +152,8 @@ void killSoundStuff() {
  */
 
 void setMusicVolume(int a, int v) {
-	if (! soundOK) return;
+	if (!soundOK)
+		return;
 
 	if (modCache[a].playing) {
 #if 0
@@ -165,7 +167,8 @@ void setDefaultMusicVolume(int v) {
 }
 
 void setSoundVolume(int a, int v) {
-	if (! soundOK) return;
+	if (!soundOK)
+		return;
 	int ch = findInSoundCache(a);
 	if (ch != -1) {
 		if (soundCache[ch].playing) {
@@ -218,7 +221,7 @@ static void mod_eos_callback(void *cacheIndex, ALuint source) {
 
 	if (! alureDestroyStream(modCache[*a].stream, 0, NULL)) {
 		debugOut("Failed to destroy stream: %s\n",
-		         alureGetErrorString());
+				alureGetErrorString());
 	}
 
 	modCache[*a].stream = NULL;
@@ -232,7 +235,7 @@ static void mod_eos_callback(void *cacheIndex, ALuint source) {
 
 int findInSoundCache(int a) {
 	int i;
-	for (i = 0; i < MAX_SAMPLES; i ++) {
+	for (i = 0; i < MAX_SAMPLES; i++) {
 		if (soundCache[i].fileLoaded == a) {
 			return i;
 		}
@@ -241,7 +244,8 @@ int findInSoundCache(int a) {
 }
 
 void stopMOD(int i) {
-	if (! soundOK) return;
+	if (!soundOK)
+		return;
 #if 0
 	alGetError();
 	if (modCache[i].playing) {
@@ -253,7 +257,8 @@ void stopMOD(int i) {
 }
 
 void huntKillSound(int filenum) {
-	if (! soundOK) return;
+	if (!soundOK)
+		return;
 #if 0
 	// Clear OpenAL errors to make sure they don't block anything:
 	alGetError();
@@ -273,7 +278,8 @@ void huntKillSound(int filenum) {
 }
 
 void freeSound(int a) {
-	if (! soundOK) return;
+	if (!soundOK)
+		return;
 #if 0
 	// Clear OpenAL errors to make sure they don't block anything:
 	alGetError();
@@ -283,12 +289,12 @@ void freeSound(int a) {
 	if (soundCache[a].playing) {
 		if (! alureStopSource(soundCache[a].playingOnSource, AL_TRUE)) {
 			debugOut("Failed to stop source: %s\n",
-			         alureGetErrorString());
+					alureGetErrorString());
 		}
 	}
 	if (! alureDestroyStream(soundCache[a].stream, 0, NULL)) {
 		debugOut("Failed to destroy stream: %s\n",
-		         alureGetErrorString());
+				alureGetErrorString());
 	}
 
 	soundCache[a].stream = NULL;
@@ -297,11 +303,12 @@ void freeSound(int a) {
 	SilenceIKillYou = false;
 }
 
-
 void huntKillFreeSound(int filenum) {
-	if (! soundOK) return;
+	if (!soundOK)
+		return;
 	int gotSlot = findInSoundCache(filenum);
-	if (gotSlot == -1) return;
+	if (gotSlot == -1)
+		return;
 	freeSound(gotSlot);
 }
 
@@ -339,10 +346,10 @@ void playStream(int a, bool isMOD, bool loopy) {
 
 	if (loopy) {
 		ok = alurePlaySourceStream(src, (*st).stream,
-		                           NUM_BUFS, -1, eos_callback, &intpointers[a]);
+				NUM_BUFS, -1, eos_callback, &intpointers[a]);
 	} else {
 		ok = alurePlaySourceStream(src, (*st).stream,
-		                           NUM_BUFS, 0, eos_callback, &intpointers[a]);
+				NUM_BUFS, 0, eos_callback, &intpointers[a]);
 	}
 
 	if (!ok) {
@@ -361,9 +368,11 @@ void playStream(int a, bool isMOD, bool loopy) {
 #endif
 }
 
-char *loadEntireFileToMemory(Common::SeekableReadStream *inputFile, uint32_t size) {
+char *loadEntireFileToMemory(Common::SeekableReadStream *inputFile,
+		uint32_t size) {
 	char *allData = new char[size];
-	if (! allData) return NULL;
+	if (!allData)
+		return NULL;
 
 	size_t bytes_read = inputFile->read(allData, size);
 	if (bytes_read != size && inputFile->err()) {
@@ -376,7 +385,8 @@ char *loadEntireFileToMemory(Common::SeekableReadStream *inputFile, uint32_t siz
 }
 
 bool playMOD(int f, int a, int fromTrack) {
-	if (! soundOK) return true;
+	if (!soundOK)
+		return true;
 	stopMOD(a);
 
 	setResourceForFatal(f);
@@ -400,7 +410,7 @@ bool playMOD(int f, int a, int fromTrack) {
 
 		if (! alureSetStreamOrder(modCache[a].stream, fromTrack)) {
 			debugOut("Failed to set stream order: %s\n",
-			         alureGetErrorString());
+					alureGetErrorString());
 		}
 
 		playStream(a, true, true);
@@ -408,7 +418,7 @@ bool playMOD(int f, int a, int fromTrack) {
 	} else {
 
 		debugOut("Failed to create stream from MOD: %s\n",
-		         alureGetErrorString());
+				alureGetErrorString());
 
 		warning(ERROR_MUSIC_ODDNESS);
 		soundCache[a].stream = NULL;
@@ -431,15 +441,15 @@ bool stillPlayingSound(int ch) {
 }
 
 bool forceRemoveSound() {
-	for (int a = 0; a < MAX_SAMPLES; a ++) {
-		if (soundCache[a].fileLoaded != -1 && ! stillPlayingSound(a)) {
+	for (int a = 0; a < MAX_SAMPLES; a++) {
+		if (soundCache[a].fileLoaded != -1 && !stillPlayingSound(a)) {
 //			soundWarning ("Deleting silent sound", a);
 			freeSound(a);
 			return 1;
 		}
 	}
 
-	for (int a = 0; a < MAX_SAMPLES; a ++) {
+	for (int a = 0; a < MAX_SAMPLES; a++) {
 		if (soundCache[a].fileLoaded != -1) {
 //			soundWarning ("Deleting playing sound", a);
 			freeSound(a);
@@ -454,17 +464,17 @@ int emptySoundSlot = 0;
 
 int findEmptySoundSlot() {
 	int t;
-	for (t = 0; t < MAX_SAMPLES; t ++) {
-		emptySoundSlot ++;
+	for (t = 0; t < MAX_SAMPLES; t++) {
+		emptySoundSlot++;
 		emptySoundSlot %= MAX_SAMPLES;
 #if 0
 		if (soundCache[emptySoundSlot].stream == NULL)
-			return emptySoundSlot;
+		return emptySoundSlot;
 #endif
 	}
 
-	for (t = 0; t < MAX_SAMPLES; t ++) {
-		emptySoundSlot ++;
+	for (t = 0; t < MAX_SAMPLES; t++) {
+		emptySoundSlot++;
 		emptySoundSlot %= MAX_SAMPLES;
 		if (!soundCache[emptySoundSlot].playing)
 			return emptySoundSlot;
@@ -472,22 +482,24 @@ int findEmptySoundSlot() {
 
 	// Argh! They're all playing! Let's trash the oldest that's not looping...
 
-	for (t = 0; t < MAX_SAMPLES; t ++) {
-		emptySoundSlot ++;
+	for (t = 0; t < MAX_SAMPLES; t++) {
+		emptySoundSlot++;
 		emptySoundSlot %= MAX_SAMPLES;
-		if (! soundCache[emptySoundSlot].looping) return emptySoundSlot;
+		if (!soundCache[emptySoundSlot].looping)
+			return emptySoundSlot;
 	}
 
 	// Holy crap, they're all looping! What's this twat playing at?
 
-	emptySoundSlot ++;
+	emptySoundSlot++;
 	emptySoundSlot %= MAX_SAMPLES;
 	return emptySoundSlot;
 }
 
 int cacheSound(int f) {
 
-	if (! soundOK) return -1;
+	if (!soundOK)
+		return -1;
 
 	unsigned int chunkLength;
 	int retval;
@@ -506,12 +518,12 @@ int cacheSound(int f) {
 		if (soundCache[a].playing) {
 			if (! alureStopSource(soundCache[a].playingOnSource, AL_TRUE)) {
 				debugOut("Failed to stop source: %s\n",
-				         alureGetErrorString());
+						alureGetErrorString());
 			}
 		}
 		if (! alureRewindStream(soundCache[a].stream)) {
 			debugOut("Failed to rewind stream: %s\n",
-			         alureGetErrorString());
+					alureGetErrorString());
 		}
 
 		return a;
@@ -560,7 +572,7 @@ int cacheSound(int f) {
 	} else {
 
 		debugOut("Failed to create stream from sound: %s\n",
-		         alureGetErrorString());
+				alureGetErrorString());
 
 		warning(ERROR_SOUND_ODDNESS);
 		soundCache[a].stream = NULL;
@@ -592,7 +604,7 @@ bool startSound(int f, bool loopy) {
 
 void saveSounds(Common::WriteStream *stream) {
 	if (soundOK) {
-		for (int i = 0; i < MAX_SAMPLES; i ++) {
+		for (int i = 0; i < MAX_SAMPLES; i++) {
 			if (soundCache[i].looping) {
 				putch(1, stream);
 				put2bytes(soundCache[i].fileLoaded, stream);
@@ -606,7 +618,8 @@ void saveSounds(Common::WriteStream *stream) {
 }
 
 void loadSounds(Common::SeekableReadStream *stream) {
-	for (int i = 0; i < MAX_SAMPLES; i ++) freeSound(i);
+	for (int i = 0; i < MAX_SAMPLES; i++)
+		freeSound(i);
 
 	while (getch(stream)) {
 		int fileLoaded = get2bytes(stream);
@@ -622,11 +635,13 @@ bool getSoundCacheStack(stackHandler *sH) {
 	variable newFileHandle;
 	newFileHandle.varType = SVT_NULL;
 
-	for (int a = 0; a < MAX_SAMPLES; a ++) {
+	for (int a = 0; a < MAX_SAMPLES; a++) {
 		if (soundCache[a].fileLoaded != -1) {
 			setVariable(newFileHandle, SVT_FILE, soundCache[a].fileLoaded);
-			if (! addVarToStackQuick(newFileHandle, sH -> first)) return false;
-			if (sH -> last == NULL) sH -> last = sH -> first;
+			if (!addVarToStackQuick(newFileHandle, sH->first))
+				return false;
+			if (sH->last == NULL)
+				sH->last = sH->first;
 		}
 	}
 	return true;
@@ -634,19 +649,22 @@ bool getSoundCacheStack(stackHandler *sH) {
 
 soundList *deleteSoundFromList(soundList *s) {
 	// Don't delete a playing sound.
-	if (s->cacheIndex) return NULL;
+	if (s->cacheIndex)
+		return NULL;
 
 	soundList *o = NULL;
-	if (! s->next) {
+	if (!s->next) {
 		o = s->prev;
-		if (o) o-> next = NULL;
+		if (o)
+			o->next = NULL;
 		delete s;
 		return o;
 	}
 	if (s != s->next) {
 		o = s->next;
 		o->prev = s->prev;
-		if (o->prev) o->prev->next = o;
+		if (o->prev)
+			o->prev->next = o;
 	}
 	delete s;
 	return o;
@@ -699,9 +717,9 @@ void playSoundList(soundList *s) {
 		}
 		soundCache[a].looping = false;
 		if (s->vol < 0)
-			soundCache[a].vol = defSoundVol;
+		soundCache[a].vol = defSoundVol;
 		else
-			soundCache[a].vol = s->vol;
+		soundCache[a].vol = s->vol;
 		s-> cacheIndex = a;
 
 		ALboolean ok;
@@ -719,7 +737,7 @@ void playSoundList(soundList *s) {
 		alSourcef(src, AL_GAIN, (float) soundCache[a].vol / 256);
 
 		ok = alurePlaySourceStream(src, (*st).stream,
-		                           NUM_BUFS, 0, list_eos_callback, s);
+				NUM_BUFS, 0, list_eos_callback, s);
 
 		if (!ok) {
 
@@ -753,7 +771,7 @@ void playMovieStream(int a) {
 	alSourcef(src, AL_GAIN, (float) soundCache[a].vol / 256);
 
 	ok = alurePlaySourceStream(src, soundCache[a].stream,
-	                           10, 0, sound_eos_callback, &intpointers[a]);
+			10, 0, sound_eos_callback, &intpointers[a]);
 	if (!ok) {
 		debugOut("Failed to play stream: %s\n", alureGetErrorString());
 		alDeleteSources(1, &src);
@@ -771,7 +789,7 @@ void playMovieStream(int a) {
 
 #if 0
 int initMovieSound(int f, ALenum format, int audioChannels, ALuint samplerate,
-                   ALuint(*callback)(void *userdata, ALubyte *data, ALuint bytes)) {
+		ALuint(*callback)(void *userdata, ALubyte *data, ALuint bytes)) {
 	if (! soundOK) return 0;
 
 	int retval;
@@ -782,9 +800,9 @@ int initMovieSound(int f, ALenum format, int audioChannels, ALuint samplerate,
 #if 0
 	// audioChannel * sampleRate gives us a buffer of half a second. Not much, but it should be enough.
 	soundCache[a].stream = alureCreateStreamFromCallback(
-	                           callback,
-	                           &intpointers[a], format, samplerate,
-	                           audioChannels * samplerate, 0, NULL);
+			callback,
+			&intpointers[a], format, samplerate,
+			audioChannels * samplerate, 0, NULL);
 #endif
 	if (soundCache[a].stream != NULL) {
 		soundCache[a].fileLoaded = f;
@@ -793,7 +811,7 @@ int initMovieSound(int f, ALenum format, int audioChannels, ALuint samplerate,
 	} else {
 #if 0
 		debugOut("Failed to create stream from sound: %s\n",
-		         alureGetErrorString());
+				alureGetErrorString());
 #endif
 		warning(ERROR_SOUND_ODDNESS);
 		soundCache[a].stream = NULL;
diff --git a/engines/sludge/sprbanks.cpp b/engines/sludge/sprbanks.cpp
index c95e405..8598cb5 100644
--- a/engines/sludge/sprbanks.cpp
+++ b/engines/sludge/sprbanks.cpp
@@ -31,42 +31,43 @@ loadedSpriteBank *allLoadedBanks = NULL;
 extern spriteBank theFont;
 extern int loadedFontNum, fontTableSize;
 
-
 loadedSpriteBank *loadBankForAnim(int ID) {
 	//debugOut ("loadBankForAnim: Looking for sprite bank with ID %d\n", ID);
 	loadedSpriteBank *returnMe = allLoadedBanks;
 	while (returnMe) {
-		if (returnMe -> ID == ID) {
+		if (returnMe->ID == ID) {
 			//debugOut ("loadBankForAnim: Found existing sprite bank with ID %d\n", returnMe -> ID);
 			return returnMe;
 		}
-		returnMe = returnMe -> next;
+		returnMe = returnMe->next;
 	}
 	returnMe = new loadedSpriteBank;
 	//debugOut ("loadBankForAnim: No existing sprite bank with ID %d\n", ID);
 	if (checkNew(returnMe)) {
-		returnMe -> ID = ID;
-		if (loadSpriteBank(ID, returnMe -> bank, false)) {
-			returnMe -> timesUsed = 0;
-			returnMe -> next = allLoadedBanks;
+		returnMe->ID = ID;
+		if (loadSpriteBank(ID, returnMe->bank, false)) {
+			returnMe->timesUsed = 0;
+			returnMe->next = allLoadedBanks;
 			allLoadedBanks = returnMe;
 			debugOut("loadBankForAnim: New sprite bank created OK\n");
 			return returnMe;
 		} else {
-			debugOut("loadBankForAnim: I guess I couldn't load the sprites...\n");
+			debugOut(
+					"loadBankForAnim: I guess I couldn't load the sprites...\n");
 			return NULL;
 		}
-	} else return NULL;
+	} else
+		return NULL;
 }
 
 void reloadSpriteTextures() {
 	loadedSpriteBank *spriteBank = allLoadedBanks;
 	while (spriteBank) {
 		//fprintf (stderr, "Reloading bank %d: %s.\n", spriteBank->ID, resourceNameFromNum (spriteBank->ID));
-		delete spriteBank-> bank.sprites;
-		spriteBank-> bank.sprites = NULL;
+		delete spriteBank->bank.sprites;
+		spriteBank->bank.sprites = NULL;
 		loadSpriteBank(spriteBank->ID, spriteBank->bank, false);
-		spriteBank = spriteBank -> next;
+		spriteBank = spriteBank->next;
 	}
 	if (fontTableSize) {
 		delete theFont.sprites;
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index ec4144f..5b372e6 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -57,7 +57,6 @@ extern float cameraZoom;
 
 unsigned char currentBurnR = 0, currentBurnG = 0, currentBurnB = 0;
 
-
 void forgetSpriteBank(spriteBank &forgetme) {
 #if 0
 	deleteTextures(forgetme.myPalette.numTextures, forgetme.myPalette.tex_names);
@@ -70,49 +69,53 @@ void forgetSpriteBank(spriteBank &forgetme) {
 	delete [] forgetme.myPalette.tex_names;
 	forgetme.myPalette.tex_names = NULL;
 #endif
-	delete [] forgetme.myPalette.tex_w;
+	delete[] forgetme.myPalette.tex_w;
 	forgetme.myPalette.tex_w = NULL;
-	delete [] forgetme.myPalette.tex_h;
+	delete[] forgetme.myPalette.tex_h;
 	forgetme.myPalette.tex_h = NULL;
 
 	if (forgetme.myPalette.pal) {
-		delete  [] forgetme.myPalette.pal;
+		delete[] forgetme.myPalette.pal;
 		forgetme.myPalette.pal = NULL;
-		delete  [] forgetme.myPalette.r;
+		delete[] forgetme.myPalette.r;
 		forgetme.myPalette.r = NULL;
-		delete  [] forgetme.myPalette.g;
+		delete[] forgetme.myPalette.g;
 		forgetme.myPalette.g = NULL;
-		delete  [] forgetme.myPalette.b;
+		delete[] forgetme.myPalette.b;
 		forgetme.myPalette.b = NULL;
 	}
 
 	delete forgetme.sprites;
 	forgetme.sprites = NULL;
 
-
 	// TODO: also remove sprite bank from allLoadedBanks
 	// And add a function call for this function to the scripting language
 }
 
 bool reserveSpritePal(spritePalette &sP, int n) {
 	if (sP.pal) {
-		delete  [] sP.pal;
-		delete  [] sP.r;
-		delete  [] sP.g;
-		delete  [] sP.b;
+		delete[] sP.pal;
+		delete[] sP.r;
+		delete[] sP.g;
+		delete[] sP.b;
 	}
 
-	sP.pal = new unsigned short int [n];
-	if (! checkNew(sP.pal)) return false;
-
-	sP.r = new unsigned char [n];
-	if (! checkNew(sP.r)) return false;
-	sP.g = new unsigned char [n];
-	if (! checkNew(sP.g)) return false;
-	sP.b = new unsigned char [n];
-	if (! checkNew(sP.b)) return false;
+	sP.pal = new unsigned short int[n];
+	if (!checkNew(sP.pal))
+		return false;
+
+	sP.r = new unsigned char[n];
+	if (!checkNew(sP.r))
+		return false;
+	sP.g = new unsigned char[n];
+	if (!checkNew(sP.g))
+		return false;
+	sP.b = new unsigned char[n];
+	if (!checkNew(sP.b))
+		return false;
 	sP.total = n;
-	return (bool)(sP.pal != NULL) && (sP.r != NULL) && (sP.g != NULL) && (sP.b != NULL);
+	return (bool) (sP.pal != NULL) && (sP.r != NULL) && (sP.g != NULL)
+			&& (sP.b != NULL);
 }
 
 bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
@@ -173,60 +176,60 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 
 	for (i = 0; i < total; i ++) {
 		switch (spriteBankVersion) {
-		case 3: {
-			loadhere.sprites[i].xhot = getSigned(bigDataFile);
-			loadhere.sprites[i].yhot = getSigned(bigDataFile);
+			case 3: {
+				loadhere.sprites[i].xhot = getSigned(bigDataFile);
+				loadhere.sprites[i].yhot = getSigned(bigDataFile);
 
-			png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
-			if (!png_ptr) {
-				return fatal("Can't open sprite bank / font.");
-			}
+				png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+				if (!png_ptr) {
+					return fatal("Can't open sprite bank / font.");
+				}
 
-			png_infop info_ptr = png_create_info_struct(png_ptr);
-			if (!info_ptr) {
-				png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
-				return fatal("Can't open sprite bank / font.");
-			}
+				png_infop info_ptr = png_create_info_struct(png_ptr);
+				if (!info_ptr) {
+					png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
+					return fatal("Can't open sprite bank / font.");
+				}
 
-			png_infop end_info = png_create_info_struct(png_ptr);
-			if (!end_info) {
-				png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
-				return fatal("Can't open sprite bank / font.");
-			}
-			png_init_io(png_ptr, bigDataFile);      // Tell libpng which file to read
-			png_set_sig_bytes(png_ptr, 8);          // No sig
+				png_infop end_info = png_create_info_struct(png_ptr);
+				if (!end_info) {
+					png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
+					return fatal("Can't open sprite bank / font.");
+				}
+				png_init_io(png_ptr, bigDataFile); // Tell libpng which file to read
+				png_set_sig_bytes(png_ptr, 8);// No sig
 
-			png_read_info(png_ptr, info_ptr);
+				png_read_info(png_ptr, info_ptr);
 
-			png_uint_32 width, height;
-			int bit_depth, color_type, interlace_type, compression_type, filter_method;
-			png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
+				png_uint_32 width, height;
+				int bit_depth, color_type, interlace_type, compression_type, filter_method;
+				png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
 
-			int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
+				int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
 
-			unsigned char *row_pointers[height];
-			spriteData[i] = new unsigned char [rowbytes * height];
-			if (! checkNew(spriteData[i])) return false;
+				unsigned char *row_pointers[height];
+				spriteData[i] = new unsigned char [rowbytes * height];
+				if (! checkNew(spriteData[i])) return false;
 
-			for (unsigned int row = 0; row < height; row++)
+				for (unsigned int row = 0; row < height; row++)
 				row_pointers[row] = spriteData[i] + row * rowbytes;
 
-			png_read_image(png_ptr, (png_byte **) row_pointers);
-			png_read_end(png_ptr, NULL);
-			png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
+				png_read_image(png_ptr, (png_byte **) row_pointers);
+				png_read_end(png_ptr, NULL);
+				png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
 
-			picwidth = loadhere.sprites[i].width = width;
-			picheight = loadhere.sprites[i].height = height;
-			break;
-		}
-		case 2:
+				picwidth = loadhere.sprites[i].width = width;
+				picheight = loadhere.sprites[i].height = height;
+				break;
+			}
+			case 2:
 			picwidth = get2bytes(bigDataFile);
 			picheight = get2bytes(bigDataFile);
 			loadhere.sprites[i].xhot = getSigned(bigDataFile);
 			loadhere.sprites[i].yhot = getSigned(bigDataFile);
 			break;
 
-		default:
+			default:
 			picwidth = (byte) fgetc(bigDataFile);
 			picheight = (byte) fgetc(bigDataFile);
 			loadhere.sprites[i].xhot = fgetc(bigDataFile);
@@ -256,27 +259,27 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 			}
 			spriteData[i] = data;
 			switch (spriteBankVersion) {
-			case 2: {       // RUN LENGTH COMPRESSED DATA
-				unsigned size = picwidth * picheight;
-				unsigned pip = 0;
-
-				while (pip < size) {
-					byte col = fgetc(bigDataFile);
-					int looper;
-
-					if (col > howmany) {
-						col -= howmany + 1;
-						looper = fgetc(bigDataFile) + 1;
-					} else looper = 1;
-
-					while (looper --) {
-						data[pip ++] = col;
+				case 2: {       // RUN LENGTH COMPRESSED DATA
+					unsigned size = picwidth * picheight;
+					unsigned pip = 0;
+
+					while (pip < size) {
+						byte col = fgetc(bigDataFile);
+						int looper;
+
+						if (col > howmany) {
+							col -= howmany + 1;
+							looper = fgetc(bigDataFile) + 1;
+						} else looper = 1;
+
+						while (looper --) {
+							data[pip ++] = col;
+						}
 					}
 				}
-			}
-			break;
+				break;
 
-			default:        // RAW DATA
+				default:        // RAW DATA
 				size_t bytes_read = fread(data, picwidth, picheight, bigDataFile);
 				if (bytes_read != picwidth * picheight && ferror(bigDataFile)) {
 					debugOut("Reading error in loadSpriteBank.\n");
@@ -287,7 +290,6 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 	}
 	numTextures++;
 
-
 	if (! spriteBankVersion) {
 		howmany = fgetc(bigDataFile);
 		startIndex = fgetc(bigDataFile);
@@ -368,9 +370,9 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 						target[1] = (GLubyte) 255;
 						target[2] = (GLubyte) 255;
 						if (s)
-							target[3] = (GLubyte) loadhere.myPalette.r[s];
+						target[3] = (GLubyte) loadhere.myPalette.r[s];
 						/*else
-						    target[3] = (GLubyte) 0;*/
+						 target[3] = (GLubyte) 0;*/
 					}
 				} else {
 					target[0] = (GLubyte) spriteData[i][fromhere++];
@@ -390,7 +392,7 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 
 	glGenTextures(numTextures, loadhere.myPalette.tex_names);
 	if (isFont)
-		glGenTextures(numTextures, loadhere.myPalette.burnTex_names);
+	glGenTextures(numTextures, loadhere.myPalette.burnTex_names);
 
 #endif
 
@@ -436,7 +438,8 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 	return true;
 }
 
-void pasteSpriteToBackDrop(int x1, int y1, sprite &single, const spritePalette &fontPal) {
+void pasteSpriteToBackDrop(int x1, int y1, sprite &single,
+		const spritePalette &fontPal) {
 #if 0
 	float tx1 = (float)(single.tex_x) / fontPal.tex_w[single.texNum];
 	float ty1 = 0.0;
@@ -490,7 +493,6 @@ void pasteSpriteToBackDrop(int x1, int y1, sprite &single, const spritePalette &
 		while (yoffset < diffY) {
 			int h = (diffY - yoffset < viewportHeight) ? diffY - yoffset : viewportHeight;
 
-
 			// Render the sprite to the backdrop
 			// (using mulitexturing, so the backdrop is seen where alpha < 1.0)
 			glActiveTexture(GL_TEXTURE2);
@@ -499,7 +501,7 @@ void pasteSpriteToBackDrop(int x1, int y1, sprite &single, const spritePalette &
 
 			glUseProgram(shader.paste);
 			GLint uniform = glGetUniformLocation(shader.paste, "useLightTexture");
-			if (uniform >= 0) glUniform1i(uniform, 0); // No lighting
+			if (uniform >= 0) glUniform1i(uniform, 0);// No lighting
 
 			setPMVMatrix(shader.paste);
 
@@ -536,7 +538,8 @@ void pasteSpriteToBackDrop(int x1, int y1, sprite &single, const spritePalette &
 	setPixelCoords(false);
 }
 
-void burnSpriteToBackDrop(int x1, int y1, sprite &single, const spritePalette &fontPal) {
+void burnSpriteToBackDrop(int x1, int y1, sprite &single,
+		const spritePalette &fontPal) {
 #if 0
 	float tx1 = (float)(single.tex_x - 0.5) / fontPal.tex_w[single.texNum];
 	float ty1 = 0.0;
@@ -626,7 +629,7 @@ void burnSpriteToBackDrop(int x1, int y1, sprite &single, const spritePalette &f
 			glBindTexture(GL_TEXTURE_2D, fontPal.burnTex_names[single.texNum]);
 
 //FIXME: Test this some more. Also pasting the backdrop again is not strictly necessary but allows using the paste shader.
-			drawQuad(shader.paste, spriteVertices, 3, spriteTexCoords, NULL,  backdropTexCoords);
+			drawQuad(shader.paste, spriteVertices, 3, spriteTexCoords, NULL, backdropTexCoords);
 			glUseProgram(0);
 
 			// Copy Our ViewPort To The Texture
@@ -644,17 +647,19 @@ void burnSpriteToBackDrop(int x1, int y1, sprite &single, const spritePalette &f
 extern GLuint backdropTextureName;
 #endif
 
-void fontSprite(bool flip, int x, int y, sprite &single, const spritePalette &fontPal) {
+void fontSprite(bool flip, int x, int y, sprite &single,
+		const spritePalette &fontPal) {
 
-	float tx1 = (float)(single.tex_x - 0.5) / fontPal.tex_w[single.texNum];
+	float tx1 = (float) (single.tex_x - 0.5) / fontPal.tex_w[single.texNum];
 	float ty1 = 0.0;
-	float tx2 = (float)(single.tex_x + single.width + (flip ? 1.0 : 0.5)) / fontPal.tex_w[single.texNum];
-	float ty2 = (float)(single.height + 2) / fontPal.tex_h[single.texNum];
+	float tx2 = (float) (single.tex_x + single.width + (flip ? 1.0 : 0.5))
+			/ fontPal.tex_w[single.texNum];
+	float ty2 = (float) (single.height + 2) / fontPal.tex_h[single.texNum];
 
-	float x1 = (float)x - (float)single.xhot / cameraZoom;
-	float y1 = (float)y - (float)single.yhot / cameraZoom;
-	float x2 = x1 + (float)single.width / cameraZoom;
-	float y2 = y1 + (float)single.height / cameraZoom;
+	float x1 = (float) x - (float) single.xhot / cameraZoom;
+	float y1 = (float) y - (float) single.yhot / cameraZoom;
+	float x2 = x1 + (float) single.width / cameraZoom;
+	float y2 = y1 + (float) single.height / cameraZoom;
 
 #if 0
 	GLfloat vertices[] = {
@@ -707,13 +712,11 @@ void fontSprite(int x, int y, sprite &single, const spritePalette &fontPal) {
 	fontSprite(false, x, y, single, fontPal);
 }
 
-void flipFontSprite(int x, int y, sprite &single, const spritePalette &fontPal) {
+void flipFontSprite(int x, int y, sprite &single,
+		const spritePalette &fontPal) {
 	fontSprite(true, x, y, single, fontPal);
 }
 
-
-
-
 unsigned char curLight[3];
 
 void setDrawMode(onScreenPerson *thisPerson) {
@@ -734,7 +737,8 @@ extern GLuint backdropTextureName;
 
 bool checkColourChange(bool reset);
 
-bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *thisPerson, bool mirror) {
+bool scaleSprite(sprite &single, const spritePalette &fontPal,
+		onScreenPerson *thisPerson, bool mirror) {
 #if 0
 	float x = thisPerson->x;
 	float y = thisPerson->y;
@@ -758,9 +762,9 @@ bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *t
 		x = x / cameraZoom;
 		y = y / cameraZoom;
 		if (single.xhot < 0)
-			x1 = x - (int)((mirror ? (float)(single.width - single.xhot) : (float)(single.xhot + 1)) * scale / cameraZoom);
+		x1 = x - (int)((mirror ? (float)(single.width - single.xhot) : (float)(single.xhot + 1)) * scale / cameraZoom);
 		else
-			x1 = x - (int)((mirror ? (float)(single.width - (single.xhot + 1)) : (float)single.xhot) * scale / cameraZoom);
+		x1 = x - (int)((mirror ? (float)(single.width - (single.xhot + 1)) : (float)single.xhot) * scale / cameraZoom);
 		y1 = y - (int)((single.yhot - thisPerson->floaty) * scale / cameraZoom);
 		x2 = x1 + (int)(diffX / cameraZoom);
 		y2 = y1 + (int)(diffY / cameraZoom);
@@ -768,9 +772,9 @@ bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *t
 		x -= cameraX;
 		y -= cameraY;
 		if (single.xhot < 0)
-			x1 = x - (int)((mirror ? (float)(single.width - single.xhot) : (float)(single.xhot + 1)) * scale);
+		x1 = x - (int)((mirror ? (float)(single.width - single.xhot) : (float)(single.xhot + 1)) * scale);
 		else
-			x1 = x - (int)((mirror ? (float)(single.width - (single.xhot + 1)) : (float)single.xhot) * scale);
+		x1 = x - (int)((mirror ? (float)(single.width - (single.xhot + 1)) : (float)single.xhot) * scale);
 		y1 = y - (int)((single.yhot - thisPerson->floaty) * scale);
 		x2 = x1 + diffX;
 		y2 = y1 + diffY;
@@ -843,7 +847,7 @@ bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *t
 	}
 #ifndef HAVE_GLES2
 	if (!(thisPerson->extra & EXTRA_RECTANGULAR))
-		checkColourChange(true);
+	checkColourChange(true);
 #endif
 	setDrawMode(thisPerson);
 
@@ -909,7 +913,8 @@ bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *t
 }
 
 // Paste a scaled sprite onto the backdrop
-void fixScaleSprite(int x, int y, sprite &single, const spritePalette &fontPal, onScreenPerson *thisPerson, int camX, int camY, bool mirror) {
+void fixScaleSprite(int x, int y, sprite &single, const spritePalette &fontPal,
+		onScreenPerson *thisPerson, int camX, int camY, bool mirror) {
 #if 0
 	float scale = thisPerson-> scale;
 	bool useZB = !(thisPerson->extra & EXTRA_NOZB);
@@ -926,9 +931,9 @@ void fixScaleSprite(int x, int y, sprite &single, const spritePalette &fontPal,
 	int diffY = (int)(((float)single.height) * scale);
 	int x1;
 	if (single.xhot < 0)
-		x1 = x - (int)((mirror ? (float)(single.width - single.xhot) : (float)(single.xhot + 1)) * scale);
+	x1 = x - (int)((mirror ? (float)(single.width - single.xhot) : (float)(single.xhot + 1)) * scale);
 	else
-		x1 = x - (int)((mirror ? (float)(single.width - (single.xhot + 1)) : (float)single.xhot) * scale);
+	x1 = x - (int)((mirror ? (float)(single.width - (single.xhot + 1)) : (float)single.xhot) * scale);
 	int y1 = y - (int)((single.yhot - thisPerson->floaty) * scale);
 
 	float spriteWidth = diffX;
@@ -942,7 +947,6 @@ void fixScaleSprite(int x, int y, sprite &single, const spritePalette &fontPal,
 
 	GLfloat z;
 
-
 	if (useZB && zBuffer.numPanels) {
 		int i;
 		for (i = 1; i < zBuffer.numPanels; i++) {
diff --git a/engines/sludge/sprites.h b/engines/sludge/sprites.h
index 2a617bb..067c84a 100644
--- a/engines/sludge/sprites.h
+++ b/engines/sludge/sprites.h
@@ -51,23 +51,24 @@ public:
 	GLuint *tex_names;
 	GLuint *burnTex_names;
 #endif
-	int *tex_w, * tex_h;
+	int *tex_w, *tex_h;
 	int numTextures;
 	unsigned char originalRed, originalGreen, originalBlue, total;
 
-	spritePalette(): pal(0), r(0), g(0), b(0)/*, tex_names(0), burnTex_names(0)*/
-		, tex_w(0), tex_h(0), numTextures(0)
-		, total(0) {}
+	spritePalette() :
+			pal(0), r(0), g(0), b(0)/*, tex_names(0), burnTex_names(0)*/
+			, tex_w(0), tex_h(0), numTextures(0), total(0) {
+	}
 
 	~spritePalette() {
-		delete [] pal;
-		delete [] r;
-		delete [] g;
-		delete [] b;
+		delete[] pal;
+		delete[] r;
+		delete[] g;
+		delete[] b;
 //		delete [] tex_names;
 //		delete [] burnTex_names;
-		delete [] tex_w;
-		delete [] tex_h;
+		delete[] tex_w;
+		delete[] tex_h;
 	}
 };
 
@@ -84,13 +85,19 @@ bool loadSpriteBank(char *filename, spriteBank &loadhere);
 bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont);
 
 void fontSprite(int x1, int y1, sprite &single, const spritePalette &fontPal);
-void flipFontSprite(int x1, int y1, sprite &single, const spritePalette &fontPal);
+void flipFontSprite(int x1, int y1, sprite &single,
+		const spritePalette &fontPal);
 
-bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *thisPerson, bool mirror);
-void pasteSpriteToBackDrop(int x1, int y1, sprite &single, const spritePalette &fontPal);
+bool scaleSprite(sprite &single, const spritePalette &fontPal,
+		onScreenPerson *thisPerson, bool mirror);
+void pasteSpriteToBackDrop(int x1, int y1, sprite &single,
+		const spritePalette &fontPal);
 bool reserveSpritePal(spritePalette &sP, int n);
-void fixScaleSprite(int x1, int y1, sprite &single, const spritePalette &fontPal, onScreenPerson *thisPerson, const int camX, const int camY, bool);
-void burnSpriteToBackDrop(int x1, int y1, sprite &single, const spritePalette &fontPal);
+void fixScaleSprite(int x1, int y1, sprite &single,
+		const spritePalette &fontPal, onScreenPerson *thisPerson,
+		const int camX, const int camY, bool);
+void burnSpriteToBackDrop(int x1, int y1, sprite &single,
+		const spritePalette &fontPal);
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/stringy.cpp b/engines/sludge/stringy.cpp
index a5440b6..5446f57 100644
--- a/engines/sludge/stringy.cpp
+++ b/engines/sludge/stringy.cpp
@@ -28,15 +28,17 @@
 namespace Sludge {
 
 char *copyString(const char *copyMe) {
-	char *newString = new char [strlen(copyMe) + 1];
-	if (! checkNew(newString)) return NULL;
+	char *newString = new char[strlen(copyMe) + 1];
+	if (!checkNew(newString))
+		return NULL;
 	strcpy(newString, copyMe);
 	return newString;
 }
 
 char *joinStrings(const char *s1, const char *s2) {
-	char *newString = new char [strlen(s1) + strlen(s2) + 1];
-	if (! checkNew(newString)) return NULL;
+	char *newString = new char[strlen(s1) + strlen(s2) + 1];
+	if (!checkNew(newString))
+		return NULL;
 	sprintf(newString, "%s%s", s1, s2);
 	return newString;
 }
diff --git a/engines/sludge/talk.cpp b/engines/sludge/talk.cpp
index abee33c..5e6c10d 100644
--- a/engines/sludge/talk.cpp
+++ b/engines/sludge/talk.cpp
@@ -60,7 +60,7 @@ void killAllSpeech() {
 	}
 
 	if (speech->currentTalker) {
-		makeSilent(* (speech->currentTalker));
+		makeSilent(*(speech->currentTalker));
 		speech->currentTalker = NULL;
 	}
 
@@ -96,8 +96,9 @@ void addSpeechLine(char *theLine, int x, int &offset) {
 	speech->allSpeech = newLine;
 	if ((xx1 < 5) && (offset < (5 - xx1))) {
 		offset = 5 - xx1;
-	} else if ((xx2 >= ((float)winWidth / cameraZoom) - 5) && (offset > (((float)winWidth / cameraZoom) - 5 - xx2))) {
-		offset = ((float)winWidth / cameraZoom) - 5 - xx2;
+	} else if ((xx2 >= ((float) winWidth / cameraZoom) - 5)
+			&& (offset > (((float) winWidth / cameraZoom) - 5 - xx2))) {
+		offset = ((float) winWidth / cameraZoom) - 5 - xx2;
 	}
 }
 
@@ -111,7 +112,8 @@ int wrapSpeechXY(char *theText, int x, int y, int wrap, int sampleFile) {
 	killAllSpeech();
 
 	int speechTime = (strlen(theText) + 20) * speechSpeed;
-	if (speechTime < 1) speechTime = 1;
+	if (speechTime < 1)
+		speechTime = 1;
 	if (sampleFile != -1) {
 		if (speechMode >= 1) {
 #if 0
@@ -128,7 +130,7 @@ int wrapSpeechXY(char *theText, int x, int y, int wrap, int sampleFile) {
 	while (strlen(theText) > wrap) {
 		a = wrap;
 		while (theText[a] != ' ') {
-			a --;
+			a--;
 			if (a == 0) {
 				a = wrap;
 				break;
@@ -143,8 +145,12 @@ int wrapSpeechXY(char *theText, int x, int y, int wrap, int sampleFile) {
 	addSpeechLine(theText, x, offset);
 	y -= fontHeight / cameraZoom;
 
-	if (y < 0) speech->speechY -= y;
-	else if (speech->speechY > cameraY + (float)(winHeight - fontHeight / 3) / cameraZoom) speech->speechY = cameraY + (float)(winHeight - fontHeight / 3) / cameraZoom;
+	if (y < 0)
+		speech->speechY -= y;
+	else if (speech->speechY
+			> cameraY + (float) (winHeight - fontHeight / 3) / cameraZoom)
+		speech->speechY = cameraY
+				+ (float) (winHeight - fontHeight / 3) / cameraZoom;
 
 	if (offset) {
 		speechLine *viewLine = speech->allSpeech;
@@ -156,8 +162,13 @@ int wrapSpeechXY(char *theText, int x, int y, int wrap, int sampleFile) {
 	return speechTime;
 }
 
-int wrapSpeechPerson(char *theText, onScreenPerson &thePerson, int sampleFile, bool animPerson) {
-	int i = wrapSpeechXY(theText, thePerson.x - cameraX, thePerson.y - cameraY - (thePerson.scale * (thePerson.height - thePerson.floaty)) - thePerson.thisType->speechGap, thePerson.thisType->wrapSpeech, sampleFile);
+int wrapSpeechPerson(char *theText, onScreenPerson &thePerson, int sampleFile,
+		bool animPerson) {
+	int i = wrapSpeechXY(theText, thePerson.x - cameraX,
+			thePerson.y - cameraY
+					- (thePerson.scale * (thePerson.height - thePerson.floaty))
+					- thePerson.thisType->speechGap,
+			thePerson.thisType->wrapSpeech, sampleFile);
 	if (animPerson) {
 		makeTalker(thePerson);
 		speech->currentTalker = &thePerson;
@@ -172,16 +183,20 @@ int wrapSpeech(char *theText, int objT, int sampleFile, bool animPerson) {
 	onScreenPerson *thisPerson = findPerson(objT);
 	if (thisPerson) {
 		setObjFontColour(thisPerson->thisType);
-		i = wrapSpeechPerson(theText, * thisPerson, sampleFile, animPerson);
+		i = wrapSpeechPerson(theText, *thisPerson, sampleFile, animPerson);
 	} else {
 		screenRegion *thisRegion = getRegionForObject(objT);
 		if (thisRegion) {
 			setObjFontColour(thisRegion->thisType);
-			i = wrapSpeechXY(theText, ((thisRegion->x1 + thisRegion->x2) >> 1) - cameraX, thisRegion->y1 - thisRegion->thisType->speechGap - cameraY, thisRegion->thisType->wrapSpeech, sampleFile);
+			i = wrapSpeechXY(theText,
+					((thisRegion->x1 + thisRegion->x2) >> 1) - cameraX,
+					thisRegion->y1 - thisRegion->thisType->speechGap - cameraY,
+					thisRegion->thisType->wrapSpeech, sampleFile);
 		} else {
 			objectType *temp = findObjectType(objT);
 			setObjFontColour(temp);
-			i = wrapSpeechXY(theText, winWidth >> 1, 10, temp->wrapSpeech, sampleFile);
+			i = wrapSpeechXY(theText, winWidth >> 1, 10, temp->wrapSpeech,
+					sampleFile);
 		}
 	}
 	return i;
diff --git a/engines/sludge/talk.h b/engines/sludge/talk.h
index 2ce4c4a..5e32def 100644
--- a/engines/sludge/talk.h
+++ b/engines/sludge/talk.h
@@ -32,7 +32,6 @@ struct speechLine {
 	int x;
 };
 
-
 struct speechStruct {
 	onScreenPerson *currentTalker;
 	speechLine *allSpeech;
diff --git a/engines/sludge/thumbnail.cpp b/engines/sludge/thumbnail.cpp
index c24946a..7c588a2 100644
--- a/engines/sludge/thumbnail.cpp
+++ b/engines/sludge/thumbnail.cpp
@@ -40,7 +40,6 @@ int thumbWidth = 0, thumbHeight = 0;
 extern GLuint backdropTextureName;
 #endif
 
-
 bool saveThumbnail(Common::WriteStream *stream) {
 #if 0
 	GLuint thumbnailTextureName = 0;
@@ -72,7 +71,6 @@ bool saveThumbnail(Common::WriteStream *stream) {
 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
 
-
 		const GLfloat vertices[] = {
 			0., 0., 0.,
 			thumbWidth - 1.f, 0., 0.,
@@ -120,8 +118,6 @@ bool saveThumbnail(Common::WriteStream *stream) {
 		glReadPixels(viewportOffsetX, viewportOffsetY, thumbWidth, thumbHeight, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, image);
 #endif
 
-
-
 		glUseProgram(0);
 #endif
 		setPixelCoords(false);
diff --git a/engines/sludge/timing.cpp b/engines/sludge/timing.cpp
index 887c4ed..6bf6863 100644
--- a/engines/sludge/timing.cpp
+++ b/engines/sludge/timing.cpp
@@ -59,4 +59,5 @@ void Wait_Frame(void) {
 }
 #endif
 
-} // End of namespace Sludge
+}
+               // End of namespace Sludge
diff --git a/engines/sludge/transition.cpp b/engines/sludge/transition.cpp
index 0fcd4fe..73ac737 100644
--- a/engines/sludge/transition.cpp
+++ b/engines/sludge/transition.cpp
@@ -113,7 +113,7 @@ void transitionSnapshotBox() {
 	//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
 	glBindTexture(GL_TEXTURE_2D, snapshotTextureName);
 
-	float xScale = (float) brightnessLevel * winWidth / 510.f;  // 510 = 255*2
+	float xScale = (float) brightnessLevel * winWidth / 510.f;// 510 = 255*2
 	float yScale = (float) brightnessLevel * winHeight / 510.f;
 
 	const GLfloat vertices[] = {
@@ -187,7 +187,6 @@ bool reserveTransitionTexture() {
 	return true;
 }
 
-
 void transitionDisolve() {
 
 #if 0
@@ -224,7 +223,7 @@ void transitionDisolve() {
 			toScreen[0] = toScreen[1] = toScreen[2] = toScreen[3] = 0;
 		}
 		toScreen += 4;
-	} while (toScreen < end);
+	}while (toScreen < end);
 
 	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 256, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, transitionTexture, transitionTextureName);
 
@@ -292,7 +291,7 @@ void transitionTV() {
 			toScreen[0] = toScreen[1] = toScreen[2] = toScreen[3] = 0;
 		}
 		toScreen += 4;
-	} while (toScreen < end);
+	}while (toScreen < end);
 
 	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 256, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, transitionTexture, transitionTextureName);
 
diff --git a/engines/sludge/variable.cpp b/engines/sludge/variable.cpp
index 928b65b..8d6beb2 100644
--- a/engines/sludge/variable.cpp
+++ b/engines/sludge/variable.cpp
@@ -41,10 +41,9 @@
 
 namespace Sludge {
 
-const char *typeName[] = {"undefined", "number", "user function", "string",
-                          "built-in function", "file", "stack",
-                          "object type", "animation", "costume"
-                         };
+const char *typeName[] = { "undefined", "number", "user function", "string",
+		"built-in function", "file", "stack", "object type", "animation",
+		"costume" };
 
 extern char *outputDir;
 
@@ -56,18 +55,19 @@ void unlinkVar(variable &thisVar) {
 		break;
 
 	case SVT_STACK:
-		thisVar.varData.theStack -> timesUsed --;
-		if (thisVar.varData.theStack -> timesUsed <= 0) {
-			while (thisVar.varData.theStack -> first) trimStack(thisVar.varData.theStack -> first);
+		thisVar.varData.theStack->timesUsed--;
+		if (thisVar.varData.theStack->timesUsed <= 0) {
+			while (thisVar.varData.theStack->first)
+				trimStack(thisVar.varData.theStack->first);
 			delete thisVar.varData.theStack;
 			thisVar.varData.theStack = NULL;
 		}
 		break;
 
 	case SVT_FASTARRAY:
-		thisVar.varData.fastArray -> timesUsed --;
-		if (thisVar.varData.theStack -> timesUsed <= 0) {
-			delete thisVar.varData.fastArray -> fastVariables;
+		thisVar.varData.fastArray->timesUsed--;
+		if (thisVar.varData.theStack->timesUsed <= 0) {
+			delete thisVar.varData.fastArray->fastVariables;
 			delete[] thisVar.varData.fastArray;
 			thisVar.varData.fastArray = NULL;
 		}
@@ -101,7 +101,8 @@ personaAnimation *getAnimationFromVar(variable &thisVar) {
 	if (thisVar.varType == SVT_INT && thisVar.varData.intValue == 0)
 		return makeNullAnim();
 
-	fatal("Expecting an animation variable; found variable of type", typeName[thisVar.varType]);
+	fatal("Expecting an animation variable; found variable of type",
+			typeName[thisVar.varType]);
 	return NULL;
 }
 
@@ -117,13 +118,15 @@ persona *getCostumeFromVar(variable &thisVar) {
 	switch (thisVar.varType) {
 	case SVT_ANIM:
 		p = new persona;
-		if (! checkNew(p)) return NULL;
-		p -> numDirections = 1;
-		p -> animation = new personaAnimation * [3];
-		if (! checkNew(p -> animation)) return NULL;
+		if (!checkNew(p))
+			return NULL;
+		p->numDirections = 1;
+		p->animation = new personaAnimation *[3];
+		if (!checkNew(p->animation))
+			return NULL;
 
-		for (int iii = 0; iii < 3; iii ++)
-			p -> animation[iii] = copyAnim(thisVar.varData.animHandler);
+		for (int iii = 0; iii < 3; iii++)
+			p->animation[iii] = copyAnim(thisVar.varData.animHandler);
 
 		break;
 
@@ -132,7 +135,8 @@ persona *getCostumeFromVar(variable &thisVar) {
 		break;
 
 	default:
-		fatal("Expecting an animation variable; found variable of type", typeName[thisVar.varType]);
+		fatal("Expecting an animation variable; found variable of type",
+				typeName[thisVar.varType]);
 	}
 
 	return p;
@@ -140,10 +144,10 @@ persona *getCostumeFromVar(variable &thisVar) {
 
 int stackSize(const stackHandler *me) {
 	int r = 0;
-	variableStack *a = me -> first;
+	variableStack *a = me->first;
 	while (a) {
-		r ++;
-		a = a -> next;
+		r++;
+		a = a->next;
 	}
 	return r;
 }
@@ -156,7 +160,8 @@ char *ConvertFromUTF16(const WCHAR *input);
 
 bool getSavedGamesStack(stackHandler *sH, char *ext) {
 	char *pattern = joinStrings("*", ext);
-	if (! pattern) return false;
+	if (!pattern)
+		return false;
 
 	variable newName;
 	newName.varType = SVT_NULL;
@@ -182,30 +187,32 @@ bool getSavedGamesStack(stackHandler *sH, char *ext) {
 			if (! addVarToStack(newName, sH -> first)) return false;
 			if (sH -> last == NULL) sH -> last = sH -> first;
 			keepGoing = FindNextFile(handle, & theData);
-		} while (keepGoing);
+		}while (keepGoing);
 		FindClose(handle);
 	}
 
 #else
 
 	DIR *dir = opendir(".");
-	if (! dir) return false;
+	if (!dir)
+		return false;
 
 	struct dirent *d = readdir(dir);
 	while (d != NULL) {
-		if (! strcmp(d->d_name + strlen(d->d_name) - strlen(ext), ext)) {
+		if (!strcmp(d->d_name + strlen(d->d_name) - strlen(ext), ext)) {
 			d->d_name[strlen(d->d_name) - strlen(ext)] = 0;
 			char *decoded = decodeFilename(d->d_name);
 			makeTextVar(newName, decoded);
 			delete[] decoded;
-			if (! addVarToStack(newName, sH -> first)) return false;
-			if (sH -> last == NULL) sH -> last = sH -> first;
+			if (!addVarToStack(newName, sH->first))
+				return false;
+			if (sH->last == NULL)
+				sH->last = sH->first;
 		}
 
 		d = readdir(dir);
 	}
 
-
 	closedir(dir);
 
 #endif
@@ -218,11 +225,12 @@ bool getSavedGamesStack(stackHandler *sH, char *ext) {
 bool copyStack(const variable &from, variable &to) {
 	to.varType = SVT_STACK;
 	to.varData.theStack = new stackHandler;
-	if (! checkNew(to.varData.theStack)) return false;
-	to.varData.theStack -> first = NULL;
-	to.varData.theStack -> last = NULL;
-	to.varData.theStack -> timesUsed = 1;
-	variableStack *a = from.varData.theStack -> first;
+	if (!checkNew(to.varData.theStack))
+		return false;
+	to.varData.theStack->first = NULL;
+	to.varData.theStack->last = NULL;
+	to.varData.theStack->timesUsed = 1;
+	variableStack *a = from.varData.theStack->first;
 
 #if DEBUG_STACKINESS
 	{
@@ -233,12 +241,12 @@ bool copyStack(const variable &from, variable &to) {
 #endif
 
 	while (a) {
-		addVarToStack(a -> thisVar, to.varData.theStack -> first);
-		if (to.varData.theStack -> last == NULL) {
+		addVarToStack(a->thisVar, to.varData.theStack->first);
+		if (to.varData.theStack->last == NULL) {
 #if DEBUG_STACKINESS
 			stackDebug((stackfp, "LAST"));
 #endif
-			to.varData.theStack -> last = to.varData.theStack -> first;
+			to.varData.theStack->last = to.varData.theStack->first;
 		}
 
 #if DEBUG_STACKINESS
@@ -249,7 +257,7 @@ bool copyStack(const variable &from, variable &to) {
 		}
 #endif
 
-		a = a -> next;
+		a = a->next;
 	}
 
 #if DEBUG_STACKINESS
@@ -265,10 +273,10 @@ bool copyStack(const variable &from, variable &to) {
 }
 
 /*void newStackVar (variable & thisVar) {
-    unlinkVar (thisVar);
-    thisVar.varType = VT_STACK;
-    thisVar.varData.theStack = NULL;
-} */
+ unlinkVar (thisVar);
+ thisVar.varType = VT_STACK;
+ thisVar.varData.theStack = NULL;
+ } */
 
 void addVariablesInSecond(variable &var1, variable &var2) {
 	if (var1.varType == SVT_INT && var2.varType == SVT_INT) {
@@ -330,7 +338,7 @@ void makeTextVar(variable &thisVar, const char *txt) {
 bool loadStringToVar(variable &thisVar, int value) {
 
 	makeTextVar(thisVar, getNumberedString(value));
-	return (bool)(thisVar.varData.theString != NULL);
+	return (bool) (thisVar.varData.theString != NULL);
 }
 
 char *getTextFromAnyVar(const variable &from) {
@@ -343,13 +351,16 @@ char *getTextFromAnyVar(const variable &from) {
 		char *builder2;
 		char *grabText;
 
-		for (int i = 0; i < from.varData.fastArray -> size; i ++) {
+		for (int i = 0; i < from.varData.fastArray->size; i++) {
 			builder2 = joinStrings(builder, " ");
-			if (! builder2) return NULL;
+			if (!builder2)
+				return NULL;
 			delete builder;
-			grabText = getTextFromAnyVar(from.varData.fastArray -> fastVariables[i]);
+			grabText = getTextFromAnyVar(
+					from.varData.fastArray->fastVariables[i]);
 			builder = joinStrings(builder2, grabText);
-			if (! builder) return NULL;
+			if (!builder)
+				return NULL;
 			delete grabText;
 			grabText = NULL;
 			delete builder2;
@@ -363,27 +374,30 @@ char *getTextFromAnyVar(const variable &from) {
 		char *builder2;
 		char *grabText;
 
-		variableStack *stacky = from.varData.theStack -> first;
+		variableStack *stacky = from.varData.theStack->first;
 
 		while (stacky) {
 			builder2 = joinStrings(builder, " ");
-			if (! builder2) return NULL;
+			if (!builder2)
+				return NULL;
 			delete builder;
-			grabText = getTextFromAnyVar(stacky -> thisVar);
+			grabText = getTextFromAnyVar(stacky->thisVar);
 			builder = joinStrings(builder2, grabText);
-			if (! builder) return NULL;
+			if (!builder)
+				return NULL;
 			delete grabText;
 			grabText = NULL;
 			delete builder2;
 			builder2 = NULL;
-			stacky = stacky -> next;
+			stacky = stacky->next;
 		}
 		return builder;
 	}
 
 	case SVT_INT: {
 		char *buff = new char[10];
-		if (! checkNew(buff)) return NULL;
+		if (!checkNew(buff))
+			return NULL;
 		sprintf(buff, "%i", from.varData.intValue);
 		return buff;
 	}
@@ -395,17 +409,18 @@ char *getTextFromAnyVar(const variable &from) {
 		return joinStrings("", resourceNameFromNum(from.varData.intValue));
 	}
 
-	/*      case SVT_ANIM:
-	        {
-	            char * buff = new char[20];
-	            if (! checkNew (buff)) return NULL;
-	            sprintf (buff, "%p", from.varData.animHandler);
-	            return buff;
-	        }*/
+		/*      case SVT_ANIM:
+		 {
+		 char * buff = new char[20];
+		 if (! checkNew (buff)) return NULL;
+		 sprintf (buff, "%p", from.varData.animHandler);
+		 return buff;
+		 }*/
 
 	case SVT_OBJTYPE: {
 		objectType *thisType = findObjectType(from.varData.intValue);
-		if (thisType) return copyString(thisType -> screenName);
+		if (thisType)
+			return copyString(thisType->screenName);
 	}
 
 	default:
@@ -421,16 +436,16 @@ bool getBoolean(const variable &from) {
 		return false;
 
 	case SVT_INT:
-		return (bool)(from.varData.intValue != 0);
+		return (bool) (from.varData.intValue != 0);
 
 	case SVT_STACK:
-		return (bool)(from.varData.theStack -> first != NULL);
+		return (bool) (from.varData.theStack->first != NULL);
 
 	case SVT_STRING:
-		return (bool)(from.varData.theString[0] != 0);
+		return (bool) (from.varData.theString[0] != 0);
 
 	case SVT_FASTARRAY:
-		return (bool)(from.varData.fastArray -> size != 0);
+		return (bool) (from.varData.fastArray->size != 0);
 
 	default:
 		break;
@@ -451,7 +466,7 @@ bool copyMain(const variable &from, variable &to) {
 
 	case SVT_FASTARRAY:
 		to.varData.fastArray = from.varData.fastArray;
-		to.varData.fastArray -> timesUsed ++;
+		to.varData.fastArray->timesUsed++;
 		return true;
 
 	case SVT_STRING:
@@ -460,7 +475,7 @@ bool copyMain(const variable &from, variable &to) {
 
 	case SVT_STACK:
 		to.varData.theStack = from.varData.theStack;
-		to.varData.theStack -> timesUsed ++;
+		to.varData.theStack->timesUsed++;
 		return true;
 
 	case SVT_COSTUME:
@@ -487,109 +502,124 @@ bool copyVariable(const variable &from, variable &to) {
 }
 
 variable *fastArrayGetByIndex(fastArrayHandler *vS, unsigned int theIndex) {
-	if (theIndex < 0 || theIndex >= vS -> size) return NULL;
-	return & vS -> fastVariables[theIndex];
+	if (theIndex < 0 || theIndex >= vS->size)
+		return NULL;
+	return &vS->fastVariables[theIndex];
 }
 
 bool makeFastArraySize(variable &to, int size) {
-	if (size < 0) return fatal("Can't create a fast array with a negative number of elements!");
+	if (size < 0)
+		return fatal(
+				"Can't create a fast array with a negative number of elements!");
 	unlinkVar(to);
 	to.varType = SVT_FASTARRAY;
 	to.varData.fastArray = new fastArrayHandler;
-	if (! checkNew(to.varData.fastArray)) return false;
-	to.varData.fastArray -> fastVariables = new variable[size];
-	if (! checkNew(to.varData.fastArray -> fastVariables)) return false;
-	for (int i = 0; i < size; i ++) {
-		initVarNew(to.varData.fastArray -> fastVariables[i]);
+	if (!checkNew(to.varData.fastArray))
+		return false;
+	to.varData.fastArray->fastVariables = new variable[size];
+	if (!checkNew(to.varData.fastArray->fastVariables))
+		return false;
+	for (int i = 0; i < size; i++) {
+		initVarNew(to.varData.fastArray->fastVariables[i]);
 	}
-	to.varData.fastArray -> size = size;
-	to.varData.fastArray -> timesUsed = 1;
+	to.varData.fastArray->size = size;
+	to.varData.fastArray->timesUsed = 1;
 	return true;
 }
 
 bool makeFastArrayFromStack(variable &to, const stackHandler *stacky) {
 	int size = stackSize(stacky);
-	if (! makeFastArraySize(to, size)) return false;
+	if (!makeFastArraySize(to, size))
+		return false;
 
 	// Now let's fill up the new array
 
-	variableStack *allV = stacky -> first;
+	variableStack *allV = stacky->first;
 	size = 0;
 	while (allV) {
-		copyMain(allV -> thisVar, to.varData.fastArray -> fastVariables[size]);
-		size ++;
-		allV = allV -> next;
+		copyMain(allV->thisVar, to.varData.fastArray->fastVariables[size]);
+		size++;
+		allV = allV->next;
 	}
 	return true;
 }
 
 /*
-bool moveVariable (variable & from, variable & to) {
-    unlinkVar (to);
-    memcpy (& to, & from, sizeof (variable));
-    from.varType = SVT_NULL;
-}
-*/
+ bool moveVariable (variable & from, variable & to) {
+ unlinkVar (to);
+ memcpy (& to, & from, sizeof (variable));
+ from.varType = SVT_NULL;
+ }
+ */
 
 bool addVarToStack(const variable &va, variableStack *&thisStack) {
 	variableStack *newStack = new variableStack;
-	if (! checkNew(newStack)) return false;
+	if (!checkNew(newStack))
+		return false;
 
-	if (! copyMain(va, newStack -> thisVar)) return false;
-	newStack -> next = thisStack;
+	if (!copyMain(va, newStack->thisVar))
+		return false;
+	newStack->next = thisStack;
 	thisStack = newStack;
-	debug(kSludgeDebugStackMachine, "Variable %s was added to stack", getTextFromAnyVar(va));
+	debug(kSludgeDebugStackMachine, "Variable %s was added to stack",
+			getTextFromAnyVar(va));
 	return true;
 }
 
 bool addVarToStackQuick(variable &va, variableStack *&thisStack) {
 	variableStack *newStack = new variableStack;
-	if (! checkNew(newStack)) return false;
+	if (!checkNew(newStack))
+		return false;
 
 //	if (! copyMain (va, newStack -> thisVar)) return false;
 
-	memcpy(& (newStack -> thisVar), & va, sizeof(variable));
+	memcpy(&(newStack->thisVar), &va, sizeof(variable));
 	va.varType = SVT_NULL;
 
-	newStack -> next = thisStack;
+	newStack->next = thisStack;
 	thisStack = newStack;
-	debug(kSludgeDebugStackMachine, "Variable %s was added to stack quick", getTextFromAnyVar(va));
+	debug(kSludgeDebugStackMachine, "Variable %s was added to stack quick",
+			getTextFromAnyVar(va));
 	return true;
 }
 
-bool stackSetByIndex(variableStack *vS, unsigned int theIndex, const variable &va) {
-	while (theIndex --) {
-		vS = vS -> next;
-		if (! vS) return fatal("Index past end of stack.");
+bool stackSetByIndex(variableStack *vS, unsigned int theIndex,
+		const variable &va) {
+	while (theIndex--) {
+		vS = vS->next;
+		if (!vS)
+			return fatal("Index past end of stack.");
 	}
-	return copyVariable(va, vS -> thisVar);
+	return copyVariable(va, vS->thisVar);
 }
 
 variable *stackGetByIndex(variableStack *vS, unsigned int theIndex) {
-	while (theIndex --) {
-		vS = vS -> next;
-		if (! vS) {
+	while (theIndex--) {
+		vS = vS->next;
+		if (!vS) {
 			return NULL;
 		}
 	}
-	return & (vS -> thisVar);
+	return &(vS->thisVar);
 }
 
-int deleteVarFromStack(const variable &va, variableStack *&thisStack, bool allOfEm) {
-	variableStack * * huntVar = & thisStack;
+int deleteVarFromStack(const variable &va, variableStack *&thisStack,
+		bool allOfEm) {
+	variableStack * * huntVar = &thisStack;
 	variableStack *killMe;
 	int reply = 0;
 
-	while (* huntVar) {
-		if (compareVars((* huntVar) -> thisVar, va)) {
-			killMe = * huntVar;
-			* huntVar = killMe -> next;
-			unlinkVar(killMe -> thisVar);
+	while (*huntVar) {
+		if (compareVars((*huntVar)->thisVar, va)) {
+			killMe = *huntVar;
+			*huntVar = killMe->next;
+			unlinkVar(killMe->thisVar);
 			delete killMe;
-			if (! allOfEm) return 1;
-			reply ++;
+			if (!allOfEm)
+				return 1;
+			reply++;
 		} else {
-			huntVar = & ((* huntVar) -> next);
+			huntVar = &((*huntVar)->next);
 		}
 	}
 
@@ -610,8 +640,12 @@ variableStack *stackFindLast(variableStack *hunt) {
 bool getValueType(int &toHere, variableType vT, const variable &v) {
 	//if (! v) return false;
 	if (v.varType != vT) {
-		char *e1 = joinStrings("Can only perform specified operation on a value which is of type ", typeName[vT]);
-		char *e2 = joinStrings("... value supplied was of type ", typeName[v.varType]);
+		char *e1 =
+				joinStrings(
+						"Can only perform specified operation on a value which is of type ",
+						typeName[vT]);
+		char *e2 = joinStrings("... value supplied was of type ",
+				typeName[v.varType]);
 		fatal(e1, e2);
 
 		return false;
@@ -622,50 +656,51 @@ bool getValueType(int &toHere, variableType vT, const variable &v) {
 
 void trimStack(variableStack *&stack) {
 	variableStack *killMe = stack;
-	stack = stack -> next;
+	stack = stack->next;
 
-	debug(kSludgeDebugStackMachine, "Variable %s was removed from stack", getTextFromAnyVar(killMe -> thisVar));
+	debug(kSludgeDebugStackMachine, "Variable %s was removed from stack",
+			getTextFromAnyVar(killMe->thisVar));
 
 	// When calling this, we've ALWAYS checked that stack != NULL
-	unlinkVar(killMe -> thisVar);
+	unlinkVar(killMe->thisVar);
 	delete killMe;
 }
 /*
-void debugVar (FILE * fp, const variable & thisVar) {
-    switch (thisVar.varType) {
-        case SVT_INT:
-        fprintf (fp, "integer value %i", thisVar.varData.intValue);
-        break;
-
-        case SVT_FUNC:
-        fprintf (fp, "pointer to function %i", thisVar.varData.intValue);
-        break;
-
-        case SVT_BUILT:
-        fprintf (fp, "pointer to bif %i", thisVar.varData.intValue);
-        break;
-
-        case SVT_OBJTYPE:
-        fprintf (fp, "object type %i", thisVar.varData.intValue);
-        break;
-
-        case SVT_STRING:
-        fprintf (fp, "\"%s\"", thisVar.varData.theString);
-        break;
-
-        case SVT_FILE:
-        fprintf (fp, "file handle %i", thisVar.varData.intValue);
-        break;
-
-        case SVT_NULL:
-        fprintf (fp, "null");
-        break;
-
-        default:
-        fprintf (fp, "unknown variable type");
-        break;
-    }
-}
-*/
+ void debugVar (FILE * fp, const variable & thisVar) {
+ switch (thisVar.varType) {
+ case SVT_INT:
+ fprintf (fp, "integer value %i", thisVar.varData.intValue);
+ break;
+
+ case SVT_FUNC:
+ fprintf (fp, "pointer to function %i", thisVar.varData.intValue);
+ break;
+
+ case SVT_BUILT:
+ fprintf (fp, "pointer to bif %i", thisVar.varData.intValue);
+ break;
+
+ case SVT_OBJTYPE:
+ fprintf (fp, "object type %i", thisVar.varData.intValue);
+ break;
+
+ case SVT_STRING:
+ fprintf (fp, "\"%s\"", thisVar.varData.theString);
+ break;
+
+ case SVT_FILE:
+ fprintf (fp, "file handle %i", thisVar.varData.intValue);
+ break;
+
+ case SVT_NULL:
+ fprintf (fp, "null");
+ break;
+
+ default:
+ fprintf (fp, "unknown variable type");
+ break;
+ }
+ }
+ */
 
 } // End of namespace Sludge
diff --git a/engines/sludge/variable.h b/engines/sludge/variable.h
index 8f9f743..295473e 100644
--- a/engines/sludge/variable.h
+++ b/engines/sludge/variable.h
@@ -27,41 +27,50 @@ namespace Sludge {
 struct variable;
 struct variableStack;
 
-enum variableType {SVT_NULL, SVT_INT, SVT_FUNC, SVT_STRING,
-                   SVT_BUILT, SVT_FILE, SVT_STACK,
-                   SVT_OBJTYPE, SVT_ANIM, SVT_COSTUME,
-                   SVT_FASTARRAY, SVT_NUM_TYPES
-                  };
+enum variableType {
+	SVT_NULL,
+	SVT_INT,
+	SVT_FUNC,
+	SVT_STRING,
+	SVT_BUILT,
+	SVT_FILE,
+	SVT_STACK,
+	SVT_OBJTYPE,
+	SVT_ANIM,
+	SVT_COSTUME,
+	SVT_FASTARRAY,
+	SVT_NUM_TYPES
+};
 
 struct fastArrayHandler {
-	struct variable            *fastVariables;
-	int                         size;
-	int                         timesUsed;
+	struct variable *fastVariables;
+	int size;
+	int timesUsed;
 };
 
 struct stackHandler {
-	struct variableStack       *first;
-	struct variableStack       *last;
-	int                         timesUsed;
+	struct variableStack *first;
+	struct variableStack *last;
+	int timesUsed;
 };
 
 union variableData {
-	signed int                  intValue;
-	char                       *theString;
-	stackHandler               *theStack;
-	struct personaAnimation    *animHandler;
-	struct persona             *costumeHandler;
-	fastArrayHandler           *fastArray;
+	signed int intValue;
+	char *theString;
+	stackHandler *theStack;
+	struct personaAnimation *animHandler;
+	struct persona *costumeHandler;
+	fastArrayHandler *fastArray;
 };
 
 struct variable {
-	variableType                varType;
-	variableData                varData;
+	variableType varType;
+	variableData varData;
 };
 
 struct variableStack {
-	variable                    thisVar;
-	variableStack              *next;
+	variable thisVar;
+	variableStack *next;
 };
 
 // Initialisation
@@ -94,7 +103,8 @@ bool getValueType(int &toHere, variableType vT, const variable &v);
 bool addVarToStack(const variable &va, variableStack *&thisStack);
 bool addVarToStackQuick(variable &va, variableStack *&thisStack);
 void trimStack(variableStack *&stack);
-int deleteVarFromStack(const variable &va, variableStack *&thisStack, bool allOfEm = false);
+int deleteVarFromStack(const variable &va, variableStack *&thisStack,
+		bool allOfEm = false);
 variableStack *stackFindLast(variableStack *hunt);
 bool copyStack(const variable &from, variable &to);
 int stackSize(const stackHandler *me);
@@ -106,7 +116,6 @@ bool makeFastArrayFromStack(variable &to, const stackHandler *stacky);
 bool makeFastArraySize(variable &to, int size);
 variable *fastArrayGetByIndex(fastArrayHandler *vS, unsigned int theIndex);
 
-
 #define DEBUG_STACKINESS    0
 
 #if DEBUG_STACKINESS
diff --git a/engines/sludge/vid.cpp b/engines/sludge/vid.cpp
index 13eea52..00e2063 100644
--- a/engines/sludge/vid.cpp
+++ b/engines/sludge/vid.cpp
@@ -40,10 +40,10 @@
 namespace Sludge {
 
 struct timStream {
-	PAVISTREAM      got;
-	AVISTREAMINFO   info;
-	LONG            chunkSize;
-	LPBYTE          chunk;
+	PAVISTREAM got;
+	AVISTREAMINFO info;
+	LONG chunkSize;
+	LPBYTE chunk;
 };
 
 static PAVIFILE pAviFile = NULL;
@@ -64,27 +64,32 @@ extern HWND hMainWindow;
 
 void initialiseMovieStuff() {
 	char buffer[500];
-	if (ExpandEnvironmentStrings("%temp%", buffer, 499) == 0) buffer[0] = NULL;
+	if (ExpandEnvironmentStrings("%temp%", buffer, 499) == 0)
+		buffer[0] = NULL;
 	videoFile = joinStrings(buffer, "\\test.avi");
 //	warning (videoFile);
 }
 
 bool getStream(DWORD type, timStream &intoHere) {
-	if (AVIFileGetStream(pAviFile, & intoHere.got, type, 0)) {
+	if (AVIFileGetStream(pAviFile, &intoHere.got, type, 0)) {
 		intoHere.got = NULL;
 		return true;
-	} else if (AVIStreamInfo(intoHere.got, & intoHere.info, sizeof(AVISTREAMINFO))) {
+	} else if (AVIStreamInfo(intoHere.got, &intoHere.info,
+			sizeof(AVISTREAMINFO))) {
 		return fatal("Can't get stream info");
-	} else if (AVIStreamReadFormat(intoHere.got, AVIStreamStart(intoHere.got), NULL, & intoHere.chunkSize)) {
+	} else if (AVIStreamReadFormat(intoHere.got, AVIStreamStart(intoHere.got),
+	NULL, &intoHere.chunkSize)) {
 		return fatal("Can't get stream chunk size");
 	} else {
 		// So far so good! Let's read a chunk of data (huh?)
 
 		intoHere.chunk = new BYTE[intoHere.chunkSize];
 
-		if (! intoHere.chunk) {
+		if (!intoHere.chunk) {
 			return fatal("Out of memory");
-		} else if (AVIStreamReadFormat(intoHere.got, AVIStreamStart(intoHere.got), intoHere.chunk, & intoHere.chunkSize)) {
+		} else if (AVIStreamReadFormat(intoHere.got,
+				AVIStreamStart(intoHere.got), intoHere.chunk,
+				&intoHere.chunkSize)) {
 			return fatal("Couldn't read stream format");
 		}
 	}
@@ -97,46 +102,48 @@ void killStream(timStream &intoHere) {
 }
 
 /*
-#define WAVHEADERSIZE 20
-char wavHeader[WAVHEADERSIZE] = {'R', 'I', 'F', 'F', 0, 0, 0, 0,
-                                 'W', 'A', 'V', 'E', 'f', 'm', 't',
-                                 0x20, 0x10, 0, 0, 0};
-
-void handleAudio () {
-    LONG aSize;
-
-    if(AVIStreamRead(audio.got, 0, AVISTREAMREAD_CONVENIENT, NULL, 0, & aSize, NULL)) return;
-
-    int totalSize = aSize + audio.chunkSize + WAVHEADERSIZE + 4;
-
-    LPBYTE pBuffer = new BYTE[totalSize];
-    if (!pBuffer) return;
-
-    memcpy (pBuffer, wavHeader, WAVHEADERSIZE);
-    pBuffer[4] = (char) (aSize);
-    pBuffer[5] = (char) (aSize >> 8);
-    memcpy (pBuffer + WAVHEADERSIZE, audio.chunk, audio.chunkSize);
-    memcpy (pBuffer + WAVHEADERSIZE + audio.chunkSize, "data", 4);
-
-    if(! AVIStreamRead (audio.got, 0, AVISTREAMREAD_CONVENIENT, pBuffer + audio.chunkSize + WAVHEADERSIZE + 4, aSize, NULL, NULL)) {
-        FILE * fp = fopen ("test.wav", "wb");
-        if (fp) {
-            fwrite (pBuffer, 1, totalSize, fp);
-            fclose (fp);
-        }
-        int i = fakeCacheSoundForVideo ((char *) pBuffer, totalSize);
-        if (i != -1) startSound (i, false);
-    }
-
-    delete pBuffer;
-}
-*/
+ #define WAVHEADERSIZE 20
+ char wavHeader[WAVHEADERSIZE] = {'R', 'I', 'F', 'F', 0, 0, 0, 0,
+ 'W', 'A', 'V', 'E', 'f', 'm', 't',
+ 0x20, 0x10, 0, 0, 0};
+
+ void handleAudio () {
+ LONG aSize;
+
+ if(AVIStreamRead(audio.got, 0, AVISTREAMREAD_CONVENIENT, NULL, 0, & aSize, NULL)) return;
+
+ int totalSize = aSize + audio.chunkSize + WAVHEADERSIZE + 4;
+
+ LPBYTE pBuffer = new BYTE[totalSize];
+ if (!pBuffer) return;
+
+ memcpy (pBuffer, wavHeader, WAVHEADERSIZE);
+ pBuffer[4] = (char) (aSize);
+ pBuffer[5] = (char) (aSize >> 8);
+ memcpy (pBuffer + WAVHEADERSIZE, audio.chunk, audio.chunkSize);
+ memcpy (pBuffer + WAVHEADERSIZE + audio.chunkSize, "data", 4);
+
+ if(! AVIStreamRead (audio.got, 0, AVISTREAMREAD_CONVENIENT, pBuffer + audio.chunkSize + WAVHEADERSIZE + 4, aSize, NULL, NULL)) {
+ FILE * fp = fopen ("test.wav", "wb");
+ if (fp) {
+ fwrite (pBuffer, 1, totalSize, fp);
+ fclose (fp);
+ }
+ int i = fakeCacheSoundForVideo ((char *) pBuffer, totalSize);
+ if (i != -1) startSound (i, false);
+ }
+
+ delete pBuffer;
+ }
+ */
 
 void finishVideo() {
 	videoPlaying = false;
 	AVIStreamGetFrameClose(pgf);
-	if (audio.got) AVIStreamRelease(audio.got);
-	if (video.got) AVIStreamRelease(video.got);
+	if (audio.got)
+		AVIStreamRelease(audio.got);
+	if (video.got)
+		AVIStreamRelease(video.got);
 	killStream(audio);
 	killStream(video);
 	AVIFileRelease(pAviFile);
@@ -144,17 +151,19 @@ void finishVideo() {
 #ifdef _MSC_VER
 	_unlink(videoFile);
 #else
-	unlink(videoFile);
+	unlink(videoFile)
+;
 #endif
 }
 
 #define COPYSIZE 256
 
 bool extractSlice(int fileNum, char *toName) {
-	unsigned char buff[COPYSIZE];
+unsigned char buff[COPYSIZE];
 
-	unsigned long fileLength = openFileFromNum(fileNum);
-	if (! fileLength) return false; // Error already displayed
+unsigned long fileLength = openFileFromNum(fileNum);
+if (!fileLength)
+	return false; // Error already displayed
 #if 0
 	FILE *copyVid = fopen(toName, "wb");
 	if (! copyVid) return fatal("Can't extract resource");
@@ -171,94 +180,100 @@ bool extractSlice(int fileNum, char *toName) {
 
 	fclose(copyVid);
 #endif
-	finishAccess();
+finishAccess();
 
-	return true;
+return true;
 }
 
 bool startVideo(int fileNum) {
 
-	setResourceForFatal(fileNum);
+setResourceForFatal(fileNum);
 
-	AVIFILEINFO info;
+AVIFILEINFO info;
 
-	if (videoPlaying) finishVideo();
-	AVIFileInit();
+if (videoPlaying)
+	finishVideo();
+AVIFileInit();
 
-	if (! extractSlice(fileNum, videoFile)) return false;
-	if (AVIFileOpen(& pAviFile, videoFile, OF_READ, NULL))
-		return fatal(ERROR_AVI_FILE_ERROR);
+if (!extractSlice(fileNum, videoFile))
+	return false;
+if (AVIFileOpen(&pAviFile, videoFile, OF_READ, NULL))
+	return fatal(ERROR_AVI_FILE_ERROR);
 
-	AVIFileInfo(pAviFile, &info, sizeof(info));
+AVIFileInfo(pAviFile, &info, sizeof(info));
 
-	if (! getStream(streamtypeAUDIO, audio)) return false;
-	if (! getStream(streamtypeVIDEO, video)) return false;
+if (!getStream(streamtypeAUDIO, audio))
+	return false;
+if (!getStream(streamtypeVIDEO, video))
+	return false;
 
-	if (! video.got) return fatal(ERROR_AVI_NO_STREAM);
+if (!video.got)
+	return fatal(ERROR_AVI_NO_STREAM);
 
 //	if (audio.got) handleAudio ();
 
-	pgf = AVIStreamGetFrameOpen(video.got, NULL);
-	if (!pgf) return fatal(ERROR_AVI_ARGH);
+pgf = AVIStreamGetFrameOpen(video.got, NULL);
+if (!pgf)
+	return fatal(ERROR_AVI_ARGH);
 
-	LPBITMAPINFO pInfo = (LPBITMAPINFO)(video.chunk);
-	vidBytesPerPixel = pInfo -> bmiHeader.biBitCount / 8;
-	biSize = pInfo -> bmiHeader.biSize;
-	vidWidth = pInfo -> bmiHeader.biWidth;
-	vidHeight = pInfo -> bmiHeader.biHeight;
+LPBITMAPINFO pInfo = (LPBITMAPINFO)(video.chunk);
+vidBytesPerPixel = pInfo->bmiHeader.biBitCount / 8;
+biSize = pInfo->bmiHeader.biSize;
+vidWidth = pInfo->bmiHeader.biWidth;
+vidHeight = pInfo->bmiHeader.biHeight;
 
-	videoFrameNum = 0;
-	videoPlaying = true;
+videoFrameNum = 0;
+videoPlaying = true;
 
-	setResourceForFatal(-1);
+setResourceForFatal(-1);
 
-	return true;
+return true;
 }
 
 bool nextVideoFrame() {
-	LPBITMAPINFOHEADER lpbi = (LPBITMAPINFOHEADER) AVIStreamGetFrame(pgf, videoFrameNum);
-	if (! lpbi) {
-		finishVideo();
-		return false;
-	}
+LPBITMAPINFOHEADER lpbi = (LPBITMAPINFOHEADER) AVIStreamGetFrame(pgf,
+		videoFrameNum);
+if (!lpbi) {
+	finishVideo();
+	return false;
+}
+
+BYTE *pData = (((BYTE *) lpbi) + lpbi->biSize);
+
+int xOff = (winWidth - vidWidth) >> 1;
+int yOff = (winHeight + vidHeight) >> 1;
+unsigned short int *startingPoint = screen + xOff + (yOff * winWidth);
 
-	BYTE *pData = (((BYTE *) lpbi) + lpbi->biSize);
-
-	int xOff = (winWidth - vidWidth) >> 1;
-	int yOff = (winHeight + vidHeight) >> 1;
-	unsigned short int *startingPoint = screen + xOff + (yOff * winWidth);
-
-	for (int y = 0; y < vidHeight; y ++) {
-		startingPoint -= winWidth;
-		unsigned short int *toHere = startingPoint;
-		for (int x = 0; x < vidWidth; x ++) {
-			switch (vidBytesPerPixel) {
-			case 1:
-				(* toHere) = makeGrey(*pData);
-				break;
-
-			case 3:
-			case 4:
-				(* toHere) = makeColour(*(pData + 2), *(pData + 1), *pData);
-				break;
-
-			default: {
-				WORD Pixel16 = * ((WORD *) pData);
-				(* toHere) = makeColour(
-				                 (((UINT)(Pixel16) >> 10) & 0x1F) << 3,
-				                 (((UINT)(Pixel16) >> 5) & 0x1F) << 3,
-				                 (((UINT)(Pixel16) >> 0) & 0x1F) << 3);
-			}
+for (int y = 0; y < vidHeight; y++) {
+	startingPoint -= winWidth;
+	unsigned short int *toHere = startingPoint;
+	for (int x = 0; x < vidWidth; x++) {
+		switch (vidBytesPerPixel) {
+		case 1:
+			(*toHere) = makeGrey(*pData);
 			break;
-			}
-			pData += vidBytesPerPixel;
-			toHere ++;
+
+		case 3:
+		case 4:
+			(*toHere) = makeColour(*(pData + 2), *(pData + 1), *pData);
+			break;
+
+		default: {
+			WORD Pixel16 = *((WORD *) pData);
+			(*toHere) = makeColour((((UINT)(Pixel16) >> 10) & 0x1F) << 3,
+					(((UINT)(Pixel16) >> 5) & 0x1F) << 3,
+					(((UINT)(Pixel16) >> 0) & 0x1F) << 3);
 		}
+			break;
+		}
+		pData += vidBytesPerPixel;
+		toHere++;
 	}
+}
 
-	videoFrameNum ++;
+videoFrameNum++;
 
-	return true;
+return true;
 }
 
 } // End of namespace Sludge
diff --git a/engines/sludge/winstuff.cpp b/engines/sludge/winstuff.cpp
index 266df69..a229225 100644
--- a/engines/sludge/winstuff.cpp
+++ b/engines/sludge/winstuff.cpp
@@ -53,179 +53,178 @@
 
 namespace Sludge {
 
-HINSTANCE hInst;                // Handle of the main instance
-extern HWND hMainWindow;
+	HINSTANCE hInst;                // Handle of the main instance
+	extern HWND hMainWindow;
 
-extern variableStack *noStack;
+	extern variableStack *noStack;
 
 // The platform-specific functions - Windows edition.
 
-WCHAR *ConvertToUTF16(const char *input) {
-	int s = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, input, -1, NULL, 0);
-	WCHAR *ret = new WCHAR [s];
-	checkNew(ret);
-	/*int a = */MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, input, -1, ret, s);
-	return ret;
-}
-
-char *ConvertFromUTF16(const WCHAR *input) {
-	int s = WideCharToMultiByte(CP_UTF8, 0, input, -1, NULL, 0, NULL, NULL);
-	char *ret = new char [s];
-	checkNew(ret);
-	/*int a = */WideCharToMultiByte(CP_UTF8, 0, input, -1, ret, s, NULL, NULL);
-	return ret;
-}
-
-
-char *grabFileName() {
-	OPENFILENAME ofn;
-	WCHAR path[MAX_PATH];
-	WCHAR file[MAX_PATH] = TEXT("");
-
-	hInst = GetModuleHandle(NULL);
-
-	memset(& ofn, 0, sizeof(ofn));
-	ofn.lStructSize = sizeof(ofn);
-	ofn.hwndOwner = NULL;
-	ofn.hInstance = hInst;
-	ofn.nMaxFile = MAX_PATH;
-	ofn.lpstrInitialDir = path;
-	ofn.Flags = OFN_HIDEREADONLY | OFN_EXPLORER;
-	ofn.lpstrFilter = TEXT("SLUDGE games (*.SLG)\0*.slg\0\0");
-	ofn.lpstrFile = file;
-
-	if (GetOpenFileName(& ofn)) {
-		return ConvertFromUTF16(file);
-	} else {
-		return NULL;
+	WCHAR *ConvertToUTF16(const char *input) {
+		int s = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, input, -1, NULL, 0);
+		WCHAR *ret = new WCHAR [s];
+		checkNew(ret);
+		/*int a = */MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, input, -1, ret, s);
+		return ret;
 	}
-}
 
-extern char **languageName;
-extern int *languageTable;
-
-HBITMAP hLogo = NULL;
-extern unsigned char *gameLogo;
+	char *ConvertFromUTF16(const WCHAR *input) {
+		int s = WideCharToMultiByte(CP_UTF8, 0, input, -1, NULL, 0, NULL, NULL);
+		char *ret = new char [s];
+		checkNew(ret);
+		/*int a = */WideCharToMultiByte(CP_UTF8, 0, input, -1, ret, s, NULL, NULL);
+		return ret;
+	}
 
-BOOL CALLBACK setupDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
-	switch (message) {
-	case WM_INITDIALOG:
-		if (gameLogo) {
-			hLogo = CreateBitmap(310, 88, 1, 32, gameLogo);
-			SendDlgItemMessage(hDlg, 1003, STM_SETIMAGE, (WPARAM)IMAGE_BITMAP, (LPARAM)hLogo);
+	char *grabFileName() {
+		OPENFILENAME ofn;
+		WCHAR path[MAX_PATH];
+		WCHAR file[MAX_PATH] = TEXT("");
+
+		hInst = GetModuleHandle(NULL);
+
+		memset(& ofn, 0, sizeof(ofn));
+		ofn.lStructSize = sizeof(ofn);
+		ofn.hwndOwner = NULL;
+		ofn.hInstance = hInst;
+		ofn.nMaxFile = MAX_PATH;
+		ofn.lpstrInitialDir = path;
+		ofn.Flags = OFN_HIDEREADONLY | OFN_EXPLORER;
+		ofn.lpstrFilter = TEXT("SLUDGE games (*.SLG)\0*.slg\0\0");
+		ofn.lpstrFile = file;
+
+		if (GetOpenFileName(& ofn)) {
+			return ConvertFromUTF16(file);
+		} else {
+			return NULL;
 		}
+	}
+
+	extern char **languageName;
+	extern int *languageTable;
+
+	HBITMAP hLogo = NULL;
+	extern unsigned char *gameLogo;
+
+	BOOL CALLBACK setupDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
+		switch (message) {
+			case WM_INITDIALOG:
+			if (gameLogo) {
+				hLogo = CreateBitmap(310, 88, 1, 32, gameLogo);
+				SendDlgItemMessage(hDlg, 1003, STM_SETIMAGE, (WPARAM)IMAGE_BITMAP, (LPARAM)hLogo);
+			}
 
-		if (gameSettings.userFullScreen)
+			if (gameSettings.userFullScreen)
 			CheckDlgButton(hDlg, 1000, BST_CHECKED);
-		else
+			else
 			CheckDlgButton(hDlg, 1000, BST_UNCHECKED);
 
-		SendDlgItemMessage(hDlg, 1002, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)TEXT("Default (best looking)")));
-		SendDlgItemMessage(hDlg, 1002, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)TEXT("Linear (faster but blurry)")));
-		SendDlgItemMessage(hDlg, 1002, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)TEXT("Off (blocky graphics)")));
+			SendDlgItemMessage(hDlg, 1002, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)TEXT("Default (best looking)")));
+			SendDlgItemMessage(hDlg, 1002, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)TEXT("Linear (faster but blurry)")));
+			SendDlgItemMessage(hDlg, 1002, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)TEXT("Off (blocky graphics)")));
 
-		if (gameSettings.antiAlias < 0)
+			if (gameSettings.antiAlias < 0)
 			SendDlgItemMessage(hDlg, 1002, CB_SETCURSEL, 1, 0);
-		else if (gameSettings.antiAlias)
+			else if (gameSettings.antiAlias)
 			SendDlgItemMessage(hDlg, 1002, CB_SETCURSEL, 0, 0);
-		else
+			else
 			SendDlgItemMessage(hDlg, 1002, CB_SETCURSEL, 2, 0);
 
-		if (gameSettings.numLanguages) {
-			WCHAR text[20];
-			for (unsigned int i = 0; i <= gameSettings.numLanguages; i++) {
-				if (languageName[i]) {
-					WCHAR *w_lang = ConvertToUTF16(languageName[i]);
-					SendDlgItemMessage(hDlg, 1001, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)w_lang));
-					delete w_lang;
-				} else {
-					swprintf(text, TEXT("Language %d"), i);
-					SendDlgItemMessage(hDlg, 1001, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)text));
+			if (gameSettings.numLanguages) {
+				WCHAR text[20];
+				for (unsigned int i = 0; i <= gameSettings.numLanguages; i++) {
+					if (languageName[i]) {
+						WCHAR *w_lang = ConvertToUTF16(languageName[i]);
+						SendDlgItemMessage(hDlg, 1001, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)w_lang));
+						delete w_lang;
+					} else {
+						swprintf(text, TEXT("Language %d"), i);
+						SendDlgItemMessage(hDlg, 1001, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)text));
+					}
 				}
+				SendDlgItemMessage(hDlg, 1001, CB_SETCURSEL, getLanguageForFileB(), 0);
+			} else {
+				const WCHAR *text = TEXT("No translations available");
+				SendDlgItemMessage(hDlg, 1001, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)text));
+				SendDlgItemMessage(hDlg, 1001, CB_SETCURSEL, 0, 0);
+				EnableWindow(GetDlgItem(hDlg, 1001), false);
 			}
-			SendDlgItemMessage(hDlg, 1001, CB_SETCURSEL, getLanguageForFileB(), 0);
-		} else {
-			const WCHAR *text = TEXT("No translations available");
-			SendDlgItemMessage(hDlg, 1001, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)text));
-			SendDlgItemMessage(hDlg, 1001, CB_SETCURSEL, 0, 0);
-			EnableWindow(GetDlgItem(hDlg, 1001), false);
-		}
-		return true;
-
-	case WM_COMMAND:
-		if (hLogo) DeleteObject(hLogo);
-		switch (LOWORD(wParam)) {
-		case IDOK:
-
-			gameSettings.userFullScreen = (IsDlgButtonChecked(hDlg, 1000) == BST_CHECKED);
-			gameSettings.antiAlias = SendDlgItemMessage(hDlg, 1002, CB_GETCURSEL, 0, 0);
-			if (gameSettings.antiAlias == 0) gameSettings.antiAlias = 1;
-			else if (gameSettings.antiAlias == 1) gameSettings.antiAlias = -1;
-			else if (gameSettings.antiAlias == 2) gameSettings.antiAlias = 0;
+			return true;
+
+			case WM_COMMAND:
+			if (hLogo) DeleteObject(hLogo);
+			switch (LOWORD(wParam)) {
+				case IDOK:
+
+				gameSettings.userFullScreen = (IsDlgButtonChecked(hDlg, 1000) == BST_CHECKED);
+				gameSettings.antiAlias = SendDlgItemMessage(hDlg, 1002, CB_GETCURSEL, 0, 0);
+				if (gameSettings.antiAlias == 0) gameSettings.antiAlias = 1;
+				else if (gameSettings.antiAlias == 1) gameSettings.antiAlias = -1;
+				else if (gameSettings.antiAlias == 2) gameSettings.antiAlias = 0;
+
+				if (gameSettings.numLanguages) {
+					gameSettings.languageID = SendDlgItemMessage(hDlg, 1001, CB_GETCURSEL, 0, 0);
+					if (gameSettings.languageID < 0) gameSettings.languageID = 0;
+					gameSettings.languageID = languageTable[gameSettings.languageID];
+				}
+				EndDialog(hDlg, true);
+				return TRUE;
 
-			if (gameSettings.numLanguages) {
-				gameSettings.languageID = SendDlgItemMessage(hDlg, 1001, CB_GETCURSEL, 0, 0);
-				if (gameSettings.languageID < 0) gameSettings.languageID = 0;
-				gameSettings.languageID = languageTable[gameSettings.languageID];
+				case IDCANCEL:
+				EndDialog(hDlg, false);
+				return TRUE;
 			}
-			EndDialog(hDlg, true);
-			return TRUE;
-
-		case IDCANCEL:
-			EndDialog(hDlg, false);
-			return TRUE;
+			break;
 		}
-		break;
+		return false;
 	}
-	return false;
-}
 
-int showSetupWindow() {
+	int showSetupWindow() {
 
-	hInst = GetModuleHandle(NULL);
+		hInst = GetModuleHandle(NULL);
 
-	if (! hInst) debugOut("ERROR: No hInst!\n");
+		if (! hInst) debugOut("ERROR: No hInst!\n");
 
-	if (DialogBox(hInst, TEXT("SETUPWINDOW"), NULL, setupDlgProc)) return true;
-	return false;
+		if (DialogBox(hInst, TEXT("SETUPWINDOW"), NULL, setupDlgProc)) return true;
+		return false;
 
-}
+	}
 
-void msgBox(const char *head, const char *msg) {
-	WCHAR *w_head = ConvertToUTF16(head);
-	WCHAR *w_msg = ConvertToUTF16(msg);
-	MessageBox(NULL, w_msg, w_head, MB_OK | MB_ICONSTOP | MB_SYSTEMMODAL | MB_SETFOREGROUND);
-	delete w_head;
-	delete w_msg;
-}
+	void msgBox(const char *head, const char *msg) {
+		WCHAR *w_head = ConvertToUTF16(head);
+		WCHAR *w_msg = ConvertToUTF16(msg);
+		MessageBox(NULL, w_msg, w_head, MB_OK | MB_ICONSTOP | MB_SYSTEMMODAL | MB_SETFOREGROUND);
+		delete w_head;
+		delete w_msg;
+	}
 
-int msgBoxQuestion(const char *head, const char *msg) {
-	WCHAR *w_head = ConvertToUTF16(head);
-	WCHAR *w_msg = ConvertToUTF16(msg);
-	int val = MessageBox(NULL, w_msg, w_head, MB_YESNO | MB_SETFOREGROUND | MB_APPLMODAL | MB_ICONQUESTION) == IDNO;
-	delete w_head;
-	delete w_msg;
-	if (val)
+	int msgBoxQuestion(const char *head, const char *msg) {
+		WCHAR *w_head = ConvertToUTF16(head);
+		WCHAR *w_msg = ConvertToUTF16(msg);
+		int val = MessageBox(NULL, w_msg, w_head, MB_YESNO | MB_SETFOREGROUND | MB_APPLMODAL | MB_ICONQUESTION) == IDNO;
+		delete w_head;
+		delete w_msg;
+		if (val)
 		return false;
-	return true;
-}
-
-void changeToUserDir() {
-	TCHAR szAppData[MAX_PATH];
-	/*hr = */SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, szAppData);
-	_wchdir(szAppData);
-}
-
-uint32_t launch(char *f) {
-	WCHAR *w_f = ConvertToUTF16(f);
-	uint32_t r = (uint32_t) ShellExecute(hMainWindow, TEXT("open"), w_f, NULL, TEXT("C:\\"), SW_SHOWNORMAL);
-	delete w_f;
-	return r;
-}
-
-bool defaultUserFullScreen() {
-	return true;
-}
+		return true;
+	}
+
+	void changeToUserDir() {
+		TCHAR szAppData[MAX_PATH];
+		/*hr = */SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, szAppData);
+		_wchdir(szAppData);
+	}
+
+	uint32_t launch(char *f) {
+		WCHAR *w_f = ConvertToUTF16(f);
+		uint32_t r = (uint32_t) ShellExecute(hMainWindow, TEXT("open"), w_f, NULL, TEXT("C:\\"), SW_SHOWNORMAL);
+		delete w_f;
+		return r;
+	}
+
+	bool defaultUserFullScreen() {
+		return true;
+	}
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/zbuffer.cpp b/engines/sludge/zbuffer.cpp
index f73f4f6..fe13a98 100644
--- a/engines/sludge/zbuffer.cpp
+++ b/engines/sludge/zbuffer.cpp
@@ -47,13 +47,14 @@ void killZBuffer() {
 void sortZPal(int *oldpal, int *newpal, int size) {
 	int i, tmp;
 
-	for (i = 0; i < size; i ++) {
+	for (i = 0; i < size; i++) {
 		newpal[i] = i;
 	}
 
-	if (size < 2) return;
+	if (size < 2)
+		return;
 
-	for (i = 1; i < size; i ++) {
+	for (i = 1; i < size; i++) {
 		if (oldpal[newpal[i]] < oldpal[newpal[i - 1]]) {
 			tmp = newpal[i];
 			newpal[i] = newpal[i - 1];
@@ -80,17 +81,17 @@ bool setZBuffer(int y) {
 	if (fgetc(bigDataFile) != 'b') return fatal("Not a Z-buffer file");
 
 	switch (fgetc(bigDataFile)) {
-	case 0:
+		case 0:
 		zBuffer.width = 640;
 		zBuffer.height = 480;
 		break;
 
-	case 1:
+		case 1:
 		zBuffer.width = get2bytes(bigDataFile);
 		zBuffer.height = get2bytes(bigDataFile);
 		break;
 
-	default:
+		default:
 		return fatal("Extended Z-buffer format not supported in this version of the SLUDGE engine");
 	}
 	if (zBuffer.width != sceneWidth || zBuffer.height != sceneHeight) {
diff --git a/engines/sludge/zbuffer.h b/engines/sludge/zbuffer.h
index 6fdbd02..46510ec 100644
--- a/engines/sludge/zbuffer.h
+++ b/engines/sludge/zbuffer.h
@@ -44,7 +44,6 @@ struct zBufferData {
 #endif
 };
 
-
 bool setZBuffer(int y);
 void killZBuffer();
 void drawZBuffer(int x, int y, bool upsidedown);


Commit: 6e5dec313788be6ac3083e9d3ca30a9b66243894
    https://github.com/scummvm/scummvm/commit/6e5dec313788be6ac3083e9d3ca30a9b66243894
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Fix png displaying

Changed paths:
    engines/sludge/backdrop.cpp
    engines/sludge/main_loop.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index 7fecf57..ff24e1b 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -58,6 +58,7 @@
 #include "common/debug.h"
 #include "image/png.h"
 #include "graphics/surface.h"
+#include "graphics/palette.h"
 #include "sludge.h"
 
 namespace Sludge {
@@ -81,6 +82,7 @@ GLuint snapshotTextureName = 0;
 
 Graphics::Surface backdropSurface;
 
+
 float snapTexW = 1.0;
 float snapTexH = 1.0;
 
@@ -1017,6 +1019,8 @@ bool loadPng(int &picWidth, int &picHeight, int &realPicWidth,
 		return false;
 	}
 	backdropSurface.copyFrom(*(png.getSurface()));
+	const byte *palette = png.getPalette();
+	g_system->getPaletteManager()->setPalette(palette, 0, 256);
 	picWidth = realPicWidth = backdropSurface.w;
 	picHeight = realPicHeight = backdropSurface.h;
 	return true;
@@ -1137,11 +1141,12 @@ bool loadByteArray(int &picWidth, int &picHeight, int &realPicWidth,
 bool loadImage(int &picWidth, int &picHeight, int &realPicWidth,
 		int &realPicHeight, Common::SeekableReadStream *stream, int x, int y,
 		bool reserve) {
-	debug(kSludgeDebugGraphics, "Loading back drop image.");
+	debug(kSludgeDebugGraphics, "Loading back drop image at file position: %i", stream->pos());
 	if (!loadPng(picWidth, picHeight, realPicWidth, realPicHeight, stream,
 			reserve)) {
 		if (!loadByteArray(picWidth, picHeight, realPicWidth, realPicHeight,
 				stream, reserve)) {
+			debug(kSludgeDebugGraphics, "Back drop loading failed");
 			return false;
 		}
 	}
@@ -1151,9 +1156,10 @@ bool loadImage(int &picWidth, int &picHeight, int &realPicWidth,
 	if (y == IN_THE_CENTRE)
 		y = (sceneHeight - realPicHeight) >> 1;
 	if (x < 0 || x + realPicWidth > sceneWidth || y < 0
-			|| y + realPicHeight > sceneHeight)
+			|| y + realPicHeight > sceneHeight) {
+		debug(kSludgeDebugGraphics, "Illegal back drop size");
 		return false;
-
+	}
 	return true;
 }
 
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index 8496a9b..5e9a0f1 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -74,6 +74,7 @@
 #include "graphics.h"
 #include "helpers.h"
 #include "graphics/surface.h"
+#include "common/debug.h"
 
 namespace Sludge {
 
@@ -480,7 +481,9 @@ int main_loop(char *filename)
 		g_system->copyRectToScreen(backdropSurface.getPixels(),
 				backdropSurface.pitch, 0, 0, backdropSurface.w,
 				backdropSurface.h);
+		//g_system->getPaletteManager()->setPalette(_image->getPalette(), 0, 256);
 		g_system->updateScreen();
+		g_system->delayMillis(100);
 #if 0
 		Wait_Frame();
 #endif


Commit: c0822cbc8df88877f90ea1f807e14acea9f2e840
    https://github.com/scummvm/scummvm/commit/c0822cbc8df88877f90ea1f807e14acea9f2e840
Author: Tobia Tesan (tobia.tesan at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Fix configure.engine

It doesn't work with create_project.exe otherwise

Changed paths:
    engines/sludge/configure.engine


diff --git a/engines/sludge/configure.engine b/engines/sludge/configure.engine
index 24ae50d..7101729 100644
--- a/engines/sludge/configure.engine
+++ b/engines/sludge/configure.engine
@@ -1,3 +1,3 @@
 # This file is included from the main "configure" script
 # add_engine [name] [desc] [build-by-default] [subengines] [base games] [deps]
-add_engine sludge "Sludge" yes
\ No newline at end of file
+add_engine sludge "Sludge" yes "" "" "png"


Commit: 3ae270f70975f52f7a502145b9dbd78062bf70e1
    https://github.com/scummvm/scummvm/commit/3ae270f70975f52f7a502145b9dbd78062bf70e1
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Correct ifdef position in backdrop.h

Changed paths:
    engines/sludge/backdrop.h


diff --git a/engines/sludge/backdrop.h b/engines/sludge/backdrop.h
index 8346a46..9b0832a 100644
--- a/engines/sludge/backdrop.h
+++ b/engines/sludge/backdrop.h
@@ -97,6 +97,7 @@ void nosnapshot();
 bool snapshot();
 void saveSnapshot(Common::WriteStream *stream);
 bool restoreSnapshot(Common::SeekableReadStream *stream);
-#endif
 
 } // End of namespace Sludge
+
+#endif


Commit: b920f61a111b2dddac41b44a318c9078dea833ff
    https://github.com/scummvm/scummvm/commit/b920f61a111b2dddac41b44a318c9078dea833ff
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Add the slusge specific image decoder

Changed paths:
  A engines/sludge/bytearray.cpp
  A engines/sludge/bytearray.h
    engines/sludge/backdrop.cpp
    engines/sludge/main_loop.cpp
    engines/sludge/module.mk
    engines/sludge/sludge.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index ff24e1b..da71289 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -60,6 +60,7 @@
 #include "graphics/surface.h"
 #include "graphics/palette.h"
 #include "sludge.h"
+#include "bytearray.h"
 
 namespace Sludge {
 
@@ -82,7 +83,6 @@ GLuint snapshotTextureName = 0;
 
 Graphics::Surface backdropSurface;
 
-
 float snapTexW = 1.0;
 float snapTexH = 1.0;
 
@@ -1010,17 +1010,18 @@ bool loadParallax(unsigned short v, unsigned short fracX,
 
 extern int viewportOffsetX, viewportOffsetY;
 
-bool loadPng(int &picWidth, int &picHeight, int &realPicWidth,
-		int &realPicHeight, Common::SeekableReadStream *stream, bool reserve) {
-	debug(kSludgeDebugGraphics, "Loading back drop png.");
+bool loadPng(int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, bool reserve) {
+	debug(kSludgeDebugGraphics, "Loading back drop png at file position: %i", stream->pos());
 	::Image::PNGDecoder png;
 	if (!png.loadStream(*stream)) {
 		debug(kSludgeDebugGraphics, "Back drop is not a png");
 		return false;
 	}
-	backdropSurface.copyFrom(*(png.getSurface()));
-	const byte *palette = png.getPalette();
-	g_system->getPaletteManager()->setPalette(palette, 0, 256);
+	const Graphics::Surface *sourceSurface = png.getSurface();
+	Graphics::Surface *pngSurface = sourceSurface->convertTo(Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0), png.getPalette());
+	backdropSurface.copyFrom(*pngSurface);
+	pngSurface->free();
+	delete pngSurface;
 	picWidth = realPicWidth = backdropSurface.w;
 	picHeight = realPicHeight = backdropSurface.h;
 	return true;
@@ -1095,8 +1096,17 @@ bool loadPng(int &picWidth, int &picHeight, int &realPicWidth,
 #endif
 }
 
-bool loadByteArray(int &picWidth, int &picHeight, int &realPicWidth,
-		int &realPicHeight, Common::SeekableReadStream *stream, bool reserve) {
+bool loadByteArray(int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, bool reserve) {
+	debug(kSludgeDebugGraphics, "Loading back drop as a byte array at file position: %i", stream->pos());
+	ByteArrayDecoder byteDecoder;
+	if (!byteDecoder.loadStream(*stream)) {
+		debug(kSludgeDebugGraphics, "Back drop is not a byte array");
+		return false;
+	}
+	backdropSurface.copyFrom(*(byteDecoder.getSurface()));
+	picWidth = realPicWidth = backdropSurface.w;
+	picHeight = realPicHeight = backdropSurface.h;
+	return true;
 #if 0
 	int32_t transCol = reserve ? -1 : 63519;
 	int t1, t2, n;
@@ -1138,14 +1148,12 @@ bool loadByteArray(int &picWidth, int &picHeight, int &realPicWidth,
 #endif
 }
 
-bool loadImage(int &picWidth, int &picHeight, int &realPicWidth,
-		int &realPicHeight, Common::SeekableReadStream *stream, int x, int y,
-		bool reserve) {
+bool loadImage(int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 	debug(kSludgeDebugGraphics, "Loading back drop image at file position: %i", stream->pos());
-	if (!loadPng(picWidth, picHeight, realPicWidth, realPicHeight, stream,
-			reserve)) {
-		if (!loadByteArray(picWidth, picHeight, realPicWidth, realPicHeight,
-				stream, reserve)) {
+	int32 start_ptr = stream->pos();
+	if (!loadPng(picWidth, picHeight, realPicWidth, realPicHeight, stream, reserve)) {
+		stream->seek(start_ptr);
+		if (!loadByteArray(picWidth, picHeight, realPicWidth, realPicHeight, stream, reserve)) {
 			debug(kSludgeDebugGraphics, "Back drop loading failed");
 			return false;
 		}
diff --git a/engines/sludge/bytearray.cpp b/engines/sludge/bytearray.cpp
new file mode 100644
index 0000000..0b28a02
--- /dev/null
+++ b/engines/sludge/bytearray.cpp
@@ -0,0 +1,90 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#include "common/stream.h"
+#include "common/debug.h"
+#include "graphics/surface.h"
+
+#include "allfiles.h"
+#include "bytearray.h"
+#include "colours.h"
+#include "sludge.h"
+
+namespace Sludge {
+
+ByteArrayDecoder::ByteArrayDecoder() : _surface(nullptr) {
+}
+
+ByteArrayDecoder::~ByteArrayDecoder() {
+	destroy();
+}
+
+void ByteArrayDecoder::destroy() {
+	if (_surface != nullptr) {
+		_surface->free();
+		delete _surface;
+		_surface = nullptr;
+	}
+}
+
+bool ByteArrayDecoder::loadStream(Common::SeekableReadStream &stream) {
+	destroy();
+	int32_t transCol = /*reserve ? -1 : */63519;
+	int n;
+	uint16 width = stream.readUint16BE();
+	debug(kSludgeDebugGraphics, "picWidth : %i", width);
+	uint16 height = stream.readUint16BE();
+	debug(kSludgeDebugGraphics, "picHeight : %i", height);
+
+	_surface = new Graphics::Surface();
+	_surface->create(width, height, Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0));
+	for (uint16 y = 0; y < height; y++) {
+		uint16 x = 0;
+		while (x < width) {
+			unsigned short c = (unsigned short)stream.readUint16BE();
+			if (c & 32) {
+				n = stream.readByte() + 1;
+				c -= 32;
+			} else {
+				n = 1;
+			}
+			while (n--) {
+				byte *target = (byte *)_surface->getBasePtr(x, y);
+				if (c == transCol || c == 2015) {
+					target[0] = (byte)0;
+					target[1] = (byte)0;
+					target[2] = (byte)0;
+					target[3] = (byte)0;
+				} else {
+					target[0] = (byte)255;
+					target[1] = (byte)blueValue(c);
+					target[2] = (byte)greenValue(c);
+					target[3] = (byte)redValue(c);
+				}
+				x++;
+			}
+		}
+	}
+	return true;
+}
+
+} // End of namespace Sludge
diff --git a/engines/sludge/bytearray.h b/engines/sludge/bytearray.h
new file mode 100644
index 0000000..22bcc76
--- /dev/null
+++ b/engines/sludge/bytearray.h
@@ -0,0 +1,48 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef PRINCE_MHWANH_H
+#define PRINCE_MHWANH_H
+
+#include "image/image_decoder.h"
+#include "graphics/surface.h"
+
+namespace Sludge {
+
+class ByteArrayDecoder : public Image::ImageDecoder {
+
+public:
+	ByteArrayDecoder();
+	virtual ~ByteArrayDecoder();
+
+	// ImageDecoder API
+	void destroy();
+	virtual bool loadStream(Common::SeekableReadStream &stream);
+	virtual Graphics::Surface *getSurface() const { return _surface; }
+
+private:
+	Graphics::Surface *_surface;
+};
+
+} // End of namespace Sludge
+
+#endif
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index 5e9a0f1..cf0c7f3 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -75,6 +75,7 @@
 #include "helpers.h"
 #include "graphics/surface.h"
 #include "common/debug.h"
+#include "sludge.h"
 
 namespace Sludge {
 
@@ -481,7 +482,6 @@ int main_loop(char *filename)
 		g_system->copyRectToScreen(backdropSurface.getPixels(),
 				backdropSurface.pitch, 0, 0, backdropSurface.w,
 				backdropSurface.h);
-		//g_system->getPaletteManager()->setPalette(_image->getPalette(), 0, 256);
 		g_system->updateScreen();
 		g_system->delayMillis(100);
 #if 0
diff --git a/engines/sludge/module.mk b/engines/sludge/module.mk
index bad7f35..5e62f5a 100644
--- a/engines/sludge/module.mk
+++ b/engines/sludge/module.mk
@@ -4,6 +4,7 @@ MODULE_OBJS := \
 	backdrop.o \
 	bg_effects.o \
 	builtin.o \
+	bytearray.o \
 	console.o \
 	cursors.o \
 	debug.o \
diff --git a/engines/sludge/sludge.cpp b/engines/sludge/sludge.cpp
index ea9dc57..86c4980 100644
--- a/engines/sludge/sludge.cpp
+++ b/engines/sludge/sludge.cpp
@@ -64,7 +64,8 @@ SludgeEngine::~SludgeEngine() {
  
 Common::Error SludgeEngine::run() {
 	// init graphics
-	initGraphics(640, 480, false);
+	Graphics::PixelFormat format = Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0);
+	initGraphics(640, 480, false, &format);
 
 	// create console
 	_console = new SludgeConsole(this);


Commit: 8c59f8deac6da7fd3b46234b70ca1cea428ca1f5
    https://github.com/scummvm/scummvm/commit/8c59f8deac6da7fd3b46234b70ca1cea428ca1f5
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Replace sludge stream reading functions by scummvm ones

Changed paths:
    engines/sludge/backdrop.cpp
    engines/sludge/bg_effects.cpp
    engines/sludge/fileset.cpp
    engines/sludge/floor.cpp
    engines/sludge/language.cpp
    engines/sludge/loadsave.cpp
    engines/sludge/moreio.cpp
    engines/sludge/moreio.h
    engines/sludge/objtypes.cpp
    engines/sludge/people.cpp
    engines/sludge/region.cpp
    engines/sludge/savedata.cpp
    engines/sludge/sludger.cpp
    engines/sludge/sound_bass.cpp
    engines/sludge/sound_nosound.cpp
    engines/sludge/sound_openal.cpp
    engines/sludge/sprites.cpp
    engines/sludge/statusba.cpp
    engines/sludge/talk.cpp
    engines/sludge/thumbnail.cpp
    engines/sludge/zbuffer.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index da71289..07f4d35 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -107,10 +107,10 @@ void nosnapshot() {
 void saveSnapshot(Common::WriteStream *stream) {
 #if 0
 	if (snapshotTextureName) {
-		putch(1, stream);               // 1 for snapshot follows
+		stream->writeByte(1);               // 1 for snapshot follows
 		saveCoreHSI(stream, snapshotTextureName, winWidth, winHeight);
 	} else {
-		putch(0, stream);
+		stream->writeByte(0);
 	}
 #endif
 }
@@ -167,8 +167,8 @@ bool snapshot() {
 }
 
 bool restoreSnapshot(Common::SeekableReadStream *stream) {
-	unsigned int picWidth = get2bytes(stream);
-	unsigned int picHeight = get2bytes(stream);
+	unsigned int picWidth = stream->readUint16BE();
+	unsigned int picHeight = stream->readUint16BE();
 
 	if ((picWidth != winWidth) || (picHeight != winHeight))
 		return false;
@@ -190,9 +190,9 @@ bool restoreSnapshot(Common::SeekableReadStream *stream) {
 	for (t2 = 0; t2 < winHeight; t2++) {
 		t1 = 0;
 		while (t1 < winWidth) {
-			c = (unsigned short) get2bytes(stream);
+			c = (unsigned short)stream->readUint16BE();
 			if (c & 32) {
-				n = getch(stream) + 1;
+				n = stream->readByte() + 1;
 				c -= 32;
 			} else {
 				n = 1;
@@ -653,8 +653,8 @@ bool loadLightMap(int v) {
 		fileIsPNG = false;
 		fseek(bigDataFile, file_pointer, SEEK_SET);
 
-		newPicWidth = lightMap.w = get2bytes(bigDataFile);
-		newPicHeight = lightMap.h = get2bytes(bigDataFile);
+		newPicWidth = lightMap.w = bigDataFile->readUint16BE();
+		newPicHeight = lightMap.h = bigDataFile->readUint16BE();
 	} else {
 		// Read the PNG header
 
@@ -745,7 +745,7 @@ bool loadLightMap(int v) {
 		for (t2 = 0; t2 < lightMap.h; t2 ++) {
 			t1 = 0;
 			while (t1 < lightMap.w) {
-				c = (unsigned short) get2bytes(bigDataFile);
+				c = (unsigned short)bigDataFile->readUint16BE();
 				if (c & 32) {
 					n = fgetc(bigDataFile) + 1;
 					c -= 32;
@@ -859,8 +859,8 @@ bool loadParallax(unsigned short v, unsigned short fracX,
 		fileIsPNG = false;
 		fseek(bigDataFile, file_pointer, SEEK_SET);
 
-		picWidth = nP->width = get2bytes(bigDataFile);
-		picHeight = nP->height = get2bytes(bigDataFile);
+		picWidth = nP->width = bigDataFile->readUint16BE();
+		picHeight = nP->height = bigDataFile->readUint16BE();
 	} else {
 		// Read the PNG header
 
@@ -955,7 +955,7 @@ bool loadParallax(unsigned short v, unsigned short fracX,
 		for (t2 = 0; t2 < nP->height; t2 ++) {
 			t1 = 0;
 			while (t1 < nP->width) {
-				c = (unsigned short) get2bytes(bigDataFile);
+				c = (unsigned short)bigDataFile->readUint16BE();
 				if (c & 32) {
 					n = fgetc(bigDataFile) + 1;
 					c -= 32;
@@ -1111,8 +1111,8 @@ bool loadByteArray(int &picWidth, int &picHeight, int &realPicWidth, int &realPi
 	int32_t transCol = reserve ? -1 : 63519;
 	int t1, t2, n;
 	unsigned short c;
-	picWidth = realPicWidth = get2bytes(stream);
-	picHeight = realPicHeight = get2bytes(stream);
+	picWidth = realPicWidth = stream->readUint16BE();
+	picHeight = realPicHeight = stream->readUint16BE();
 
 	if (reserve) {
 		if (!resizeBackdrop(realPicWidth, realPicHeight)) return false;
@@ -1121,9 +1121,9 @@ bool loadByteArray(int &picWidth, int &picHeight, int &realPicWidth, int &realPi
 	for (t2 = 0; t2 < realPicHeight; t2 ++) {
 		t1 = 0;
 		while (t1 < realPicWidth) {
-			c = (unsigned short) get2bytes(stream);
+			c = (unsigned short)stream->readUint16BE();
 			if (c & 32) {
-				n = getch(stream) + 1;
+				n = stream->readByte() + 1;
 				c -= 32;
 			} else {
 				n = 1;
@@ -1337,8 +1337,8 @@ bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 		fileIsPNG = false;
 		stream->seek(file_pointer, SEEK_SET);
 
-		picWidth = realPicWidth = get2bytes(stream);
-		picHeight = realPicHeight = get2bytes(stream);
+		picWidth = realPicWidth = stream->readUint16BE();
+		picHeight = realPicHeight = stream->readUint16BE();
 	} else {
 		// Read the PNG header
 
@@ -1446,9 +1446,9 @@ bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 		for (t2 = 0; t2 < realPicHeight; t2 ++) {
 			t1 = 0;
 			while (t1 < realPicWidth) {
-				c = (unsigned short) get2bytes(stream);
+				c = (unsigned short)stream->readUint16BE();
 				if (c & 32) {
-					n = getch(stream) + 1;
+					n = stream->readByte() + 1;
 					c -= 32;
 				} else {
 					n = 1;
@@ -1701,8 +1701,8 @@ void saveCoreHSI(Common::WriteStream *stream, GLuint texture, int w, int h) {
 	int x, y, lookAhead;
 	unsigned short int *fromHere, * lookPointer;
 
-	put2bytes(w, stream);
-	put2bytes(h, stream);
+	stream->writeUint16BE(w);
+	stream->writeUint16BE(h);
 
 	for (y = 0; y < h; y ++) {
 		fromHere = image + (y * tw);
@@ -1717,8 +1717,8 @@ void saveCoreHSI(Common::WriteStream *stream, GLuint texture, int w, int h) {
 			if (lookAhead == x + 1) {
 				put2bytes((* fromHere) & 65503, stream);
 			} else {
-				put2bytes(* fromHere | 32, stream);
-				putch(lookAhead - x - 1, stream);
+				stream->writeUint16BE(* fromHere | 32);
+				stream->writeByte(lookAhead - x - 1);
 			}
 			fromHere = lookPointer;
 			x = lookAhead;
@@ -1738,10 +1738,10 @@ void saveHSI(Common::WriteStream *stream) {
 void saveParallaxRecursive(parallaxLayer *me, Common::WriteStream *stream) {
 	if (me) {
 		saveParallaxRecursive(me->next, stream);
-		putch(1, stream);
-		put2bytes(me->fileNum, stream);
-		put2bytes(me->fractionX, stream);
-		put2bytes(me->fractionY, stream);
+		stream->writeByte(1);
+		stream->writeUint16BE(me->fileNum);
+		stream->writeUint16BE(me->fractionX);
+		stream->writeUint16BE(me->fractionY);
 	}
 }
 
diff --git a/engines/sludge/bg_effects.cpp b/engines/sludge/bg_effects.cpp
index 8a61551..9c8bcb3 100644
--- a/engines/sludge/bg_effects.cpp
+++ b/engines/sludge/bg_effects.cpp
@@ -118,16 +118,16 @@ static int s_matrixEffectBase = 0;
 
 void blur_saveSettings(Common::WriteStream *stream) {
 	if (s_matrixEffectData) {
-		put4bytes(s_matrixEffectDivide, stream);
-		put4bytes(s_matrixEffectWidth, stream);
-		put4bytes(s_matrixEffectHeight, stream);
-		put4bytes(s_matrixEffectBase, stream);
+		stream->writeUint32LE(s_matrixEffectDivide);
+		stream->writeUint32LE(s_matrixEffectWidth);
+		stream->writeUint32LE(s_matrixEffectHeight);
+		stream->writeUint32LE(s_matrixEffectBase);
 		stream->write(s_matrixEffectData, sizeof(int) * s_matrixEffectWidth * s_matrixEffectHeight);
 	} else {
-		put4bytes(0, stream);
-		put4bytes(0, stream);
-		put4bytes(0, stream);
-		put4bytes(0, stream);
+		stream->writeUint32LE(0);
+		stream->writeUint32LE(0);
+		stream->writeUint32LE(0);
+		stream->writeUint32LE(0);
 	}
 }
 
@@ -143,10 +143,10 @@ static int *blur_allocateMemoryForEffect() {
 }
 
 void blur_loadSettings(Common::SeekableReadStream *stream) {
-	s_matrixEffectDivide = get4bytes(stream);
-	s_matrixEffectWidth = get4bytes(stream);
-	s_matrixEffectHeight = get4bytes(stream);
-	s_matrixEffectBase = get4bytes(stream);
+	s_matrixEffectDivide = stream->readUint32LE();
+	s_matrixEffectWidth = stream->readUint32LE();
+	s_matrixEffectHeight = stream->readUint32LE();
+	s_matrixEffectBase = stream->readUint32LE();
 
 	if (blur_allocateMemoryForEffect()) {
 		size_t bytes_read = stream->read(s_matrixEffectData, sizeof(int) * s_matrixEffectWidth * s_matrixEffectHeight);
diff --git a/engines/sludge/fileset.cpp b/engines/sludge/fileset.cpp
index eb39166..d6ecdef 100644
--- a/engines/sludge/fileset.cpp
+++ b/engines/sludge/fileset.cpp
@@ -35,6 +35,8 @@
 #include "CommonCode/version.h"
 
 #include "common/file.h"
+#include "common/debug.h"
+#include "sludge.h"
 
 namespace Sludge {
 
@@ -56,7 +58,7 @@ bool openSubSlice(int num) {
 	}
 //	fprintf (dbug, "Going to position %li\n", startOfSubIndex + (num << 2));
 	bigDataFile->seek(startOfSubIndex + (num << 2), 0);
-	bigDataFile->seek(get4bytes(bigDataFile), 0);
+	bigDataFile->seek(bigDataFile->readUint32LE(), 0);
 //	fprintf (dbug, "Told to skip forward to %li\n", ftell (bigDataFile));
 //	fclose (dbug);
 
@@ -75,7 +77,7 @@ bool openObjectSlice(int num) {
 
 //	fprintf (dbug, "Going to position %li\n", startOfObjectIndex + (num << 2));
 	bigDataFile->seek(startOfObjectIndex + (num << 2), 0);
-	bigDataFile->seek(get4bytes(bigDataFile), 0);
+	bigDataFile->seek(bigDataFile->readUint32LE(), 0);
 //	fprintf (dbug, "Told to skip forward to %li\n", ftell (bigDataFile));
 //	fclose (dbug);
 	return sliceBusy = true;
@@ -92,12 +94,12 @@ unsigned int openFileFromNum(int num) {
 //	fprintf (dbug, "\nTrying to open file %i\n", num);
 //	fprintf (dbug, "Jumping to %li (for index) \n", startOfDataIndex + (num << 2));
 	bigDataFile->seek(startOfDataIndex + (num << 2), 0);
-	bigDataFile->seek(get4bytes(bigDataFile), 1);
+	bigDataFile->seek(bigDataFile->readUint32LE(), 1);
 //	fprintf (dbug, "Jumping to %li (for data) \n", ftell (bigDataFile));
 	sliceBusy = true;
 //	fclose (dbug);
 
-	return get4bytes(bigDataFile);
+	return bigDataFile->readUint32LE();
 }
 
 // Converts a string from Windows CP-1252 to UTF-8.
@@ -173,7 +175,7 @@ char *getNumberedString(int value) {
 	}
 
 	bigDataFile->seek((value << 2) + startOfTextIndex, 0);
-	value = get4bytes(bigDataFile);
+	value = bigDataFile->readUint32LE();
 	bigDataFile->seek(value, 0);
 
 	char *s = readString(bigDataFile);
@@ -218,26 +220,30 @@ void setFileIndices(Common::File *fp, int numLanguages,
 	// STRINGS
 	int skipAfter = numLanguages - skipBefore;
 	while (skipBefore) {
-		fp->seek(get4bytes(fp), SEEK_SET);
+		fp->seek(fp->readUint32LE(), SEEK_SET);
 		skipBefore--;
 	}
 	startOfTextIndex = fp->pos() + 4;
+	debug(kSludgeDebugDataLoad, "startOfTextIndex: %i", startOfTextIndex);
 
-	fp->seek(get4bytes(fp), SEEK_SET);
+	fp->seek(fp->readUint32LE(), SEEK_SET);
 
 	while (skipAfter) {
-		fp->seek(get4bytes(fp), SEEK_SET);
+		fp->seek(fp->readUint32LE(), SEEK_SET);
 		skipAfter--;
 	}
 
 	startOfSubIndex = fp->pos() + 4;
-	fp->seek(get4bytes(fp), SEEK_CUR);
+	fp->seek(fp->readUint32LE(), SEEK_CUR);
+	debug(kSludgeDebugDataLoad, "startOfSubIndex: %i", startOfTextIndex);
 
 	startOfObjectIndex = fp->pos() + 4;
-	fp->seek(get4bytes(fp), SEEK_CUR);
+	fp->seek(fp->readUint32LE(), SEEK_CUR);
+	debug(kSludgeDebugDataLoad, "startOfObjectIndex: %i", startOfTextIndex);
 
 	// Remember that the data section starts here
 	startOfDataIndex = fp->pos();
+	debug(kSludgeDebugDataLoad, "startOfDataIndex: %i", startOfTextIndex);
 }
 
 } // End of namespace Sludge
diff --git a/engines/sludge/floor.cpp b/engines/sludge/floor.cpp
index ec57387..cfb64d5 100644
--- a/engines/sludge/floor.cpp
+++ b/engines/sludge/floor.cpp
@@ -135,7 +135,7 @@ bool setFloor(int fileNum) {
 	// Find out how many polygons there are and reserve memory
 
 	currentFloor->originalNum = fileNum;
-	currentFloor->numPolygons = getch(bigDataFile);
+	currentFloor->numPolygons = bigDataFile->readByte();
 	currentFloor->polygon = new floorPolygon[currentFloor->numPolygons];
 	if (!checkNew(currentFloor->polygon))
 		return false;
@@ -146,7 +146,7 @@ bool setFloor(int fileNum) {
 
 		// Find out how many vertex IDs there are and reserve memory
 
-		currentFloor->polygon[i].numVertices = getch(bigDataFile);
+		currentFloor->polygon[i].numVertices = bigDataFile->readByte();
 		currentFloor->polygon[i].vertexID =
 				new int[currentFloor->polygon[i].numVertices];
 		if (!checkNew(currentFloor->polygon[i].vertexID))
@@ -155,21 +155,21 @@ bool setFloor(int fileNum) {
 		// Read in each vertex ID
 
 		for (j = 0; j < currentFloor->polygon[i].numVertices; j++) {
-			currentFloor->polygon[i].vertexID[j] = get2bytes(bigDataFile);
+			currentFloor->polygon[i].vertexID[j] = bigDataFile->readUint16BE();
 		}
 	}
 
 	// Find out how many vertices there are and reserve memory
 
-	i = get2bytes(bigDataFile);
+	i = bigDataFile->readUint16BE();
 	currentFloor->vertex = new POINT[i];
 	if (!checkNew(currentFloor->vertex))
 		return false;
 
 	for (j = 0; j < i; j++) {
 
-		currentFloor->vertex[j].x = get2bytes(bigDataFile);
-		currentFloor->vertex[j].y = get2bytes(bigDataFile);
+		currentFloor->vertex[j].x = bigDataFile->readUint16BE();
+		currentFloor->vertex[j].y = bigDataFile->readUint16BE();
 	}
 
 	finishAccess();
diff --git a/engines/sludge/language.cpp b/engines/sludge/language.cpp
index 6bbb6d3..b6a7ab6 100644
--- a/engines/sludge/language.cpp
+++ b/engines/sludge/language.cpp
@@ -115,7 +115,7 @@ void readIniFile(char *filename) {
 	bool doingSecond = false;
 
 	do {
-		readChar = getch(&fd);
+		readChar = fd.readByte();
 		if (fd.eos()) {
 			readChar = '\n';
 			keepGoing = false;
@@ -193,7 +193,7 @@ void makeLanguageTable(Common::File *table) {
 		return;
 
 	for (unsigned int i = 0; i <= gameSettings.numLanguages; i++) {
-		languageTable[i] = i ? get2bytes(table) : 0;
+		languageTable[i] = i ? table->readUint16BE() : 0;
 		debug(kSludgeDebugDataLoad, "languageTable %i: %i", i,
 				languageTable[i]);
 		languageName[i] = 0;
diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index 125e318..f3eb93f 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -105,7 +105,7 @@ void saveStack(variableStack *vs, Common::WriteStream *stream) {
 
 	stackDebug((stackfp, "  stack contains %d elements\n", elements));
 
-	put2bytes(elements, stream);
+	stream->writeUint16BE(elements);
 	search = vs;
 	for (a = 0; a < elements; ++a) {
 		saveVariable(&search->thisVar, stream);
@@ -115,7 +115,7 @@ void saveStack(variableStack *vs, Common::WriteStream *stream) {
 
 variableStack *loadStack(Common::SeekableReadStream *stream,
 		variableStack **last) {
-	int elements = get2bytes(stream);
+	int elements = stream->readUint16BE();
 	int a;
 	variableStack *first = NULL;
 	variableStack * * changeMe = &first;
@@ -142,14 +142,14 @@ bool saveStackRef(stackHandler *vs, Common::WriteStream *stream) {
 	int a = 0;
 	while (s) {
 		if (s->stack == vs) {
-			putch(1, stream);
-			put2bytes(stackLibTotal - a, stream);
+			stream->writeByte(1);
+			stream->writeUint16BE(stackLibTotal - a);
 			return true;
 		}
 		s = s->next;
 		++a;
 	}
-	putch(0, stream);
+	stream->writeByte(0);
 	saveStack(vs->first, stream);
 	s = new stackLibrary;
 	stackLibTotal++;
@@ -183,10 +183,10 @@ stackHandler *getStackFromLibrary(int n) {
 stackHandler *loadStackRef(Common::SeekableReadStream *stream) {
 	stackHandler *nsh;
 
-	if (getch(stream)) {    // It's one we've loaded already...
+	if (stream->readByte()) {    // It's one we've loaded already...
 		stackDebug((stackfp, "loadStackRef (duplicate, get from library)\n"));
 
-		nsh = getStackFromLibrary(get2bytes(stream));
+		nsh = getStackFromLibrary(stream->readUint16BE());
 		nsh->timesUsed++;
 	} else {
 		stackDebug((stackfp, "loadStackRef (new one)\n"));
@@ -231,14 +231,14 @@ bool saveVariable(variable *from, Common::WriteStream *stream) {
 	}
 #endif
 
-	putch(from->varType, stream);
+	stream->writeByte(from->varType);
 	switch (from->varType) {
 	case SVT_INT:
 	case SVT_FUNC:
 	case SVT_BUILT:
 	case SVT_FILE:
 	case SVT_OBJTYPE:
-		put4bytes(from->varData.intValue, stream);
+		stream->writeUint32LE(from->varData.intValue);
 		return true;
 
 	case SVT_STRING:
@@ -268,14 +268,14 @@ bool saveVariable(variable *from, Common::WriteStream *stream) {
 }
 
 bool loadVariable(variable *to, Common::SeekableReadStream *stream) {
-	to->varType = (variableType) getch(stream);
+	to->varType = (variableType)stream->readByte();
 	switch (to->varType) {
 	case SVT_INT:
 	case SVT_FUNC:
 	case SVT_BUILT:
 	case SVT_FILE:
 	case SVT_OBJTYPE:
-		to->varData.intValue = get4bytes(stream);
+		to->varData.intValue = stream->readUint32LE();
 		return true;
 
 	case SVT_STRING:
@@ -318,18 +318,18 @@ bool loadVariable(variable *to, Common::SeekableReadStream *stream) {
 //----------------------------------------------------------------------
 void saveFunction(loadedFunction *fun, Common::WriteStream *stream) {
 	int a;
-	put2bytes(fun->originalNumber, stream);
+	stream->writeUint16BE(fun->originalNumber);
 	if (fun->calledBy) {
-		putch(1, stream);
+		stream->writeByte(1);
 		saveFunction(fun->calledBy, stream);
 	} else {
-		putch(0, stream);
+		stream->writeByte(0);
 	}
-	put4bytes(fun->timeLeft, stream);
-	put2bytes(fun->runThisLine, stream);
-	putch(fun->cancelMe, stream);
-	putch(fun->returnSomething, stream);
-	putch(fun->isSpeech, stream);
+	stream->writeUint32LE(fun->timeLeft);
+	stream->writeUint16BE(fun->runThisLine);
+	stream->writeByte(fun->cancelMe);
+	stream->writeByte(fun->returnSomething);
+	stream->writeByte(fun->isSpeech);
 	saveVariable(&(fun->reg), stream);
 
 	if (fun->freezerLevel) {
@@ -352,20 +352,20 @@ loadedFunction *loadFunction(Common::SeekableReadStream *stream) {
 
 	// See what it was called by and load if we need to...
 
-	buildFunc->originalNumber = get2bytes(stream);
+	buildFunc->originalNumber = stream->readUint16BE();
 	buildFunc->calledBy = NULL;
-	if (getch(stream)) {
+	if (stream->readByte()) {
 		buildFunc->calledBy = loadFunction(stream);
 		if (!buildFunc->calledBy)
 			return NULL;
 	}
 
-	buildFunc->timeLeft = get4bytes(stream);
-	buildFunc->runThisLine = get2bytes(stream);
+	buildFunc->timeLeft = stream->readUint32LE();
+	buildFunc->runThisLine = stream->readUint16BE();
 	buildFunc->freezerLevel = 0;
-	buildFunc->cancelMe = getch(stream);
-	buildFunc->returnSomething = getch(stream);
-	buildFunc->isSpeech = getch(stream);
+	buildFunc->cancelMe = stream->readByte();
+	buildFunc->returnSomething = stream->readByte();
+	buildFunc->isSpeech = stream->readByte();
 	loadVariable(&(buildFunc->reg), stream);
 	loadFunctionCode(buildFunc);
 
@@ -407,15 +407,15 @@ bool saveGame(char *fname) {
 	fputc(fontTableSize > 0, fp);
 
 	if (fontTableSize > 0) {
-		put2bytes(loadedFontNum, fp);
-		put2bytes(fontHeight, fp);
+		fp->writeUint16BE(loadedFontNum);
+		fp->writeUint16BE(fontHeight);
 		writeString(fontOrderString, fp);
 	}
 	putSigned(fontSpace, fp);
 
 	// Save backdrop
-	put2bytes(cameraX, fp);
-	put2bytes(cameraY, fp);
+	fp->writeUint16BE(cameraX);
+	fp->writeUint16BE(cameraY);
 	putFloat(cameraZoom, fp);
 
 	fputc(brightnessLevel, fp);
@@ -428,7 +428,7 @@ bool saveGame(char *fname) {
 	saveRegions(fp);
 
 	saveAnim(mouseCursorAnim, fp);
-	put2bytes(mouseCursorFrameNum, fp);
+	fp->writeUint16BE(mouseCursorFrameNum);
 
 	// Save functions
 	loadedFunction *thisFunction = allRunningFunctions;
@@ -437,7 +437,7 @@ bool saveGame(char *fname) {
 		countFunctions ++;
 		thisFunction = thisFunction->next;
 	}
-	put2bytes(countFunctions, fp);
+	fp->writeUint16BE(countFunctions);
 
 	thisFunction = allRunningFunctions;
 	while (thisFunction) {
@@ -453,17 +453,17 @@ bool saveGame(char *fname) {
 
 	if (currentFloor->numPolygons) {
 		fputc(1, fp);
-		put2bytes(currentFloor->originalNum, fp);
+		fp->writeUint16BE(currentFloor->originalNum);
 	} else fputc(0, fp);
 
 	if (zBuffer.tex) {
 		fputc(1, fp);
-		put2bytes(zBuffer.originalNum, fp);
+		fp->writeUint16BE(zBuffer.originalNum);
 	} else fputc(0, fp);
 
 	if (lightMap.data) {
 		fputc(1, fp);
-		put2bytes(lightMapNumber, fp);
+		fp->writeUint16BE(lightMapNumber);
 	} else fputc(0, fp);
 
 	fputc(lightMapMode, fp);
@@ -473,11 +473,11 @@ bool saveGame(char *fname) {
 	saveStatusBars(fp);
 	saveSounds(fp);
 
-	put2bytes(saveEncoding, fp);
+	fp->writeUint16BE(saveEncoding);
 
 	blur_saveSettings(fp);
 
-	put2bytes(currentBlankColour, fp);
+	fp->writeUint16BE(currentBlankColour);
 	fputc(currentBurnR, fp);
 	fputc(currentBurnG, fp);
 	fputc(currentBurnB, fp);
@@ -538,8 +538,8 @@ bool loadGame(char *fname) {
 	int fontNum;
 	char *charOrder;
 	if (fontLoaded) {
-		fontNum = get2bytes(fp);
-		fontHeight = get2bytes(fp);
+		fontNum = fp->readUint16BE();
+		fontHeight = fp->readUint16BE();
 
 		if (ssgVersion < VERSION(2, 2)) {
 			int x;
@@ -563,8 +563,8 @@ bool loadGame(char *fname) {
 	killAllPeople();
 	killAllRegions();
 
-	int camerX = get2bytes(fp);
-	int camerY = get2bytes(fp);
+	int camerX = fp->readUint16BE();
+	int camerY = fp->readUint16BE();
 	float camerZ;
 	if (ssgVersion >= VERSION(2, 0)) {
 		camerZ = getFloat(fp);
@@ -581,12 +581,12 @@ bool loadGame(char *fname) {
 	mouseCursorAnim = new personaAnimation;
 	if (! checkNew(mouseCursorAnim)) return false;
 	if (! loadAnim(mouseCursorAnim, fp)) return false;
-	mouseCursorFrameNum = get2bytes(fp);
+	mouseCursorFrameNum = fp->readUint16BE();
 
 	loadedFunction *rFunc;
 	loadedFunction * * buildList = &allRunningFunctions;
 
-	int countFunctions = get2bytes(fp);
+	int countFunctions = fp->readUint16BE();
 	while (countFunctions --) {
 		rFunc = loadFunction(fp);
 		rFunc->next = NULL;
@@ -602,15 +602,15 @@ bool loadGame(char *fname) {
 	loadPeople(fp);
 
 	if (fgetc(fp)) {
-		if (! setFloor(get2bytes(fp))) return false;
+		if (! setFloor(fp->readUint16BE())) return false;
 	} else setFloorNull();
 
 	if (fgetc(fp)) {
-		if (! setZBuffer(get2bytes(fp))) return false;
+		if (! setZBuffer(fp->readUint16BE())) return false;
 	}
 
 	if (fgetc(fp)) {
-		if (! loadLightMap(get2bytes(fp))) return false;
+		if (! loadLightMap(fp->readUint16BE())) return false;
 	}
 
 	if (ssgVersion >= VERSION(1, 4)) {
@@ -623,7 +623,7 @@ bool loadGame(char *fname) {
 	loadStatusBars(fp);
 	loadSounds(fp);
 
-	saveEncoding = get2bytes(fp);
+	saveEncoding = fp->readUint16BE();
 
 	if (ssgVersion >= VERSION(1, 6)) {
 		if (ssgVersion < VERSION(2, 0)) {
@@ -637,16 +637,16 @@ bool loadGame(char *fname) {
 	}
 
 	if (ssgVersion >= VERSION(1, 3)) {
-		currentBlankColour = get2bytes(fp);
+		currentBlankColour = fp->readUint16BE();
 		currentBurnR = fgetc(fp);
 		currentBurnG = fgetc(fp);
 		currentBurnB = fgetc(fp);
 
 		// Read parallax layers
 		while (fgetc(fp)) {
-			int im = get2bytes(fp);
-			int fx = get2bytes(fp);
-			int fy = get2bytes(fp);
+			int im = fp->readUint16BE();
+			int fx = fp->readUint16BE();
+			int fy = fp->readUint16BE();
 
 			if (! loadParallax(im, fx, fy)) return false;
 		}
diff --git a/engines/sludge/moreio.cpp b/engines/sludge/moreio.cpp
index 754f22c..ed3a7ec 100644
--- a/engines/sludge/moreio.cpp
+++ b/engines/sludge/moreio.cpp
@@ -40,44 +40,22 @@ namespace Sludge {
 
 bool allowAnyFilename = true;
 
-int getch(Common::SeekableReadStream *stream) {
-	return stream->readByte();
-}
-
-void putch(int c, Common::WriteStream *stream) {
-	stream->writeByte(c);
-}
-
-int get2bytes(Common::SeekableReadStream *stream) {
-	int f1, f2;
-
-	f1 = getch(stream);
-	f2 = getch(stream);
-
-	return (f1 * 256 + f2);
-}
-
-void put2bytes(int numtoput, Common::WriteStream *stream) {
-	putch((char) (numtoput / 256), stream);
-	putch((char) (numtoput % 256), stream);
-}
-
 void writeString(char *s, Common::WriteStream *stream) {
 	int a, len = strlen(s);
-	put2bytes(len, stream);
+	stream->writeUint16BE(len);
 	for (a = 0; a < len; ++a) {
-		putch(s[a] + 1, stream);
+		stream->writeByte(s[a] + 1);
 	}
 }
 
 char *readString(Common::SeekableReadStream *stream) {
-	int a, len = get2bytes(stream);
+	int a, len = stream->readUint16BE();
 	char *s = new char[len + 1];
 	if (!checkNew(s)) {
 		return NULL;
 	}
 	for (a = 0; a < len; ++a) {
-		s[a] = (char) (getch(stream) - 1);
+		s[a] = (char)(stream->readByte() - 1);
 	}
 	s[len] = 0;
 	debug(kSludgeDebugDataLoad, "Read string of length %i: %s", len, s);
@@ -101,7 +79,6 @@ float floatSwap(float f) {
 float getFloat(Common::SeekableReadStream *stream) {
 	float f;
 	size_t bytes_read = stream->read(&f, sizeof(float));
-	//fread(& f, sizeof(float), 1, fp);
 	if (bytes_read != sizeof(float) && stream->err()) {
 		debug("Reading error in getFloat.\n");
 	}
@@ -118,7 +95,6 @@ void putFloat(float f, Common::WriteStream *stream) {
 	f = floatSwap(f);
 #endif
 	stream->write(&f, sizeof(float));
-	//fwrite(& f, sizeof(float), 1, fp);
 }
 
 short shortSwap(short s) {
@@ -149,38 +125,6 @@ void putSigned(short f, Common::WriteStream *stream) {
 	stream->write(&f, sizeof(short));
 }
 
-// The following two functions treat signed integers as unsigned.
-// That's done on purpose.
-
-int32_t get4bytes(Common::SeekableReadStream *stream) {
-	int f1, f2, f3, f4;
-
-	f1 = getch(stream);
-	f2 = getch(stream);
-	f3 = getch(stream);
-	f4 = getch(stream);
-
-	unsigned int x = f1 + f2 * 256 + f3 * 256 * 256 + f4 * 256 * 256 * 256;
-
-	return x;
-}
-
-void put4bytes(unsigned int i, Common::WriteStream *stream) {
-	unsigned char f1, f2, f3, f4;
-
-	f4 = i / (256 * 256 * 256);
-	i = i % (256 * 256 * 256);
-	f3 = i / (256 * 256);
-	i = i % (256 * 256);
-	f2 = i / 256;
-	f1 = i % 256;
-
-	putch(f1, stream);
-	putch(f2, stream);
-	putch(f3, stream);
-	putch(f4, stream);
-}
-
 char *encodeFilename(char *nameIn) {
 	if (!nameIn)
 		return NULL;
diff --git a/engines/sludge/moreio.h b/engines/sludge/moreio.h
index 9c2287b..1e2f314 100644
--- a/engines/sludge/moreio.h
+++ b/engines/sludge/moreio.h
@@ -27,20 +27,14 @@
 namespace Sludge {
 
 // Read
-int getch(Common::SeekableReadStream *stream);
-int get2bytes(Common::SeekableReadStream *stream);
 char *readString(Common::SeekableReadStream *stream);
 float getFloat(Common::SeekableReadStream *stream);
 short getSigned(Common::SeekableReadStream *stream);
-int32_t get4bytes(Common::SeekableReadStream *stream);
 
 // Write
-void putch(int c, Common::WriteStream *stream);
-void put2bytes(int numtoput, Common::WriteStream *stream);
 void writeString(char *s, Common::WriteStream *stream);
 void putFloat(float f, Common::WriteStream *stream);
 void putSigned(short f, Common::WriteStream *stream);
-void put4bytes(uint32_t f, Common::WriteStream *stream);
 
 char *encodeFilename(char *nameIn);
 char *decodeFilename(char *nameIn);
diff --git a/engines/sludge/objtypes.cpp b/engines/sludge/objtypes.cpp
index 5f82fb0..3c79374 100644
--- a/engines/sludge/objtypes.cpp
+++ b/engines/sludge/objtypes.cpp
@@ -56,29 +56,29 @@ objectType *loadObjectType(int i) {
 
 	if (checkNew(newType)) {
 		if (openObjectSlice(i)) {
-			nameNum = get2bytes(bigDataFile);
-			newType->r = (byte) getch(bigDataFile);
-			newType->g = (byte) getch(bigDataFile);
-			newType->b = (byte) getch(bigDataFile);
-			newType->speechGap = getch(bigDataFile);
-			newType->walkSpeed = getch(bigDataFile);
-			newType->wrapSpeech = get4bytes(bigDataFile);
-			newType->spinSpeed = get2bytes(bigDataFile);
+			nameNum = bigDataFile->readUint16BE();
+			newType->r = (byte)bigDataFile->readByte();
+			newType->g = (byte)bigDataFile->readByte();
+			newType->b = (byte)bigDataFile->readByte();
+			newType->speechGap = bigDataFile->readByte();
+			newType->walkSpeed = bigDataFile->readByte();
+			newType->wrapSpeech = bigDataFile->readUint32LE();
+			newType->spinSpeed = bigDataFile->readUint16BE();
 
 			if (gameVersion >= VERSION(1, 6)) {
 				// aaLoad
-				getch(bigDataFile);
+				bigDataFile->readByte();
 				getFloat(bigDataFile);
 				getFloat(bigDataFile);
 			}
 
 			if (gameVersion >= VERSION(1, 4)) {
-				newType->flags = get2bytes(bigDataFile);
+				newType->flags = bigDataFile->readUint16BE();
 			} else {
 				newType->flags = 0;
 			}
 
-			newType->numCom = get2bytes(bigDataFile);
+			newType->numCom = bigDataFile->readUint16BE();
 			newType->allCombis =
 					(newType->numCom) ? new combination[newType->numCom] : NULL;
 
@@ -90,8 +90,8 @@ objectType *loadObjectType(int i) {
 #endif
 
 			for (a = 0; a < newType->numCom; a++) {
-				newType->allCombis[a].withObj = get2bytes(bigDataFile);
-				newType->allCombis[a].funcNum = get2bytes(bigDataFile);
+				newType->allCombis[a].withObj = bigDataFile->readUint16BE();
+				newType->allCombis[a].funcNum = bigDataFile->readUint16BE();
 #if DEBUG_COMBINATIONS
 				if (callEventLog) {
 					fprintf(callEventLog, "%d(%d) ", newType -> allCombis[a].withObj, newType -> allCombis[a].funcNum);
@@ -117,14 +117,14 @@ objectType *loadObjectType(int i) {
 }
 
 objectType *loadObjectRef(Common::SeekableReadStream *stream) {
-	objectType *r = loadObjectType(get2bytes(stream));
+	objectType *r = loadObjectType(stream->readUint16BE());
 	delete r->screenName;
 	r->screenName = readString(stream);
 	return r;
 }
 
 void saveObjectRef(objectType *r, Common::WriteStream *stream) {
-	put2bytes(r->objectNum, stream);
+	stream->writeUint16BE(r->objectNum);
 	writeString(r->screenName, stream);
 }
 
diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index 93f1d6c..9b19bbf 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -1009,34 +1009,34 @@ void removeOneCharacter(int i) {
 }
 
 bool saveAnim(personaAnimation *p, Common::WriteStream *stream) {
-	put2bytes(p->numFrames, stream);
+	stream->writeUint16BE(p->numFrames);
 	if (p->numFrames) {
-		put4bytes(p->theSprites->ID, stream);
+		stream->writeUint32LE(p->theSprites->ID);
 
 		for (int a = 0; a < p->numFrames; ++a) {
-			put4bytes(p->frames[a].frameNum, stream);
-			put4bytes(p->frames[a].howMany, stream);
-			put4bytes(p->frames[a].noise, stream);
+			stream->writeUint32LE(p->frames[a].frameNum);
+			stream->writeUint32LE(p->frames[a].howMany);
+			stream->writeUint32LE(p->frames[a].noise);
 		}
 	}
 	return true;
 }
 
 bool loadAnim(personaAnimation *p, Common::SeekableReadStream *stream) {
-	p->numFrames = get2bytes(stream);
+	p->numFrames = stream->readUint16BE();
 
 	if (p->numFrames) {
-		int a = get4bytes(stream);
+		int a = stream->readUint32LE();
 		p->frames = new animFrame[p->numFrames];
 		if (!checkNew(p->frames))
 			return false;
 		p->theSprites = loadBankForAnim(a);
 
 		for (a = 0; a < p->numFrames; ++a) {
-			p->frames[a].frameNum = get4bytes(stream);
-			p->frames[a].howMany = get4bytes(stream);
+			p->frames[a].frameNum = stream->readUint32LE();
+			p->frames[a].howMany = stream->readUint32LE();
 			if (ssgVersion >= VERSION(2, 0)) {
-				p->frames[a].noise = get4bytes(stream);
+				p->frames[a].noise = stream->readUint32LE();
 			} else {
 				p->frames[a].noise = 0;
 			}
@@ -1064,7 +1064,7 @@ bool loadAnim(personaAnimation *p, Common::SeekableReadStream *stream) {
  */
 bool saveCostume(persona *cossy, Common::WriteStream *stream) {
 	int a;
-	put2bytes(cossy->numDirections, stream);
+	stream->writeUint16BE(cossy->numDirections);
 	for (a = 0; a < cossy->numDirections * 3; ++a) {
 		if (!saveAnim(cossy->animation[a], stream))
 			return false;
@@ -1075,7 +1075,7 @@ bool saveCostume(persona *cossy, Common::WriteStream *stream) {
 
 bool loadCostume(persona *cossy, Common::SeekableReadStream *stream) {
 	int a;
-	cossy->numDirections = get2bytes(stream);
+	cossy->numDirections = stream->readUint16BE();
 	cossy->animation = new personaAnimation *[cossy->numDirections * 3];
 	if (!checkNew(cossy->animation))
 		return false;
@@ -1103,7 +1103,7 @@ bool savePeople(Common::WriteStream *stream) {
 		me = me->next;
 	}
 
-	put2bytes(countPeople, stream);
+	stream->writeUint16BE(countPeople);
 
 	me = allPeople;
 	for (a = 0; a < countPeople; ++a) {
@@ -1113,43 +1113,43 @@ bool savePeople(Common::WriteStream *stream) {
 
 		saveCostume(me->myPersona, stream);
 		saveAnim(me->myAnim, stream);
-		putch(me->myAnim == me->lastUsedAnim, stream);
+		stream->writeByte(me->myAnim == me->lastUsedAnim);
 
 		putFloat(me->scale, stream);
 
-		put2bytes(me->extra, stream);
-		put2bytes(me->height, stream);
-		put2bytes(me->walkToX, stream);
-		put2bytes(me->walkToY, stream);
-		put2bytes(me->thisStepX, stream);
-		put2bytes(me->thisStepY, stream);
-		put2bytes(me->frameNum, stream);
-		put2bytes(me->frameTick, stream);
-		put2bytes(me->walkSpeed, stream);
-		put2bytes(me->spinSpeed, stream);
+		stream->writeUint16BE(me->extra);
+		stream->writeUint16BE(me->height);
+		stream->writeUint16BE(me->walkToX);
+		stream->writeUint16BE(me->walkToY);
+		stream->writeUint16BE(me->thisStepX);
+		stream->writeUint16BE(me->thisStepY);
+		stream->writeUint16BE(me->frameNum);
+		stream->writeUint16BE(me->frameTick);
+		stream->writeUint16BE(me->walkSpeed);
+		stream->writeUint16BE(me->spinSpeed);
 		putSigned(me->floaty, stream);
-		putch(me->show, stream);
-		putch(me->walking, stream);
-		putch(me->spinning, stream);
+		stream->writeByte(me->show);
+		stream->writeByte(me->walking);
+		stream->writeByte(me->spinning);
 		if (me->continueAfterWalking) {
-			putch(1, stream);
+			stream->writeByte(1);
 			saveFunction(me->continueAfterWalking, stream);
 		} else {
-			putch(0, stream);
+			stream->writeByte(0);
 		}
-		put2bytes(me->direction, stream);
-		put2bytes(me->angle, stream);
-		put2bytes(me->angleOffset, stream);
-		put2bytes(me->wantAngle, stream);
+		stream->writeUint16BE(me->direction);
+		stream->writeUint16BE(me->angle);
+		stream->writeUint16BE(me->angleOffset);
+		stream->writeUint16BE(me->wantAngle);
 		putSigned(me->directionWhenDoneWalking, stream);
 		putSigned(me->inPoly, stream);
 		putSigned(me->walkToPoly, stream);
 
-		putch(me->r, stream);
-		putch(me->g, stream);
-		putch(me->b, stream);
-		putch(me->colourmix, stream);
-		putch(me->transparency, stream);
+		stream->writeByte(me->r);
+		stream->writeByte(me->g);
+		stream->writeByte(me->b);
+		stream->writeByte(me->colourmix);
+		stream->writeByte(me->transparency);
 
 		saveObjectRef(me->thisType, stream);
 
@@ -1165,7 +1165,7 @@ bool loadPeople(Common::SeekableReadStream *stream) {
 	scaleHorizon = getSigned(stream);
 	scaleDivide = getSigned(stream);
 
-	int countPeople = get2bytes(stream);
+	int countPeople = stream->readUint16BE();
 	int a;
 
 	allPeople = NULL;
@@ -1188,50 +1188,50 @@ bool loadPeople(Common::SeekableReadStream *stream) {
 		loadCostume(me->myPersona, stream);
 		loadAnim(me->myAnim, stream);
 
-		me->lastUsedAnim = getch(stream) ? me->myAnim : NULL;
+		me->lastUsedAnim = stream->readByte() ? me->myAnim : NULL;
 
 		me->scale = getFloat(stream);
 
-		me->extra = get2bytes(stream);
-		me->height = get2bytes(stream);
-		me->walkToX = get2bytes(stream);
-		me->walkToY = get2bytes(stream);
-		me->thisStepX = get2bytes(stream);
-		me->thisStepY = get2bytes(stream);
-		me->frameNum = get2bytes(stream);
-		me->frameTick = get2bytes(stream);
-		me->walkSpeed = get2bytes(stream);
-		me->spinSpeed = get2bytes(stream);
+		me->extra = stream->readUint16BE();
+		me->height = stream->readUint16BE();
+		me->walkToX = stream->readUint16BE();
+		me->walkToY = stream->readUint16BE();
+		me->thisStepX = stream->readUint16BE();
+		me->thisStepY = stream->readUint16BE();
+		me->frameNum = stream->readUint16BE();
+		me->frameTick = stream->readUint16BE();
+		me->walkSpeed = stream->readUint16BE();
+		me->spinSpeed = stream->readUint16BE();
 		me->floaty = getSigned(stream);
-		me->show = getch(stream);
-		me->walking = getch(stream);
-		me->spinning = getch(stream);
-		if (getch(stream)) {
+		me->show = stream->readByte();
+		me->walking = stream->readByte();
+		me->spinning = stream->readByte();
+		if (stream->readByte()) {
 			me->continueAfterWalking = loadFunction(stream);
 			if (!me->continueAfterWalking)
 				return false;
 		} else {
 			me->continueAfterWalking = NULL;
 		}
-		me->direction = get2bytes(stream);
-		me->angle = get2bytes(stream);
+		me->direction = stream->readUint16BE();
+		me->angle = stream->readUint16BE();
 		if (ssgVersion >= VERSION(2, 0)) {
-			me->angleOffset = get2bytes(stream);
+			me->angleOffset = stream->readUint16BE();
 		} else {
 			me->angleOffset = 0;
 		}
-		me->wantAngle = get2bytes(stream);
+		me->wantAngle = stream->readUint16BE();
 		me->directionWhenDoneWalking = getSigned(stream);
 		me->inPoly = getSigned(stream);
 		me->walkToPoly = getSigned(stream);
 		if (ssgVersion >= VERSION(2, 0)) {
-			me->r = getch(stream);
-			me->g = getch(stream);
-			me->b = getch(stream);
-			me->colourmix = getch(stream);
-			me->transparency = getch(stream);
+			me->r = stream->readByte();
+			me->g = stream->readByte();
+			me->b = stream->readByte();
+			me->colourmix = stream->readByte();
+			me->transparency = stream->readByte();
 		} else {
-			setMyDrawMode(me, get2bytes(stream));
+			setMyDrawMode(me, stream->readUint16BE());
 		}
 		me->thisType = loadObjectRef(stream);
 
@@ -1239,7 +1239,7 @@ bool loadPeople(Common::SeekableReadStream *stream) {
 		if (ssgVersion >= VERSION(1, 6)) {
 			if (ssgVersion < VERSION(2, 0)) {
 				// aaLoad
-				getch(stream);
+				stream->readByte();
 				getFloat(stream);
 				getFloat(stream);
 			}
diff --git a/engines/sludge/region.cpp b/engines/sludge/region.cpp
index f837d32..efc6908 100644
--- a/engines/sludge/region.cpp
+++ b/engines/sludge/region.cpp
@@ -72,16 +72,16 @@ void saveRegions(Common::WriteStream *stream) {
 		thisRegion = thisRegion->next;
 		numRegions++;
 	}
-	put2bytes(numRegions, stream);
+	stream->writeUint16BE(numRegions);
 	thisRegion = allScreenRegions;
 	while (thisRegion) {
-		put2bytes(thisRegion->x1, stream);
-		put2bytes(thisRegion->y1, stream);
-		put2bytes(thisRegion->x2, stream);
-		put2bytes(thisRegion->y2, stream);
-		put2bytes(thisRegion->sX, stream);
-		put2bytes(thisRegion->sY, stream);
-		put2bytes(thisRegion->di, stream);
+		stream->writeUint16BE(thisRegion->x1);
+		stream->writeUint16BE(thisRegion->y1);
+		stream->writeUint16BE(thisRegion->x2);
+		stream->writeUint16BE(thisRegion->y2);
+		stream->writeUint16BE(thisRegion->sX);
+		stream->writeUint16BE(thisRegion->sY);
+		stream->writeUint16BE(thisRegion->di);
 		saveObjectRef(thisRegion->thisType, stream);
 
 		thisRegion = thisRegion->next;
@@ -89,7 +89,7 @@ void saveRegions(Common::WriteStream *stream) {
 }
 
 void loadRegions(Common::SeekableReadStream *stream) {
-	int numRegions = get2bytes(stream);
+	int numRegions = stream->readUint16BE();
 
 	screenRegion *newRegion;
 	screenRegion * * pointy = &allScreenRegions;
@@ -99,13 +99,13 @@ void loadRegions(Common::SeekableReadStream *stream) {
 		*pointy = newRegion;
 		pointy = &(newRegion->next);
 
-		newRegion->x1 = get2bytes(stream);
-		newRegion->y1 = get2bytes(stream);
-		newRegion->x2 = get2bytes(stream);
-		newRegion->y2 = get2bytes(stream);
-		newRegion->sX = get2bytes(stream);
-		newRegion->sY = get2bytes(stream);
-		newRegion->di = get2bytes(stream);
+		newRegion->x1 = stream->readUint16BE();
+		newRegion->y1 = stream->readUint16BE();
+		newRegion->x2 = stream->readUint16BE();
+		newRegion->y2 = stream->readUint16BE();
+		newRegion->sX = stream->readUint16BE();
+		newRegion->sY = stream->readUint16BE();
+		newRegion->di = stream->readUint16BE();
 		newRegion->thisType = loadObjectRef(stream);
 	}
 	*pointy = NULL;
diff --git a/engines/sludge/savedata.cpp b/engines/sludge/savedata.cpp
index 805f006..e387b92 100644
--- a/engines/sludge/savedata.cpp
+++ b/engines/sludge/savedata.cpp
@@ -64,20 +64,20 @@ extern char *gamePath;
 void writeStringEncoded(const char *s, Common::WriteStream *stream) {
 	int a, len = strlen(s);
 
-	put2bytes(len, stream);
+	stream->writeUint16BE(len);
 	for (a = 0; a < len; a++) {
-		putch(s[a] ^ encode1, stream);
+		stream->writeByte(s[a] ^ encode1);
 		encode1 += encode2;
 	}
 }
 
 char *readStringEncoded(Common::File *fp) {
-	int a, len = get2bytes(fp);
+	int a, len = fp->readUint16BE();
 	char *s = new char[len + 1];
 	if (!checkNew(s))
 		return NULL;
 	for (a = 0; a < len; a++) {
-		s[a] = (char) (getch(fp) ^ encode1);
+		s[a] = (char) (fp->readByte() ^ encode1);
 		encode1 += encode2;
 	}
 	s[len] = 0;
@@ -95,7 +95,7 @@ char *readTextPlain(Common::File *fp) {
 	startPos = fp->pos();
 
 	while (keepGoing) {
-		gotChar = (char) getch(fp);
+		gotChar = (char) fp->readByte();
 		if ((gotChar == '\n') || (fp->eos())) {
 			keepGoing = false;
 		} else {
@@ -114,7 +114,7 @@ char *readTextPlain(Common::File *fp) {
 		if (bytes_read != stringSize && fp->err()) {
 			debugOut("Reading error in readTextPlain.\n");
 		}
-		getch(fp);  // Skip the newline character
+		fp->readByte();  // Skip the newline character
 		reply[stringSize] = 0;
 	}
 
@@ -157,7 +157,7 @@ bool fileToStack(char *filename, stackHandler *sH) {
 	encode2 = (unsigned char) (saveEncoding >> 8);
 
 	while (*checker) {
-		if (getch(&fd) != *checker) {
+		if (fd.readByte() != *checker) {
 			fd.close();
 			return fatal(LOAD_ERROR "This isn't a SLUDGE custom data file:",
 					filename);
@@ -179,7 +179,7 @@ bool fileToStack(char *filename, stackHandler *sH) {
 
 	for (;;) {
 		if (saveEncoding) {
-			char i = getch(&fd) ^ encode1;
+			char i = fd.readByte() ^ encode1;
 
 			if (fd.eos())
 				break;
@@ -192,11 +192,11 @@ bool fileToStack(char *filename, stackHandler *sH) {
 				break;
 
 			case 1:
-				setVariable(stringVar, SVT_INT, get4bytes(&fd));
+				setVariable(stringVar, SVT_INT, fd.readUint32LE());
 				break;
 
 			case 2:
-				setVariable(stringVar, SVT_INT, getch(&fd));
+				setVariable(stringVar, SVT_INT, fd.readByte());
 				break;
 
 			default:
@@ -260,7 +260,7 @@ bool stackToFile(char *filename, const variable &from) {
 					fputc(hereWeAre -> thisVar.varData.intValue, fp);
 				} else {
 					fputc(1 ^ encode1, fp);
-					put4bytes(hereWeAre -> thisVar.varData.intValue, fp);
+					fp->writeUint32LE(hereWeAre -> thisVar.varData.intValue);
 				}
 				break;
 
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index c7ffd9d..7fe2119 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -127,23 +127,23 @@ const char *sludgeText[] = { "?????", "RETURN", "BRANCH", "BR_ZERO",
 		"INDEXGET", "INC_INDEX", "DEC_INDEX", "QUICK_PUSH" };
 
 void loadHandlers(Common::SeekableReadStream *stream) {
-	currentEvents->leftMouseFunction = get2bytes(stream);
-	currentEvents->leftMouseUpFunction = get2bytes(stream);
-	currentEvents->rightMouseFunction = get2bytes(stream);
-	currentEvents->rightMouseUpFunction = get2bytes(stream);
-	currentEvents->moveMouseFunction = get2bytes(stream);
-	currentEvents->focusFunction = get2bytes(stream);
-	currentEvents->spaceFunction = get2bytes(stream);
+	currentEvents->leftMouseFunction = stream->readUint16BE();
+	currentEvents->leftMouseUpFunction = stream->readUint16BE();
+	currentEvents->rightMouseFunction = stream->readUint16BE();
+	currentEvents->rightMouseUpFunction = stream->readUint16BE();
+	currentEvents->moveMouseFunction = stream->readUint16BE();
+	currentEvents->focusFunction = stream->readUint16BE();
+	currentEvents->spaceFunction = stream->readUint16BE();
 }
 
 void saveHandlers(Common::WriteStream *stream) {
-	put2bytes(currentEvents->leftMouseFunction, stream);
-	put2bytes(currentEvents->leftMouseUpFunction, stream);
-	put2bytes(currentEvents->rightMouseFunction, stream);
-	put2bytes(currentEvents->rightMouseUpFunction, stream);
-	put2bytes(currentEvents->moveMouseFunction, stream);
-	put2bytes(currentEvents->focusFunction, stream);
-	put2bytes(currentEvents->spaceFunction, stream);
+	stream->writeUint16BE(currentEvents->leftMouseFunction);
+	stream->writeUint16BE(currentEvents->leftMouseUpFunction);
+	stream->writeUint16BE(currentEvents->rightMouseFunction);
+	stream->writeUint16BE(currentEvents->rightMouseUpFunction);
+	stream->writeUint16BE(currentEvents->moveMouseFunction);
+	stream->writeUint16BE(currentEvents->focusFunction);
+	stream->writeUint16BE(currentEvents->spaceFunction);
 }
 
 Common::File *openAndVerify(char *filename, char extra1, char extra2,
@@ -154,32 +154,32 @@ Common::File *openAndVerify(char *filename, char extra1, char extra2,
 		return NULL;
 	}
 	bool headerBad = false;
-	if (getch(fp) != 'S')
+	if (fp->readByte() != 'S')
 		headerBad = true;
-	if (getch(fp) != 'L')
+	if (fp->readByte() != 'L')
 		headerBad = true;
-	if (getch(fp) != 'U')
+	if (fp->readByte() != 'U')
 		headerBad = true;
-	if (getch(fp) != 'D')
+	if (fp->readByte() != 'D')
 		headerBad = true;
-	if (getch(fp) != extra1)
+	if (fp->readByte() != extra1)
 		headerBad = true;
-	if (getch(fp) != extra2)
+	if (fp->readByte() != extra2)
 		headerBad = true;
 	if (headerBad) {
 		fatal(er, filename);
 		return NULL;
 	}
 	char c;
-	c = getch(fp);
+	c = fp->readByte();
 	debug("%c", c);
-	while ((c = getch(fp))) {
+	while ((c = fp->readByte())) {
 		debug("%c", c);
 	}
 
-	int majVersion = getch(fp);
+	int majVersion = fp->readByte();
 	debug(kSludgeDebugDataLoad, "majVersion %i", majVersion);
-	int minVersion = getch(fp);
+	int minVersion = fp->readByte();
 	debug(kSludgeDebugDataLoad, "minVersion %i", minVersion);
 	fileVersion = majVersion * 256 + minVersion;
 
@@ -206,9 +206,9 @@ bool initSludge(char *filename) {
 	if (!fp)
 		return false;
 
-	char c = getch(fp);
+	char c = fp->readByte();
 	if (c) {
-		numBIFNames = get2bytes(fp);
+		numBIFNames = fp->readUint16BE();
 		debug(kSludgeDebugDataLoad, "numBIFNames %i", numBIFNames);
 		allBIFNames = new char *[numBIFNames];
 		if (!checkNew(allBIFNames))
@@ -217,7 +217,7 @@ bool initSludge(char *filename) {
 		for (int fn = 0; fn < numBIFNames; fn++) {
 			allBIFNames[fn] = readString(fp);
 		}
-		numUserFunc = get2bytes(fp);
+		numUserFunc = fp->readUint16BE();
 		debug(kSludgeDebugDataLoad, "numUserFunc %i", numUserFunc);
 		allUserFunc = new char *[numUserFunc];
 		if (!checkNew(allUserFunc))
@@ -227,7 +227,7 @@ bool initSludge(char *filename) {
 			allUserFunc[fn] = readString(fp);
 		}
 		if (gameVersion >= VERSION(1, 3)) {
-			numResourceNames = get2bytes(fp);
+			numResourceNames = fp->readUint16BE();
 			debug(kSludgeDebugDataLoad, "numResourceNames %i",
 					numResourceNames);
 			allResourceNames = new char *[numResourceNames];
@@ -240,13 +240,13 @@ bool initSludge(char *filename) {
 		}
 	}
 
-	winWidth = get2bytes(fp);
+	winWidth = fp->readUint16BE();
 	debug(kSludgeDebugDataLoad, "winWidth : %i", winWidth);
-	winHeight = get2bytes(fp);
+	winHeight = fp->readUint16BE();
 	debug(kSludgeDebugDataLoad, "winHeight : %i", winHeight);
-	specialSettings = getch(fp);
+	specialSettings = fp->readByte();
 	debug(kSludgeDebugDataLoad, "specialSettings : %i", specialSettings);
-	desiredfps = 1000 / getch(fp);
+	desiredfps = 1000 / fp->readByte();
 
 	delete[] readString(fp);  // Unused - was used for registration purposes.
 
@@ -261,14 +261,14 @@ bool initSludge(char *filename) {
 	debug(kSludgeDebugDataLoad, "dataFol : %s", dataFol);
 
 	gameSettings.numLanguages =
-			(gameVersion >= VERSION(1, 3)) ? (getch(fp)) : 0;
+			(gameVersion >= VERSION(1, 3)) ? (fp->readByte()) : 0;
 	debug(kSludgeDebugDataLoad, "numLanguages : %c", gameSettings.numLanguages);
 	makeLanguageTable(fp);
 
 	if (gameVersion >= VERSION(1, 6)) {
-		getch(fp);
+		fp->readByte();
 		// aaLoad
-		getch(fp);
+		fp->readByte();
 		getFloat(fp);
 		getFloat(fp);
 	}
@@ -281,7 +281,7 @@ bool initSludge(char *filename) {
 	delete checker;
 	checker = NULL;
 
-	unsigned char customIconLogo = getch(fp);
+	unsigned char customIconLogo = fp->readByte();
 	debug(kSludgeDebugDataLoad, "Game icon type: %i", customIconLogo);
 
 	if (customIconLogo & 1) {
@@ -309,8 +309,8 @@ bool initSludge(char *filename) {
 			fileIsPNG = false;
 			fseek(fp, file_pointer, SEEK_SET);
 
-			iconW = get2bytes(fp);
-			iconH = get2bytes(fp);
+			iconW = fp->readUint16BE();
+			iconH = fp->readUint16BE();
 		} else {
 			// Read the PNG header
 
@@ -373,7 +373,7 @@ bool initSludge(char *filename) {
 			for (int t2 = 0; t2 < iconH; t2 ++) {
 				int t1 = 0;
 				while (t1 < iconW) {
-					unsigned short c = (unsigned short) get2bytes(fp);
+					unsigned short c = (unsigned short) fp->readUint16BE();
 					if (c & 32) {
 						n = fgetc(fp) + 1;
 						c -= 32;
@@ -418,8 +418,8 @@ bool initSludge(char *filename) {
 			fileIsPNG = false;
 			fseek(fp, file_pointer, SEEK_SET);
 
-			logoW = get2bytes(fp);
-			logoH = get2bytes(fp);
+			logoW = fp->readUint16BE();
+			logoH = fp->readUint16BE();
 		} else {
 			// Read the PNG header
 
@@ -490,7 +490,7 @@ bool initSludge(char *filename) {
 			for (int t2 = 0; t2 < logoH; t2 ++) {
 				int t1 = 0;
 				while (t1 < logoW) {
-					unsigned short c = (unsigned short) get2bytes(fp);
+					unsigned short c = (unsigned short) fp->readUint16BE();
 					if (c & 32) {
 						n = fgetc(fp) + 1;
 						c -= 32;
@@ -518,7 +518,7 @@ bool initSludge(char *filename) {
 #endif
 	}
 
-	numGlobals = get2bytes(fp);
+	numGlobals = fp->readUint16BE();
 	debug("numGlobals : %i", numGlobals);
 
 	globalVars = new variable[numGlobals];
@@ -1398,21 +1398,20 @@ bool loadFunctionCode(loadedFunction *newFunc) {
 
 	debug(kSludgeDebugDataLoad, "Load function code");
 
-	newFunc->unfreezable = getch(bigDataFile);
-	numLines = get2bytes(bigDataFile);
+	newFunc->unfreezable = bigDataFile->readByte();
+	numLines = bigDataFile->readUint16BE();
 	debug(kSludgeDebugDataLoad, "numLines: %i", numLines);
-	newFunc->numArgs = get2bytes(bigDataFile);
+	newFunc->numArgs = bigDataFile->readUint16BE();
 	debug(kSludgeDebugDataLoad, "numArgs: %i", newFunc->numArgs);
-	newFunc->numLocals = get2bytes(bigDataFile);
+	newFunc->numLocals = bigDataFile->readUint16BE();
 	debug(kSludgeDebugDataLoad, "numLocals: %i", newFunc->numLocals);
 	newFunc->compiledLines = new lineOfCode[numLines];
 	if (!checkNew(newFunc->compiledLines))
 		return false;
 
 	for (numLinesRead = 0; numLinesRead < numLines; numLinesRead++) {
-		newFunc->compiledLines[numLinesRead].theCommand = (sludgeCommand) getch(
-				bigDataFile);
-		newFunc->compiledLines[numLinesRead].param = get2bytes(bigDataFile);
+		newFunc->compiledLines[numLinesRead].theCommand = (sludgeCommand) bigDataFile->readByte();
+		newFunc->compiledLines[numLinesRead].param = bigDataFile->readUint16BE();
 		debug(kSludgeDebugDataLoad, "command line %i: %i", numLinesRead,
 				newFunc->compiledLines[numLinesRead].theCommand);
 	}
diff --git a/engines/sludge/sound_bass.cpp b/engines/sludge/sound_bass.cpp
index 5bb4e79..c2fa56d 100644
--- a/engines/sludge/sound_bass.cpp
+++ b/engines/sludge/sound_bass.cpp
@@ -379,29 +379,29 @@ void saveSounds(Common::WriteStream *stream) {
 	if (soundOK) {
 		for (int i = 0; i < MAX_SAMPLES; i++) {
 			if (soundCache[i].looping) {
-				putch(1, stream);
-				put2bytes(soundCache[i].fileLoaded, stream);
-				put2bytes(soundCache[i].vol, stream);
+				stream->writeByte(1);
+				stream->writeUint16BE(soundCache[i].fileLoaded);
+				stream->writeUint16BE(soundCache[i].vol);
 			}
 		}
 	}
-	putch(0, stream);
-	put2bytes(defSoundVol, stream);
-	put2bytes(defVol, stream);
+	stream->writeByte(0);
+	stream->writeUint16BE(defSoundVol);
+	stream->writeUint16BE(defVol);
 }
 
 void loadSounds(Common::SeekableReadStream *stream) {
 	for (int i = 0; i < MAX_SAMPLES; i++)
 		freeSound(i);
 
-	while (getch(stream)) {
-		int fileLoaded = get2bytes(stream);
-		defSoundVol = get2bytes(stream);
+	while (stream->readByte()) {
+		int fileLoaded = stream->readUint16BE();
+		defSoundVol = stream->readUint16BE();
 		startSound(fileLoaded, 1);
 	}
 
-	defSoundVol = get2bytes(stream);
-	defVol = get2bytes(stream);
+	defSoundVol = stream->readUint16BE();
+	defVol = stream->readUint16BE();
 }
 
 bool getSoundCacheStack(stackHandler *sH) {
diff --git a/engines/sludge/sound_nosound.cpp b/engines/sludge/sound_nosound.cpp
index 292148b..2c347e6 100644
--- a/engines/sludge/sound_nosound.cpp
+++ b/engines/sludge/sound_nosound.cpp
@@ -113,19 +113,19 @@ bool startSound(int f, bool loopy) {
 }
 
 void saveSounds(Common::WriteStream *stream) {
-	putch(0, stream);
-	put2bytes(defSoundVol, stream);
-	put2bytes(defVol, stream);
+	stream->writeByte(0);
+	stream->writeUint16BE(defSoundVol);
+	stream->writeUint16BE(defVol);
 }
 
 void loadSounds(Common::SeekableReadStream *stream) {
-	while (getch(stream)) {
-		get2bytes(stream);
-		get2bytes(stream);
+	while (stream->readByte()) {
+		stream->readUint16BE();
+		stream->readUint16BE();
 	}
 
-	defSoundVol = get2bytes(stream);
-	defVol = get2bytes(stream);
+	defSoundVol = stream->readUint16BE();
+	defVol = stream->readUint16BE();
 }
 
 bool getSoundCacheStack(stackHandler *sH) {
diff --git a/engines/sludge/sound_openal.cpp b/engines/sludge/sound_openal.cpp
index 72824d3..e180bf8 100644
--- a/engines/sludge/sound_openal.cpp
+++ b/engines/sludge/sound_openal.cpp
@@ -606,29 +606,29 @@ void saveSounds(Common::WriteStream *stream) {
 	if (soundOK) {
 		for (int i = 0; i < MAX_SAMPLES; i++) {
 			if (soundCache[i].looping) {
-				putch(1, stream);
-				put2bytes(soundCache[i].fileLoaded, stream);
-				put2bytes(soundCache[i].vol, stream);
+				stream->writeByte(1);
+				stream->writeUint16BE(soundCache[i].fileLoaded);
+				stream->writeUint16BE(soundCache[i].vol);
 			}
 		}
 	}
-	putch(0, stream);
-	put2bytes(defSoundVol, stream);
-	put2bytes(defVol, stream);
+	stream->writeByte(0);
+	stream->writeUint16BE(defSoundVol);
+	stream->writeUint16BE(defVol);
 }
 
 void loadSounds(Common::SeekableReadStream *stream) {
 	for (int i = 0; i < MAX_SAMPLES; i++)
 		freeSound(i);
 
-	while (getch(stream)) {
-		int fileLoaded = get2bytes(stream);
-		defSoundVol = get2bytes(stream);
+	while (stream->readByte()) {
+		int fileLoaded = stream->readUint16BE();
+		defSoundVol = stream->readUint16BE();
 		startSound(fileLoaded, 1);
 	}
 
-	defSoundVol = get2bytes(stream);
-	defVol = get2bytes(stream);
+	defSoundVol = stream->readUint16BE();
+	defVol = stream->readUint16BE();
 }
 
 bool getSoundCacheStack(stackHandler *sH) {
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index 5b372e6..069d97f 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -130,13 +130,13 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 
 	loadhere.isFont = isFont;
 
-	total = get2bytes(bigDataFile);
+	total = bigDataFile->readUint16BE();
 	if (! total) {
 		spriteBankVersion = fgetc(bigDataFile);
 		if (spriteBankVersion == 1) {
 			total = 0;
 		} else {
-			total = get2bytes(bigDataFile);
+			total = bigDataFile->readUint16BE();
 		}
 	}
 
@@ -223,8 +223,8 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 				break;
 			}
 			case 2:
-			picwidth = get2bytes(bigDataFile);
-			picheight = get2bytes(bigDataFile);
+			picwidth = bigDataFile->readUint16BE();
+			picheight = bigDataFile->readUint16BE();
 			loadhere.sprites[i].xhot = getSigned(bigDataFile);
 			loadhere.sprites[i].yhot = getSigned(bigDataFile);
 			break;
diff --git a/engines/sludge/statusba.cpp b/engines/sludge/statusba.cpp
index d90d3a2..da9d655 100644
--- a/engines/sludge/statusba.cpp
+++ b/engines/sludge/statusba.cpp
@@ -29,6 +29,7 @@
 #include "stringy.h"
 #include "newfatal.h"
 #include "statusba.h"
+#include "common/file.h"
 
 namespace Sludge {
 
@@ -176,48 +177,48 @@ const char *statusBarText() {
 void saveStatusBars(Common::WriteStream *stream) {
 	statusBar *viewLine = nowStatus->firstStatusBar;
 
-	put2bytes(nowStatus->alignStatus, stream);
+	stream->writeUint16BE(nowStatus->alignStatus);
 	putSigned(nowStatus->litStatus, stream);
-	put2bytes(nowStatus->statusX, stream);
-	put2bytes(nowStatus->statusY, stream);
+	stream->writeUint16BE(nowStatus->statusX);
+	stream->writeUint16BE(nowStatus->statusY);
 
-	putch(nowStatus->statusR, stream);
-	putch(nowStatus->statusG, stream);
-	putch(nowStatus->statusB, stream);
-	putch(nowStatus->statusLR, stream);
-	putch(nowStatus->statusLG, stream);
-	putch(nowStatus->statusLB, stream);
+	stream->writeByte(nowStatus->statusR);
+	stream->writeByte(nowStatus->statusG);
+	stream->writeByte(nowStatus->statusB);
+	stream->writeByte(nowStatus->statusLR);
+	stream->writeByte(nowStatus->statusLG);
+	stream->writeByte(nowStatus->statusLB);
 
 	// Write what's being said
 	while (viewLine) {
-		putch(1, stream);
+		stream->writeByte(1);
 		writeString(viewLine->text, stream);
 		viewLine = viewLine->next;
 	}
-	putch(0, stream);
+	stream->writeByte(0);
 }
 
 bool loadStatusBars(Common::SeekableReadStream *stream) {
 	clearStatusBar();
 
-	nowStatus->alignStatus = get2bytes(stream);
+	nowStatus->alignStatus = stream->readUint16BE();
 	nowStatus->litStatus = getSigned(stream);
-	nowStatus->statusX = get2bytes(stream);
-	nowStatus->statusY = get2bytes(stream);
+	nowStatus->statusX = stream->readUint16BE();
+	nowStatus->statusY = stream->readUint16BE();
 
-	nowStatus->statusR = getch(stream);
-	nowStatus->statusG = getch(stream);
-	nowStatus->statusB = getch(stream);
-	nowStatus->statusLR = getch(stream);
-	nowStatus->statusLG = getch(stream);
-	nowStatus->statusLB = getch(stream);
+	nowStatus->statusR = stream->readByte();
+	nowStatus->statusG = stream->readByte();
+	nowStatus->statusB = stream->readByte();
+	nowStatus->statusLR = stream->readByte();
+	nowStatus->statusLG = stream->readByte();
+	nowStatus->statusLB = stream->readByte();
 
 	setFontColour(verbLinePalette, nowStatus->statusR, nowStatus->statusG, nowStatus->statusB);
 	setFontColour(litVerbLinePalette, nowStatus->statusLR, nowStatus->statusLG, nowStatus->statusLB);
 	// Read what's being said
 	statusBar * * viewLine = & (nowStatus->firstStatusBar);
 	statusBar *newOne;
-	while (getch(stream)) {
+	while (stream->readByte()) {
 		newOne = new statusBar;
 		if (! checkNew(newOne)) return false;
 		newOne->text = readString(stream);
diff --git a/engines/sludge/talk.cpp b/engines/sludge/talk.cpp
index 5e6c10d..0b66815 100644
--- a/engines/sludge/talk.cpp
+++ b/engines/sludge/talk.cpp
@@ -219,32 +219,32 @@ void saveSpeech(speechStruct *sS, Common::WriteStream *stream) {
 #if 0
 	speechLine *viewLine = sS->allSpeech;
 
-	putch(sS->talkCol.originalRed, stream);
-	putch(sS->talkCol.originalGreen, stream);
-	putch(sS->talkCol.originalBlue, stream);
+	stream->writeByte(sS->talkCol.originalRed);
+	stream->writeByte(sS->talkCol.originalGreen);
+	stream->writeByte(sS->talkCol.originalBlue);
 
 	putFloat(speechSpeed, stream);
 
 	// Write y co-ordinate
-	put2bytes(sS->speechY, stream);
+	stream->writeUint16BE(sS->speechY);
 
 	// Write which character's talking
-	put2bytes(sS->lookWhosTalking, stream);
+	stream->writeUint16BE(sS->lookWhosTalking);
 	if (sS->currentTalker) {
-		putch(1, stream);
-		put2bytes(sS->currentTalker->thisType->objectNum, stream);
+		stream->writeByte(1);
+		stream->writeUint16BE(sS->currentTalker->thisType->objectNum);
 	} else {
-		putch(0, stream);
+		stream->writeByte(0);
 	}
 
 	// Write what's being said
 	while (viewLine) {
-		putch(1, stream);
+		stream->writeByte(1);
 		writeString(viewLine->textLine, stream);
-		put2bytes(viewLine->x, stream);
+		stream->writeUint16BE(viewLine->x);
 		viewLine = viewLine->next;
 	}
-	putch(0, stream);
+	stream->writeByte(0);
 #endif
 }
 
@@ -252,21 +252,21 @@ bool loadSpeech(speechStruct *sS, Common::SeekableReadStream *stream) {
 #if 0
 	speech->currentTalker = NULL;
 	killAllSpeech();
-	byte r = getch(stream);
-	byte g = getch(stream);
-	byte b = getch(stream);
+	byte r = stream->readByte();
+	byte g = stream->readByte();
+	byte b = stream->readByte();
 	setFontColour(sS->talkCol, r, g, b);
 
 	speechSpeed = getFloat(stream);
 
 	// Read y co-ordinate
-	sS->speechY = get2bytes(stream);
+	sS->speechY = stream->readUint16BE();
 
 	// Read which character's talking
-	sS->lookWhosTalking = get2bytes(stream);
+	sS->lookWhosTalking = stream->readUint16BE();
 
-	if (getch(stream)) {
-		sS->currentTalker = findPerson(get2bytes(stream));
+	if (stream->readByte()) {
+		sS->currentTalker = findPerson(stream->readUint16BE());
 	} else {
 		sS->currentTalker = NULL;
 	}
@@ -275,11 +275,11 @@ bool loadSpeech(speechStruct *sS, Common::SeekableReadStream *stream) {
 	speechLine * * viewLine = &sS->allSpeech;
 	speechLine *newOne;
 	speech->lastFile = -1;
-	while (getch(stream)) {
+	while (stream->readByte()) {
 		newOne = new speechLine;
 		if (! checkNew(newOne)) return false;
 		newOne->textLine = readString(stream);
-		newOne->x = get2bytes(stream);
+		newOne->x = stream->readUint16BE();
 		newOne->next = NULL;
 		(* viewLine) = newOne;
 		viewLine = &(newOne->next);
diff --git a/engines/sludge/thumbnail.cpp b/engines/sludge/thumbnail.cpp
index 7c588a2..5e77936 100644
--- a/engines/sludge/thumbnail.cpp
+++ b/engines/sludge/thumbnail.cpp
@@ -44,8 +44,8 @@ bool saveThumbnail(Common::WriteStream *stream) {
 #if 0
 	GLuint thumbnailTextureName = 0;
 
-	put4bytes(thumbWidth, fp);
-	put4bytes(thumbHeight, fp);
+	fp->writeUint32LE(thumbWidth);
+	fp->writeUint32LE(thumbHeight);
 
 	if (thumbWidth && thumbHeight) {
 		if (! freeze()) return false;
@@ -148,8 +148,8 @@ void showThumbnail(char *filename, int atX, int atY) {
 	FILE *fp = openAndVerify(filename, 'S', 'A', ERROR_GAME_LOAD_NO, ssgVersion);
 	if (ssgVersion >= VERSION(1, 4)) {
 		if (fp == NULL) return;
-		int fileWidth = get4bytes(fp);
-		int fileHeight = get4bytes(fp);
+		int fileWidth = fp->readUint32LE();
+		int fileHeight = fp->readUint32LE();
 
 		int picWidth = fileWidth;
 		int picHeight = fileHeight;
@@ -170,7 +170,7 @@ void showThumbnail(char *filename, int atX, int atY) {
 		for (t2 = 0; t2 < fileHeight; t2 ++) {
 			t1 = 0;
 			while (t1 < fileWidth) {
-				c = (unsigned short) get2bytes(fp);
+				c = (unsigned short) fp->readUint16BE();
 				target = thumbnailTexture + 4 * picWidth * t2 + t1 * 4;
 				target[0] = (GLubyte) redValue(c);
 				target[1] = (GLubyte) greenValue(c);
@@ -252,12 +252,12 @@ void showThumbnail(char *filename, int atX, int atY) {
 }
 
 bool skipThumbnail(Common::SeekableReadStream *stream) {
-	thumbWidth = get4bytes(stream);
-	thumbHeight = get4bytes(stream);
+	thumbWidth = stream->readUint32LE();
+	thumbHeight = stream->readUint32LE();
 	uint32_t skippy = thumbWidth;
 	skippy *= thumbHeight << 1;
 	stream->seek(skippy, 1);
-	return (getch(stream) == '!');
+	return (stream->readByte() == '!');
 }
 
 } // End of namespace Sludge
diff --git a/engines/sludge/zbuffer.cpp b/engines/sludge/zbuffer.cpp
index fe13a98..d81fde6 100644
--- a/engines/sludge/zbuffer.cpp
+++ b/engines/sludge/zbuffer.cpp
@@ -87,8 +87,8 @@ bool setZBuffer(int y) {
 		break;
 
 		case 1:
-		zBuffer.width = get2bytes(bigDataFile);
-		zBuffer.height = get2bytes(bigDataFile);
+		zBuffer.width = bigDataFile->readUint16BE();
+		zBuffer.height = bigDataFile->readUint16BE();
 		break;
 
 		default:
@@ -102,7 +102,7 @@ bool setZBuffer(int y) {
 
 	zBuffer.numPanels = fgetc(bigDataFile);
 	for (y = 0; y < zBuffer.numPanels; y ++) {
-		yPalette[y] = get2bytes(bigDataFile);
+		yPalette[y] = bigDataFile->readUint16BE();
 	}
 	sortZPal(yPalette, sorted, zBuffer.numPanels);
 	for (y = 0; y < zBuffer.numPanels; y ++) {
@@ -124,7 +124,7 @@ bool setZBuffer(int y) {
 			if (stillToGo == 0) {
 				n = fgetc(bigDataFile);
 				stillToGo = n >> 4;
-				if (stillToGo == 15) stillToGo = get2bytes(bigDataFile) + 16l;
+				if (stillToGo == 15) stillToGo = bigDataFile->readUint16BE() + 16l;
 				else stillToGo ++;
 				n &= 15;
 			}


Commit: 786e4c3dc3ce834002253f8c280826108f9a3225
    https://github.com/scummvm/scummvm/commit/786e4c3dc3ce834002253f8c280826108f9a3225
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Refactor image loading function and apply in backdrop

Changed paths:
  A engines/sludge/imgloader.cpp
  A engines/sludge/imgloader.h
  R engines/sludge/bytearray.cpp
  R engines/sludge/bytearray.h
    engines/sludge/backdrop.cpp
    engines/sludge/backdrop.h
    engines/sludge/builtin.cpp
    engines/sludge/freeze.cpp
    engines/sludge/graphics.h
    engines/sludge/main_loop.cpp
    engines/sludge/module.mk


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index 07f4d35..35159d0 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -60,7 +60,7 @@
 #include "graphics/surface.h"
 #include "graphics/palette.h"
 #include "sludge.h"
-#include "bytearray.h"
+#include "imgloader.h"
 
 namespace Sludge {
 
@@ -76,11 +76,10 @@ bool backdropExists = false;
 GLfloat backdropTexW = 1.0;
 GLfloat backdropTexH = 1.0;
 
-texture lightMap;
-
 GLuint snapshotTextureName = 0;
 #endif
 
+texture lightMap;
 Graphics::Surface backdropSurface;
 
 float snapTexW = 1.0;
@@ -226,6 +225,8 @@ bool restoreSnapshot(Common::SeekableReadStream *stream) {
 }
 
 void killBackDrop() {
+	if (backdropSurface.getPixels())
+		backdropSurface.free();
 #if 0
 	deleteTextures(1, &backdropTextureName);
 	backdropTextureName = 0;
@@ -234,31 +235,31 @@ void killBackDrop() {
 }
 
 void killLightMap() {
+	if (lightMap.surface.getPixels()) {
+		lightMap.surface.free();
+	}
+	lightMapNumber = 0;
 #if 0
 	deleteTextures(1, &lightMap.name);
 	lightMap.name = 0;
-	if (lightMap.data) {
-		delete lightMap.data;
-		lightMap.data = NULL;
-	}
-	lightMapNumber = 0;
 #endif
 }
 
 void killParallax() {
-#if 0
+
 	while (parallaxStuff) {
 
 		parallaxLayer *k = parallaxStuff;
 		parallaxStuff = k->next;
-
+#if 0
 		// Now kill the image
 		deleteTextures(1, &k->textureName);
-		delete k->texture;
+#endif
+		k->surface.free();
 		delete k;
 		k = NULL;
 	}
-#endif
+
 }
 
 bool reserveBackdrop() {
@@ -302,16 +303,24 @@ bool reserveBackdrop() {
 	return true;
 }
 
-bool resizeBackdrop(int x, int y) {
+void killAllBackDrop() {
 	killLightMap();
 	killBackDrop();
 	killParallax();
 	killZBuffer();
+}
+
+bool resizeBackdrop(int x, int y) {
 	sceneWidth = x;
 	sceneHeight = y;
 	return reserveBackdrop();
 }
 
+bool killResizeBackdrop(int x, int y) {
+	killAllBackDrop();
+	return resizeBackdrop(x, y);
+}
+
 void loadBackDrop(int fileNum, int x, int y) {
 	debug(kSludgeDebugGraphics, "Load back drop");
 	setResourceForFatal(fileNum);
@@ -333,7 +342,6 @@ void loadBackDrop(int fileNum, int x, int y) {
 }
 
 void mixBackDrop(int fileNum, int x, int y) {
-#if 0
 	setResourceForFatal(fileNum);
 	if (!openFileFromNum(fileNum)) {
 		fatal("Can't load overlay image");
@@ -345,7 +353,6 @@ void mixBackDrop(int fileNum, int x, int y) {
 	}
 
 	finishAccess();
-#endif
 	setResourceForFatal(-1);
 }
 
@@ -629,83 +636,25 @@ void drawBackDrop() {
 }
 
 bool loadLightMap(int v) {
-	int newPicWidth, newPicHeight;
-#if 0
 	setResourceForFatal(v);
 	if (!openFileFromNum(v)) return fatal("Can't open light map.");
-	long file_pointer = ftell(bigDataFile);
-
-	png_structp png_ptr;
-	png_infop info_ptr, end_info;
-
-	int fileIsPNG = true;
 
-	// Is this a PNG file?
-
-	char tmp[10];
-	size_t bytes_read = fread(tmp, 1, 8, bigDataFile);
-	if (bytes_read != 8 && ferror(bigDataFile)) {
-		debugOut("Reading error in loadLightMap.\n");
-	}
-
-	if (png_sig_cmp((png_byte *) tmp, 0, 8)) {
-		// No, it's old-school HSI
-		fileIsPNG = false;
-		fseek(bigDataFile, file_pointer, SEEK_SET);
-
-		newPicWidth = lightMap.w = bigDataFile->readUint16BE();
-		newPicHeight = lightMap.h = bigDataFile->readUint16BE();
-	} else {
-		// Read the PNG header
-
-		png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
-		if (!png_ptr) {
-			return false;
-		}
-
-		info_ptr = png_create_info_struct(png_ptr);
-		if (!info_ptr) {
-			png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
-			return false;
-		}
-
-		end_info = png_create_info_struct(png_ptr);
-		if (!end_info) {
-			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
-			return false;
-		}
-		png_init_io(png_ptr, bigDataFile);     // Tell libpng which file to read
-		png_set_sig_bytes(png_ptr, 8);// 8 bytes already read
-
-		png_read_info(png_ptr, info_ptr);
-
-		png_uint_32 width, height;
-		int bit_depth, color_type, interlace_type, compression_type, filter_method;
-		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
-
-		newPicWidth = lightMap.w = width;
-		newPicHeight = lightMap.h = height;
-
-		if (bit_depth < 8) png_set_packing(png_ptr);
-		png_set_expand(png_ptr);
-		if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr);
-		if (bit_depth == 16) png_set_strip_16(png_ptr);
-
-		png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER);
-
-		png_read_update_info(png_ptr, info_ptr);
-		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
+	killLightMap();
+	lightMapNumber = v;
 
-		//int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
+	if (!ImgLoader::loadImage(bigDataFile, &lightMap.surface))
+		return false;
 
-	}
+	int newPicWidth = lightMap.surface.w;
+	int newPicHeight = lightMap.surface.h;
 
 	if (lightMapMode == LIGHTMAPMODE_HOTSPOT) {
-		if (lightMap.w != sceneWidth || lightMap.h != sceneHeight) {
+		if (lightMap.surface.w != sceneWidth || lightMap.surface.h != sceneHeight) {
 			return fatal("Light map width and height don't match scene width and height. That is required for lightmaps in HOTSPOT mode.");
 		}
 	}
 
+#if 0
 	if (!NPOT_textures) {
 		newPicWidth = getNextPOT(lightMap.w);
 		newPicHeight = getNextPOT(lightMap.h);
@@ -715,54 +664,11 @@ bool loadLightMap(int v) {
 		lightMap.texW = 1.0;
 		lightMap.texH = 1.0;
 	}
+#endif
 
-	killLightMap();
-	lightMapNumber = v;
 #if 0
 	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
 #endif
-	if (lightMap.data) delete [] lightMap.data;
-
-	lightMap.data = new GLubyte [newPicWidth * newPicHeight * 4];
-	if (!lightMap.data) {
-		return fatal("Out of memory loading light map.");
-	}
-
-	int t1, t2, n;
-	unsigned short c;
-	GLubyte *target;
-
-	if (fileIsPNG) {
-		unsigned char *row_pointers[lightMap.h];
-		for (int i = 0; i < lightMap.h; i++)
-		row_pointers[i] = lightMap.data + 4 * i * newPicWidth;
-
-		png_read_image(png_ptr, (png_byte **) row_pointers);
-		png_read_end(png_ptr, NULL);
-		png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
-	} else {
-
-		for (t2 = 0; t2 < lightMap.h; t2 ++) {
-			t1 = 0;
-			while (t1 < lightMap.w) {
-				c = (unsigned short)bigDataFile->readUint16BE();
-				if (c & 32) {
-					n = fgetc(bigDataFile) + 1;
-					c -= 32;
-				} else {
-					n = 1;
-				}
-				while (n --) {
-					target = lightMap.data + 4 * newPicWidth * t2 + t1 * 4;
-					target[0] = (GLubyte) redValue(c);
-					target[1] = (GLubyte) greenValue(c);
-					target[2] = (GLubyte) blueValue(c);
-					target[3] = (GLubyte) 255;
-					t1++;
-				}
-			}
-		}
-	}
 #if 0
 	if (!lightMap.name) glGenTextures(1, &lightMap.name);
 	glBindTexture(GL_TEXTURE_2D, lightMap.name);
@@ -775,7 +681,6 @@ bool loadLightMap(int v) {
 #endif
 	finishAccess();
 
-#endif
 	setResourceForFatal(-1);
 
 	return true;
@@ -820,10 +725,7 @@ void reloadParallaxTextures() {
 #endif
 }
 
-bool loadParallax(unsigned short v, unsigned short fracX,
-		unsigned short fracY) {
-
-#if 0
+bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY) {
 	setResourceForFatal(v);
 	if (!openFileFromNum(v)) return fatal("Can't open parallax image");
 
@@ -840,71 +742,8 @@ bool loadParallax(unsigned short v, unsigned short fracX,
 	int picWidth;
 	int picHeight;
 
-	long file_pointer = ftell(bigDataFile);
-
-	png_structp png_ptr;
-	png_infop info_ptr, end_info;
-
-	int fileIsPNG = true;
-
-	// Is this a PNG file?
-
-	char tmp[10];
-	size_t bytes_read = fread(tmp, 1, 8, bigDataFile);
-	if (bytes_read != 8 && ferror(bigDataFile)) {
-		debugOut("Reading error in loadParallax.\n");
-	}
-	if (png_sig_cmp((png_byte *) tmp, 0, 8)) {
-		// No, it's old-school HSI
-		fileIsPNG = false;
-		fseek(bigDataFile, file_pointer, SEEK_SET);
-
-		picWidth = nP->width = bigDataFile->readUint16BE();
-		picHeight = nP->height = bigDataFile->readUint16BE();
-	} else {
-		// Read the PNG header
-
-		png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
-		if (!png_ptr) {
-			return false;
-		}
-
-		info_ptr = png_create_info_struct(png_ptr);
-		if (!info_ptr) {
-			png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
-			return false;
-		}
-
-		end_info = png_create_info_struct(png_ptr);
-		if (!end_info) {
-			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
-			return false;
-		}
-		png_init_io(png_ptr, bigDataFile);     // Tell libpng which file to read
-		png_set_sig_bytes(png_ptr, 8);// 8 bytes already read
-
-		png_read_info(png_ptr, info_ptr);
-
-		png_uint_32 width, height;
-		int bit_depth, color_type, interlace_type, compression_type, filter_method;
-		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
-
-		picWidth = nP->width = width;
-		picHeight = nP->height = height;
-
-		if (bit_depth < 8) png_set_packing(png_ptr);
-		png_set_expand(png_ptr);
-		if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr);
-		if (bit_depth == 16) png_set_strip_16(png_ptr);
-
-		png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER);
-
-		png_read_update_info(png_ptr, info_ptr);
-		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
-
-		//int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
-
-	}
+	if (!ImgLoader::loadImage(bigDataFile, &nP->surface, false))
+		return false;
 
 	if (!NPOT_textures) {
 		picWidth = getNextPOT(picWidth);
@@ -935,52 +774,7 @@ bool loadParallax(unsigned short v, unsigned short fracX,
 		nP->wrapT = true;
 	}
 
-	nP->texture = new GLubyte [picHeight * picWidth * 4];
-	if (!checkNew(nP->texture)) return false;
-
-	if (fileIsPNG) {
-		unsigned char *row_pointers[nP->height];
-		for (int i = 0; i < nP->height; i++)
-		row_pointers[i] = nP->texture + 4 * i * picWidth;
-
-		png_read_image(png_ptr, (png_byte **) row_pointers);
-		png_read_end(png_ptr, NULL);
-		png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
-	} else {
-
-		int t1, t2, n;
-		unsigned short c;
-		GLubyte *target;
-
-		for (t2 = 0; t2 < nP->height; t2 ++) {
-			t1 = 0;
-			while (t1 < nP->width) {
-				c = (unsigned short)bigDataFile->readUint16BE();
-				if (c & 32) {
-					n = fgetc(bigDataFile) + 1;
-					c -= 32;
-				} else {
-					n = 1;
-				}
-				while (n--) {
-					target = nP->texture + 4 * picWidth * t2 + t1 * 4;
-					if (c == 63519 || c == 2015) {
-						target[0] = (GLubyte) 0;
-						target[1] = (GLubyte) 0;
-						target[2] = (GLubyte) 0;
-						target[3] = (GLubyte) 0;
-					} else {
-						target[0] = (GLubyte) redValue(c);
-						target[1] = (GLubyte) greenValue(c);
-						target[2] = (GLubyte) blueValue(c);
-						target[3] = (GLubyte) 255;
-					}
-					t1 ++;
-				}
-			}
-		}
-	}
-
+#if 0
 	glGenTextures(1, &nP->textureName);
 	glBindTexture(GL_TEXTURE_2D, nP->textureName);
 	if (nP->wrapS)
@@ -1001,176 +795,14 @@ bool loadParallax(unsigned short v, unsigned short fracX,
 	}
 
 	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, nP->texture, nP->textureName);
-
-	finishAccess();
 #endif
+	finishAccess();
 	setResourceForFatal(-1);
 	return true;
 }
 
 extern int viewportOffsetX, viewportOffsetY;
 
-bool loadPng(int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, bool reserve) {
-	debug(kSludgeDebugGraphics, "Loading back drop png at file position: %i", stream->pos());
-	::Image::PNGDecoder png;
-	if (!png.loadStream(*stream)) {
-		debug(kSludgeDebugGraphics, "Back drop is not a png");
-		return false;
-	}
-	const Graphics::Surface *sourceSurface = png.getSurface();
-	Graphics::Surface *pngSurface = sourceSurface->convertTo(Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0), png.getPalette());
-	backdropSurface.copyFrom(*pngSurface);
-	pngSurface->free();
-	delete pngSurface;
-	picWidth = realPicWidth = backdropSurface.w;
-	picHeight = realPicHeight = backdropSurface.h;
-	return true;
-#if 0
-	long file_pointer = stream->pos();
-	png_structp png_ptr;
-	png_infop info_ptr, end_info;
-
-	char tmp[10];
-	size_t bytes_read = stream->read(tmp, 8);
-
-	if (bytes_read != 8 && stream->err()) {
-		stream->seek(file_pointer, SEEK_SET);
-		return false;
-	}
-
-	if (png_sig_cmp((png_byte *) tmp, 0, 8)) {
-		stream->seek(file_pointer, SEEK_SET);
-		return false;
-	}
-
-	png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
-	if (!png_ptr) {
-		return false;
-	}
-
-	info_ptr = png_create_info_struct(png_ptr);
-	if (!info_ptr) {
-		png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
-		return false;
-	}
-
-	end_info = png_create_info_struct(png_ptr);
-	if (!end_info) {
-		png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
-		return false;
-	}
-	png_init_io(png_ptr, stream);       // Tell libpng which file to read
-	png_set_sig_bytes(png_ptr, 8);// 8 bytes already read
-
-	png_read_info(png_ptr, info_ptr);
-
-	png_uint_32 width, height;
-	int bit_depth, color_type, interlace_type, compression_type, filter_method;
-	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
-
-	picWidth = realPicWidth = width;
-	picHeight = realPicHeight = height;
-
-	if (bit_depth < 8) png_set_packing(png_ptr);
-	png_set_expand(png_ptr);
-	if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr);
-	if (bit_depth == 16) png_set_strip_16(png_ptr);
-
-	png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER);
-
-	png_read_update_info(png_ptr, info_ptr);
-	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
-
-	if (reserve) {
-		if (!resizeBackdrop(realPicWidth, realPicHeight)) return false;
-	}
-
-	unsigned char *row_pointers[realPicHeight];
-
-	for (int i = 0; i < realPicHeight; i++)
-	row_pointers[i] = loadhere + 4 * i * picWidth;
-
-	png_read_image(png_ptr, (png_byte **) row_pointers);
-	png_read_end(png_ptr, NULL);
-	png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
-#endif
-}
-
-bool loadByteArray(int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, bool reserve) {
-	debug(kSludgeDebugGraphics, "Loading back drop as a byte array at file position: %i", stream->pos());
-	ByteArrayDecoder byteDecoder;
-	if (!byteDecoder.loadStream(*stream)) {
-		debug(kSludgeDebugGraphics, "Back drop is not a byte array");
-		return false;
-	}
-	backdropSurface.copyFrom(*(byteDecoder.getSurface()));
-	picWidth = realPicWidth = backdropSurface.w;
-	picHeight = realPicHeight = backdropSurface.h;
-	return true;
-#if 0
-	int32_t transCol = reserve ? -1 : 63519;
-	int t1, t2, n;
-	unsigned short c;
-	picWidth = realPicWidth = stream->readUint16BE();
-	picHeight = realPicHeight = stream->readUint16BE();
-
-	if (reserve) {
-		if (!resizeBackdrop(realPicWidth, realPicHeight)) return false;
-	}
-
-	for (t2 = 0; t2 < realPicHeight; t2 ++) {
-		t1 = 0;
-		while (t1 < realPicWidth) {
-			c = (unsigned short)stream->readUint16BE();
-			if (c & 32) {
-				n = stream->readByte() + 1;
-				c -= 32;
-			} else {
-				n = 1;
-			}
-			while (n --) {
-				GLubyte *target = loadhere + 4 * picWidth * t2 + t1 * 4;
-				if (c == transCol || c == 2015) {
-					target[0] = (GLubyte)0;
-					target[1] = (GLubyte)0;
-					target[2] = (GLubyte)0;
-					target[3] = (GLubyte)0;
-				} else {
-					target[0] = (GLubyte)redValue(c);
-					target[1] = (GLubyte)greenValue(c);
-					target[2] = (GLubyte)blueValue(c);
-					target[3] = (GLubyte)255;
-				}
-				t1++;
-			}
-		}
-	}
-#endif
-}
-
-bool loadImage(int &picWidth, int &picHeight, int &realPicWidth, int &realPicHeight, Common::SeekableReadStream *stream, int x, int y, bool reserve) {
-	debug(kSludgeDebugGraphics, "Loading back drop image at file position: %i", stream->pos());
-	int32 start_ptr = stream->pos();
-	if (!loadPng(picWidth, picHeight, realPicWidth, realPicHeight, stream, reserve)) {
-		stream->seek(start_ptr);
-		if (!loadByteArray(picWidth, picHeight, realPicWidth, realPicHeight, stream, reserve)) {
-			debug(kSludgeDebugGraphics, "Back drop loading failed");
-			return false;
-		}
-	}
-
-	if (x == IN_THE_CENTRE)
-		x = (sceneWidth - realPicWidth) >> 1;
-	if (y == IN_THE_CENTRE)
-		y = (sceneHeight - realPicHeight) >> 1;
-	if (x < 0 || x + realPicWidth > sceneWidth || y < 0
-			|| y + realPicHeight > sceneHeight) {
-		debug(kSludgeDebugGraphics, "Illegal back drop size");
-		return false;
-	}
-	return true;
-}
-
 #if 0
 void makeGlArray(GLuint &tmpTex, const GLubyte *texture, int picWidth, int picHeight) {
 	glGenTextures(1, &tmpTex);
@@ -1294,12 +926,29 @@ void renderToTexture(GLuint tmpTex, int x, int y, int picWidth, int picHeight, i
 #endif
 bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 	debug(kSludgeDebugGraphics, "Load HSI");
-	int picWidth, picHeight;
-	int realPicWidth, realPicHeight;
+	if (reserve) {
+		killAllBackDrop(); // kill all
+	}
+
+	if (!ImgLoader::loadImage(stream, &backdropSurface, reserve))
+		return false;
+
+	int realPicWidth = backdropSurface.w;
+	int realPicHeight = backdropSurface.h;
+
+	if (reserve) { // resize backdrop
+		if (!resizeBackdrop(realPicWidth, realPicHeight)) return false;
+	}
 
-	if (!loadImage(picWidth, picHeight, realPicWidth, realPicHeight, stream, x,
-			y, reserve))
+	if (x == IN_THE_CENTRE)
+		x = (sceneWidth - realPicWidth) >> 1;
+	if (y == IN_THE_CENTRE)
+		y = (sceneHeight - realPicHeight) >> 1;
+	if (x < 0 || x + realPicWidth > sceneWidth || y < 0
+			|| y + realPicHeight > sceneHeight) {
+		debug(kSludgeDebugGraphics, "Illegal back drop size");
 		return false;
+	}
 #if 0
 	GLuint tmpTex;
 	makeGlArray(tmpTex, backdropTexture, picWidth, picHeight);
@@ -1314,80 +963,17 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 }
 
 bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
-#if 0
-	int realPicWidth, realPicHeight;
-	int picWidth;
-	int picHeight;
-
-	long file_pointer = stream->pos();
-
-	png_structp png_ptr;
-	png_infop info_ptr, end_info;
-
-	int fileIsPNG = true;
-
-	// Is this a PNG file?
-	char tmp[10];
-	size_t bytes_read = stream->read(tmp, 8);
-	if (bytes_read != 8 && stream->err()) {
-		debugOut("Reading error in mixHSI.\n");
-	}
-	if (png_sig_cmp((png_byte *) tmp, 0, 8)) {
-		// No, it's old-school HSI
-		fileIsPNG = false;
-		stream->seek(file_pointer, SEEK_SET);
-
-		picWidth = realPicWidth = stream->readUint16BE();
-		picHeight = realPicHeight = stream->readUint16BE();
-	} else {
-		// Read the PNG header
-
-		png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
-		if (!png_ptr) {
-			return false;
-		}
-
-		info_ptr = png_create_info_struct(png_ptr);
-		if (!info_ptr) {
-			png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
-			return false;
-		}
-
-		end_info = png_create_info_struct(png_ptr);
-		if (!end_info) {
-			png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
-			return false;
-		}
-		png_init_io(png_ptr, stream);       // Tell libpng which file to read
-		png_set_sig_bytes(png_ptr, 8);// 8 bytes already read
-
-		png_read_info(png_ptr, info_ptr);
-
-		png_uint_32 width, height;
-		int bit_depth, color_type, interlace_type, compression_type, filter_method;
-		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
-
-		picWidth = realPicWidth = width;
-		picHeight = realPicHeight = height;
-
-		if (bit_depth < 8) png_set_packing(png_ptr);
-		png_set_expand(png_ptr);
-		if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr);
-		if (bit_depth == 16) png_set_strip_16(png_ptr);
-
-		png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER);
-
-		png_read_update_info(png_ptr, info_ptr);
-		png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
-
-		//int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
+	debug(kSludgeDebugGraphics, "Load mixHSI");
+	if (!ImgLoader::loadImage(stream, &backdropSurface, false))
+		return false;
 
-	}
+	int realPicWidth = backdropSurface.w;
+	int realPicHeight = backdropSurface.h;
 
 	if (x == IN_THE_CENTRE) x = (sceneWidth - realPicWidth) >> 1;
 	if (y == IN_THE_CENTRE) y = (sceneHeight - realPicHeight) >> 1;
 	if (x < 0 || x + realPicWidth > sceneWidth || y < 0 || y + realPicHeight > sceneHeight) return false;
-
+#if 0
 	float btx1, tx1;
 	float btx2, tx2;
 	float bty1, ty1;
@@ -1429,66 +1015,8 @@ bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 		btx2, bty2
 	};
 
-	int t1, t2, n;
-	unsigned short c;
-	GLubyte *target;
-	int32_t transCol = 63519;
-
-	if (fileIsPNG) {
-		unsigned char *row_pointers[realPicHeight];
-		for (int i = 0; i < realPicHeight; i++)
-		row_pointers[i] = backdropTexture + 4 * i * picWidth;
-
-		png_read_image(png_ptr, (png_byte **) row_pointers);
-		png_read_end(png_ptr, NULL);
-		png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
-	} else {
-		for (t2 = 0; t2 < realPicHeight; t2 ++) {
-			t1 = 0;
-			while (t1 < realPicWidth) {
-				c = (unsigned short)stream->readUint16BE();
-				if (c & 32) {
-					n = stream->readByte() + 1;
-					c -= 32;
-				} else {
-					n = 1;
-				}
-				while (n --) {
-					target = backdropTexture + 4 * picWidth * t2 + t1 * 4;
-					if (c == transCol || c == 2015) {
-						target[0] = (GLubyte) 0;
-						target[1] = (GLubyte) 0;
-						target[2] = (GLubyte) 0;
-						target[3] = (GLubyte) 0;
-					} else {
-						target[0] = (GLubyte) redValue(c);
-						target[1] = (GLubyte) greenValue(c);
-						target[2] = (GLubyte) blueValue(c);
-						target[3] = (GLubyte) 255;
-					}
-					t1++;
-				}
-			}
-		}
-	}
-
 	GLuint tmpTex;
-
-	glGenTextures(1, &tmpTex);
-	glBindTexture(GL_TEXTURE_2D, tmpTex);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-	if (gameSettings.antiAlias < 0) {
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-	} else {
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-	}
-
-	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, backdropTexture, tmpTex);
-
-	//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
+	makeGlArray(tmpTex, backdropTexture, picWidth, picHeight);
 
 	setPixelCoords(true);
 
diff --git a/engines/sludge/backdrop.h b/engines/sludge/backdrop.h
index 9b0832a..3a88d33 100644
--- a/engines/sludge/backdrop.h
+++ b/engines/sludge/backdrop.h
@@ -51,6 +51,7 @@ struct parallaxLayer {
 	GLubyte *texture;
 	GLuint textureName;
 #endif
+	Graphics::Surface surface;
 	int width, height, speedX, speedY;
 	bool wrapS, wrapT;
 	unsigned short fileNum, fractionX, fractionY;
@@ -59,7 +60,9 @@ struct parallaxLayer {
 	parallaxLayer *prev;
 };
 
+void killAllBackDrop();
 bool resizeBackdrop(int x, int y);
+bool killResizeBackdrop(int x, int y);
 void killBackDrop();
 void loadBackDrop(int fileNum, int x, int y);
 void mixBackDrop(int fileNum, int x, int y);
@@ -82,9 +85,7 @@ bool getRGBIntoStack(unsigned int x, unsigned int y, stackHandler *sH);
 void killLightMap();
 bool loadLightMap(int v);
 
-#if 0
 extern texture lightMap;
-#endif
 
 // And background parallax scrolling
 
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index f35a2bd..5eb52f9 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -441,7 +441,7 @@ builtIn(setSceneDimensions) {
 	trimStack(fun->stack);
 	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
 	trimStack(fun->stack);
-	if (resizeBackdrop(x, y)) {
+	if (killResizeBackdrop(x, y)) {
 		blankScreen(0, 0, x, y);
 		return BR_CONTINUE;
 	}
diff --git a/engines/sludge/bytearray.cpp b/engines/sludge/bytearray.cpp
deleted file mode 100644
index 0b28a02..0000000
--- a/engines/sludge/bytearray.cpp
+++ /dev/null
@@ -1,90 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-
-#include "common/stream.h"
-#include "common/debug.h"
-#include "graphics/surface.h"
-
-#include "allfiles.h"
-#include "bytearray.h"
-#include "colours.h"
-#include "sludge.h"
-
-namespace Sludge {
-
-ByteArrayDecoder::ByteArrayDecoder() : _surface(nullptr) {
-}
-
-ByteArrayDecoder::~ByteArrayDecoder() {
-	destroy();
-}
-
-void ByteArrayDecoder::destroy() {
-	if (_surface != nullptr) {
-		_surface->free();
-		delete _surface;
-		_surface = nullptr;
-	}
-}
-
-bool ByteArrayDecoder::loadStream(Common::SeekableReadStream &stream) {
-	destroy();
-	int32_t transCol = /*reserve ? -1 : */63519;
-	int n;
-	uint16 width = stream.readUint16BE();
-	debug(kSludgeDebugGraphics, "picWidth : %i", width);
-	uint16 height = stream.readUint16BE();
-	debug(kSludgeDebugGraphics, "picHeight : %i", height);
-
-	_surface = new Graphics::Surface();
-	_surface->create(width, height, Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0));
-	for (uint16 y = 0; y < height; y++) {
-		uint16 x = 0;
-		while (x < width) {
-			unsigned short c = (unsigned short)stream.readUint16BE();
-			if (c & 32) {
-				n = stream.readByte() + 1;
-				c -= 32;
-			} else {
-				n = 1;
-			}
-			while (n--) {
-				byte *target = (byte *)_surface->getBasePtr(x, y);
-				if (c == transCol || c == 2015) {
-					target[0] = (byte)0;
-					target[1] = (byte)0;
-					target[2] = (byte)0;
-					target[3] = (byte)0;
-				} else {
-					target[0] = (byte)255;
-					target[1] = (byte)blueValue(c);
-					target[2] = (byte)greenValue(c);
-					target[3] = (byte)redValue(c);
-				}
-				x++;
-			}
-		}
-	}
-	return true;
-}
-
-} // End of namespace Sludge
diff --git a/engines/sludge/bytearray.h b/engines/sludge/bytearray.h
deleted file mode 100644
index 22bcc76..0000000
--- a/engines/sludge/bytearray.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef PRINCE_MHWANH_H
-#define PRINCE_MHWANH_H
-
-#include "image/image_decoder.h"
-#include "graphics/surface.h"
-
-namespace Sludge {
-
-class ByteArrayDecoder : public Image::ImageDecoder {
-
-public:
-	ByteArrayDecoder();
-	virtual ~ByteArrayDecoder();
-
-	// ImageDecoder API
-	void destroy();
-	virtual bool loadStream(Common::SeekableReadStream &stream);
-	virtual Graphics::Surface *getSurface() const { return _surface; }
-
-private:
-	Graphics::Surface *_surface;
-};
-
-} // End of namespace Sludge
-
-#endif
diff --git a/engines/sludge/freeze.cpp b/engines/sludge/freeze.cpp
index 7057f6e..0d797b2 100644
--- a/engines/sludge/freeze.cpp
+++ b/engines/sludge/freeze.cpp
@@ -191,7 +191,7 @@ bool freeze() {
 	zBuffer.tex = NULL;
 #endif
 	// resizeBackdrop kills parallax stuff, light map, z-buffer...
-	if (!resizeBackdrop(winWidth, winHeight))
+	if (!killResizeBackdrop(winWidth, winHeight))
 		return fatal("Can't create new temporary backdrop buffer");
 
 	if (!NPOT_textures) {
diff --git a/engines/sludge/graphics.h b/engines/sludge/graphics.h
index 493e6f1..ba23d72 100644
--- a/engines/sludge/graphics.h
+++ b/engines/sludge/graphics.h
@@ -31,6 +31,8 @@
 #endif
 #endif
 
+#include "graphics/surface.h"
+
 namespace Sludge {
 
 struct texture {
@@ -38,7 +40,7 @@ struct texture {
 	GLubyte *data;
 	GLuint name;
 #endif
-	int w, h;
+	Graphics::Surface surface;
 	double texW, texH;
 };
 
diff --git a/engines/sludge/imgloader.cpp b/engines/sludge/imgloader.cpp
new file mode 100644
index 0000000..48617f1f
--- /dev/null
+++ b/engines/sludge/imgloader.cpp
@@ -0,0 +1,138 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#include "common/debug.h"
+#include "common/stream.h"
+#include "image/png.h"
+#include "graphics/surface.h"
+
+#include "allfiles.h"
+#include "imgloader.h"
+#include "colours.h"
+#include "sludge.h"
+
+namespace Sludge {
+
+bool ImgLoader::loadImage(Common::SeekableReadStream *stream, Graphics::Surface *dest, bool reserve) {
+	debug("Loading image at position: %i", stream->pos());
+	int32 start_ptr = stream->pos();
+	if (!loadPNGImage(stream, dest)) {
+		stream->seek(start_ptr);
+		if (!loadReserveImage(stream, dest, reserve)) {
+			return false;
+		}
+	}
+	return true;
+}
+
+bool ImgLoader::loadImage(Common::SeekableReadStream *stream, Graphics::Surface *dest) {
+	debug("Loading image at position: %i", stream->pos());
+	int32 start_ptr = stream->pos();
+	if (!loadPNGImage(stream, dest)) {
+		stream->seek(start_ptr);
+		if (!loadOtherImage(stream, dest)) {
+			return false;
+		}
+	}
+	return true;
+}
+
+bool ImgLoader::loadPNGImage(Common::SeekableReadStream *stream, Graphics::Surface *dest) {
+	::Image::PNGDecoder png;
+	if (!png.loadStream(*stream))
+		return false;
+	const Graphics::Surface *sourceSurface = png.getSurface();
+	Graphics::Surface *pngSurface = sourceSurface->convertTo(Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0), png.getPalette());
+	dest->copyFrom(*pngSurface);
+	pngSurface->free();
+	delete pngSurface;
+	return true;
+}
+
+bool ImgLoader::loadReserveImage(Common::SeekableReadStream *stream, Graphics::Surface *dest, int reserve) {
+	debug("Loading image at position: %i", stream->pos());
+	int32_t transCol = reserve ? -1 : 63519;
+	int n;
+	uint16 width = stream->readUint16BE();
+	uint16 height = stream->readUint16BE();
+
+	dest->create(width, height, Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0));
+	for (uint16 y = 0; y < height; y++) {
+		uint16 x = 0;
+		while (x < width) {
+			unsigned short c = (unsigned short)stream->readUint16BE();
+			if (c & 32) {
+				n = stream->readByte() + 1;
+				c -= 32;
+			} else {
+				n = 1;
+			}
+			while (n--) {
+				byte *target = (byte *)dest->getBasePtr(x, y);
+				if (c == transCol || c == 2015) {
+					target[0] = (byte)0;
+					target[1] = (byte)0;
+					target[2] = (byte)0;
+					target[3] = (byte)0;
+				} else {
+					target[0] = (byte)255;
+					target[1] = (byte)blueValue(c);
+					target[2] = (byte)greenValue(c);
+					target[3] = (byte)redValue(c);
+				}
+				x++;
+			}
+		}
+	}
+	return true;
+}
+
+bool ImgLoader::loadOtherImage(Common::SeekableReadStream *stream, Graphics::Surface *dest) {
+	int n;
+	uint16 width = stream->readUint16BE();
+	uint16 height = stream->readUint16BE();
+
+	dest->create(width, height, Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0));
+	for (uint16 y = 0; y < height; y++) {
+		uint16 x = 0;
+		while (x < width) {
+			unsigned short c = (unsigned short)stream->readUint16BE();
+			if (c & 32) {
+				n = stream->readByte() + 1;
+				c -= 32;
+			} else {
+				n = 1;
+			}
+			while (n--) {
+				byte *target = (byte *)dest->getBasePtr(x, y);
+				target[0] = (byte)255;
+				target[1] = (byte)blueValue(c);
+				target[2] = (byte)greenValue(c);
+				target[3] = (byte)redValue(c);
+				x++;
+			}
+		}
+	}
+	return true;
+}
+
+} // End of namespace Sludge
diff --git a/engines/sludge/imgloader.h b/engines/sludge/imgloader.h
new file mode 100644
index 0000000..2f4d9ee
--- /dev/null
+++ b/engines/sludge/imgloader.h
@@ -0,0 +1,44 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef SLUDGE_IMGLOADER_H
+#define SLUDGE_IMGLOADER_H
+
+#include "common/file.h"
+
+namespace Sludge {
+
+class ImgLoader {
+protected:
+	ImgLoader() {}
+
+public:
+	static bool loadImage(Common::SeekableReadStream *stream, Graphics::Surface *dest);
+	static bool loadImage(Common::SeekableReadStream *stream, Graphics::Surface *dest, bool reserve);
+	static bool loadPNGImage(Common::SeekableReadStream *stream, Graphics::Surface *dest);
+	static bool loadReserveImage(Common::SeekableReadStream *stream, Graphics::Surface *dest, int reserve);
+	static bool loadOtherImage(Common::SeekableReadStream *stream, Graphics::Surface *dest);
+};
+
+} // End of namespace Sludge
+
+#endif
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index cf0c7f3..2c4648b 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -432,7 +432,7 @@ int main_loop(char *filename)
 
 	registerWindowForFatal();
 
-	if (!resizeBackdrop(winWidth, winHeight))
+	if (!killResizeBackdrop(winWidth, winHeight))
 		return fatal("Couldn't allocate memory for backdrop");
 
 	blankScreen(0, 0, winWidth, winHeight);
diff --git a/engines/sludge/module.mk b/engines/sludge/module.mk
index 5e62f5a..0bba16f 100644
--- a/engines/sludge/module.mk
+++ b/engines/sludge/module.mk
@@ -4,7 +4,6 @@ MODULE_OBJS := \
 	backdrop.o \
 	bg_effects.o \
 	builtin.o \
-	bytearray.o \
 	console.o \
 	cursors.o \
 	debug.o \
@@ -15,6 +14,7 @@ MODULE_OBJS := \
 	fonttext.o \
 	graphics.o \
 	helpers.o \
+	imgloader.o \
 	language.o \
 	line.o \
 	loadsave.o \


Commit: cfe2e637937321f2a634e1b016622a0fb8e2582d
    https://github.com/scummvm/scummvm/commit/cfe2e637937321f2a634e1b016622a0fb8e2582d
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: refactor HSIDecoder out of Imgloader

Changed paths:
  A engines/sludge/hsi.cpp
  A engines/sludge/hsi.h
    engines/sludge/backdrop.cpp
    engines/sludge/backdrop.h
    engines/sludge/imgloader.cpp
    engines/sludge/imgloader.h
    engines/sludge/module.mk


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index 35159d0..a6cf71f 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -19,22 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#if 0
-#if defined __unix__ && !(defined __APPLE__)
-#include <png.h>
-#else
-#include <libpng/png.h>
-#endif
-
-#include <stdlib.h>
-#include <stdint.h>
-
-#if !defined(HAVE_GLES2)
-#include "GLee.h"
-#else
-#include <GLES2/gl2.h>
-#endif
-#endif
 
 #include "allfiles.h"
 #include "debug.h"
@@ -742,7 +726,7 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 	int picWidth;
 	int picHeight;
 
-	if (!ImgLoader::loadImage(bigDataFile, &nP->surface, false))
+	if (!ImgLoader::loadImage(bigDataFile, &nP->surface, 0))
 		return false;
 
 	if (!NPOT_textures) {
@@ -930,7 +914,7 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 		killAllBackDrop(); // kill all
 	}
 
-	if (!ImgLoader::loadImage(stream, &backdropSurface, reserve))
+	if (!ImgLoader::loadImage(stream, &backdropSurface, (int)reserve))
 		return false;
 
 	int realPicWidth = backdropSurface.w;
@@ -964,7 +948,7 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 
 bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 	debug(kSludgeDebugGraphics, "Load mixHSI");
-	if (!ImgLoader::loadImage(stream, &backdropSurface, false))
+	if (!ImgLoader::loadImage(stream, &backdropSurface, 0))
 		return false;
 
 	int realPicWidth = backdropSurface.w;
diff --git a/engines/sludge/backdrop.h b/engines/sludge/backdrop.h
index 3a88d33..01f21b0 100644
--- a/engines/sludge/backdrop.h
+++ b/engines/sludge/backdrop.h
@@ -23,14 +23,6 @@
 #ifndef SLUDGE_BACKDROP_H
 #define SLUDGE_BACKDROP_H
 
-#if 0
-#if !defined(HAVE_GLES2)
-#include "GLee.h"
-#else
-#include <GLES2/gl2.h>
-#endif
-#endif
-
 #include "variable.h"
 #include "graphics.h"
 
@@ -47,10 +39,6 @@ extern unsigned int winWidth, winHeight, sceneWidth, sceneHeight;
 extern int lightMapMode;
 
 struct parallaxLayer {
-#if 0
-	GLubyte *texture;
-	GLuint textureName;
-#endif
 	Graphics::Surface surface;
 	int width, height, speedX, speedY;
 	bool wrapS, wrapT;
diff --git a/engines/sludge/hsi.cpp b/engines/sludge/hsi.cpp
new file mode 100644
index 0000000..5281ff7
--- /dev/null
+++ b/engines/sludge/hsi.cpp
@@ -0,0 +1,90 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#include "common/debug.h"
+#include "common/stream.h"
+
+#include "graphics/surface.h"
+
+#include "colours.h"
+#include "hsi.h"
+#include "sludge.h"
+
+namespace Sludge {
+
+HSIDecoder::HSIDecoder() : _surface(nullptr), _reserve(-1) {
+}
+
+HSIDecoder::~HSIDecoder() {
+	destroy();
+}
+
+void HSIDecoder::destroy() {
+	if (_surface != nullptr) {
+		_surface->free();
+		delete _surface;
+		_surface = nullptr;
+	}
+}
+
+bool HSIDecoder::loadStream(Common::SeekableReadStream &stream) {
+	destroy();
+	int32_t transCol = _reserve > 0 ? -1 : 63519;
+	int n;
+	uint16 width = stream.readUint16BE();
+	debug(kSludgeDebugGraphics, "picWidth : %i", width);
+	uint16 height = stream.readUint16BE();
+	debug(kSludgeDebugGraphics, "picHeight : %i", height);
+
+	_surface = new Graphics::Surface();
+	_surface->create(width, height, Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0));
+	for (uint16 y = 0; y < height; y++) {
+		uint16 x = 0;
+		while (x < width) {
+			unsigned short c = (unsigned short)stream.readUint16BE();
+			if (c & 32) {
+				n = stream.readByte() + 1;
+				c -= 32;
+			} else {
+				n = 1;
+			}
+			while (n--) {
+				byte *target = (byte *)_surface->getBasePtr(x, y);
+				if (_reserve != -1 && (c == transCol || c == 2015)) {
+					target[0] = (byte)0;
+					target[1] = (byte)0;
+					target[2] = (byte)0;
+					target[3] = (byte)0;
+				} else {
+					target[0] = (byte)255;
+					target[1] = (byte)blueValue(c);
+					target[2] = (byte)greenValue(c);
+					target[3] = (byte)redValue(c);
+				}
+				x++;
+			}
+		}
+	}
+	return true;
+}
+
+} // End of namespace Sludge
diff --git a/engines/sludge/hsi.h b/engines/sludge/hsi.h
new file mode 100644
index 0000000..a1bef30
--- /dev/null
+++ b/engines/sludge/hsi.h
@@ -0,0 +1,49 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#ifndef SLUDGE_HSI_H
+#define SLUDGE_HSI_H
+
+#include "image/image_decoder.h"
+
+#include "graphics/surface.h"
+
+namespace Sludge {
+
+class HSIDecoder : public Image::ImageDecoder {
+public:
+	HSIDecoder();
+	virtual ~HSIDecoder();
+
+	// ImageDecoder API
+	void destroy();
+	virtual bool loadStream(Common::SeekableReadStream &stream);
+	virtual Graphics::Surface *getSurface() const { return _surface; }
+	void setReserve(bool reserve) { _reserve = reserve; }
+
+private:
+	Graphics::Surface *_surface;
+	int _reserve;
+};
+
+} // End of namespace Sludge
+
+#endif
diff --git a/engines/sludge/imgloader.cpp b/engines/sludge/imgloader.cpp
index 48617f1f..f76c7b6 100644
--- a/engines/sludge/imgloader.cpp
+++ b/engines/sludge/imgloader.cpp
@@ -26,30 +26,19 @@
 #include "graphics/surface.h"
 
 #include "allfiles.h"
+#include "hsi.h"
 #include "imgloader.h"
 #include "colours.h"
 #include "sludge.h"
 
 namespace Sludge {
 
-bool ImgLoader::loadImage(Common::SeekableReadStream *stream, Graphics::Surface *dest, bool reserve) {
-	debug("Loading image at position: %i", stream->pos());
+bool ImgLoader::loadImage(Common::SeekableReadStream *stream, Graphics::Surface *dest, int reserve) {
+	debug(kSludgeDebugDataLoad, "Loading image at position: %i", stream->pos());
 	int32 start_ptr = stream->pos();
 	if (!loadPNGImage(stream, dest)) {
 		stream->seek(start_ptr);
-		if (!loadReserveImage(stream, dest, reserve)) {
-			return false;
-		}
-	}
-	return true;
-}
-
-bool ImgLoader::loadImage(Common::SeekableReadStream *stream, Graphics::Surface *dest) {
-	debug("Loading image at position: %i", stream->pos());
-	int32 start_ptr = stream->pos();
-	if (!loadPNGImage(stream, dest)) {
-		stream->seek(start_ptr);
-		if (!loadOtherImage(stream, dest)) {
+		if (!loadHSIImage(stream, dest, reserve)) {
 			return false;
 		}
 	}
@@ -68,70 +57,13 @@ bool ImgLoader::loadPNGImage(Common::SeekableReadStream *stream, Graphics::Surfa
 	return true;
 }
 
-bool ImgLoader::loadReserveImage(Common::SeekableReadStream *stream, Graphics::Surface *dest, int reserve) {
-	debug("Loading image at position: %i", stream->pos());
-	int32_t transCol = reserve ? -1 : 63519;
-	int n;
-	uint16 width = stream->readUint16BE();
-	uint16 height = stream->readUint16BE();
-
-	dest->create(width, height, Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0));
-	for (uint16 y = 0; y < height; y++) {
-		uint16 x = 0;
-		while (x < width) {
-			unsigned short c = (unsigned short)stream->readUint16BE();
-			if (c & 32) {
-				n = stream->readByte() + 1;
-				c -= 32;
-			} else {
-				n = 1;
-			}
-			while (n--) {
-				byte *target = (byte *)dest->getBasePtr(x, y);
-				if (c == transCol || c == 2015) {
-					target[0] = (byte)0;
-					target[1] = (byte)0;
-					target[2] = (byte)0;
-					target[3] = (byte)0;
-				} else {
-					target[0] = (byte)255;
-					target[1] = (byte)blueValue(c);
-					target[2] = (byte)greenValue(c);
-					target[3] = (byte)redValue(c);
-				}
-				x++;
-			}
-		}
-	}
-	return true;
-}
-
-bool ImgLoader::loadOtherImage(Common::SeekableReadStream *stream, Graphics::Surface *dest) {
-	int n;
-	uint16 width = stream->readUint16BE();
-	uint16 height = stream->readUint16BE();
-
-	dest->create(width, height, Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0));
-	for (uint16 y = 0; y < height; y++) {
-		uint16 x = 0;
-		while (x < width) {
-			unsigned short c = (unsigned short)stream->readUint16BE();
-			if (c & 32) {
-				n = stream->readByte() + 1;
-				c -= 32;
-			} else {
-				n = 1;
-			}
-			while (n--) {
-				byte *target = (byte *)dest->getBasePtr(x, y);
-				target[0] = (byte)255;
-				target[1] = (byte)blueValue(c);
-				target[2] = (byte)greenValue(c);
-				target[3] = (byte)redValue(c);
-				x++;
-			}
-		}
+bool ImgLoader::loadHSIImage(Common::SeekableReadStream *stream, Graphics::Surface *dest, int reserve) {
+	HSIDecoder hsiDecoder;
+	hsiDecoder.setReserve(reserve);
+	if (!hsiDecoder.loadStream(*stream)) {
+		return false;
 	}
+	dest->copyFrom(*(hsiDecoder.getSurface()));
 	return true;
 }
 
diff --git a/engines/sludge/imgloader.h b/engines/sludge/imgloader.h
index 2f4d9ee..35529f5 100644
--- a/engines/sludge/imgloader.h
+++ b/engines/sludge/imgloader.h
@@ -32,11 +32,9 @@ protected:
 	ImgLoader() {}
 
 public:
-	static bool loadImage(Common::SeekableReadStream *stream, Graphics::Surface *dest);
-	static bool loadImage(Common::SeekableReadStream *stream, Graphics::Surface *dest, bool reserve);
+	static bool loadImage(Common::SeekableReadStream *stream, Graphics::Surface *dest, int reserve = -1);
 	static bool loadPNGImage(Common::SeekableReadStream *stream, Graphics::Surface *dest);
-	static bool loadReserveImage(Common::SeekableReadStream *stream, Graphics::Surface *dest, int reserve);
-	static bool loadOtherImage(Common::SeekableReadStream *stream, Graphics::Surface *dest);
+	static bool loadHSIImage(Common::SeekableReadStream *stream, Graphics::Surface *dest, int reserve = -1);
 };
 
 } // End of namespace Sludge
diff --git a/engines/sludge/module.mk b/engines/sludge/module.mk
index 0bba16f..726cd6b 100644
--- a/engines/sludge/module.mk
+++ b/engines/sludge/module.mk
@@ -14,6 +14,7 @@ MODULE_OBJS := \
 	fonttext.o \
 	graphics.o \
 	helpers.o \
+	hsi.o \
 	imgloader.o \
 	language.o \
 	line.o \


Commit: cd42e483ded980b66b5dad230418915140cfdd00
    https://github.com/scummvm/scummvm/commit/cd42e483ded980b66b5dad230418915140cfdd00
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: complete sprite loading

Changed paths:
    engines/sludge/fonttext.cpp
    engines/sludge/sprites.cpp
    engines/sludge/sprites.h


diff --git a/engines/sludge/fonttext.cpp b/engines/sludge/fonttext.cpp
index 7339d8f..505078d 100644
--- a/engines/sludge/fonttext.cpp
+++ b/engines/sludge/fonttext.cpp
@@ -80,7 +80,7 @@ int stringWidth(char *theText) {
 
 	while (theText[a]) {
 		c = u8_nextchar(theText, &a);
-		xOff += theFont.sprites[fontInTable(c)].width + fontSpace;
+		xOff += theFont.sprites[fontInTable(c)].surface.w + fontSpace;
 	}
 
 	return xOff;
@@ -99,7 +99,7 @@ void pasteString(char *theText, int xOff, int y, spritePalette &thePal) {
 		c = u8_nextchar(theText, &a);
 		mySprite = &theFont.sprites[fontInTable(c)];
 		fontSprite(xOff, y, *mySprite, thePal);
-		xOff += (int) ((double) (mySprite->width + fontSpace) / cameraZoom);
+		xOff += (int) ((double) (mySprite->surface.w + fontSpace) / cameraZoom);
 	}
 }
 
@@ -117,7 +117,7 @@ void pasteStringToBackdrop(char *theText, int xOff, int y,
 		c = u8_nextchar(theText, &a);
 		mySprite = &theFont.sprites[fontInTable(c)];
 		pasteSpriteToBackDrop(xOff, y, *mySprite, thePal);
-		xOff += mySprite->width + fontSpace;
+		xOff += mySprite->surface.w + fontSpace;
 	}
 }
 
@@ -135,7 +135,7 @@ void burnStringToBackdrop(char *theText, int xOff, int y,
 		c = u8_nextchar(theText, &a);
 		mySprite = &theFont.sprites[fontInTable(c)];
 		burnSpriteToBackDrop(xOff, y, *mySprite, thePal);
-		xOff += mySprite->width + fontSpace;
+		xOff += mySprite->surface.w + fontSpace;
 	}
 }
 
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index 069d97f..c62c31a 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -19,16 +19,9 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#if 0
-#if defined __unix__ && !(defined __APPLE__)
-#include <png.h>
-#else
-#include <libpng/png.h>
-#endif
-#endif
 
+#include "graphics/surface.h"
 #include "allfiles.h"
-
 #include "fileset.h"
 #include "people.h"
 #include "sprites.h"
@@ -40,7 +33,7 @@
 #include "zbuffer.h"
 #include "debug.h"
 #include "graphics.h"
-
+#include "imgloader.h"
 #include "shaders.h"
 
 namespace Sludge {
@@ -68,12 +61,11 @@ void forgetSpriteBank(spriteBank &forgetme) {
 
 	delete [] forgetme.myPalette.tex_names;
 	forgetme.myPalette.tex_names = NULL;
-#endif
 	delete[] forgetme.myPalette.tex_w;
 	forgetme.myPalette.tex_w = NULL;
 	delete[] forgetme.myPalette.tex_h;
 	forgetme.myPalette.tex_h = NULL;
-
+#endif
 	if (forgetme.myPalette.pal) {
 		delete[] forgetme.myPalette.pal;
 		forgetme.myPalette.pal = NULL;
@@ -119,20 +111,18 @@ bool reserveSpritePal(spritePalette &sP, int n) {
 }
 
 bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
-#if 0
-	int i, tex_num, total, picwidth, picheight, spriteBankVersion = 0, howmany = 0, startIndex = 0;
-	int *totalwidth, * maxheight;
-	int numTextures = 0;
+
+	int total, picwidth, picheight, spriteBankVersion = 0, howmany = 0, startIndex = 0;
 	byte *data;
 
 	setResourceForFatal(fileNum);
-	if (! openFileFromNum(fileNum)) return fatal("Can't open sprite bank / font");
+	if (!openFileFromNum(fileNum)) return fatal("Can't open sprite bank / font");
 
 	loadhere.isFont = isFont;
 
 	total = bigDataFile->readUint16BE();
-	if (! total) {
-		spriteBankVersion = fgetc(bigDataFile);
+	if (!total) {
+		spriteBankVersion = bigDataFile->readByte();
 		if (spriteBankVersion == 1) {
 			total = 0;
 		} else {
@@ -149,236 +139,133 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 	byte **spriteData = new byte * [total];
 	if (! checkNew(spriteData)) return false;
 
-	totalwidth = new int[total];
-	if (! checkNew(totalwidth)) return false;
-
-	maxheight = new int[total];
-	if (! checkNew(maxheight)) return false;
-
-	loadhere.myPalette.tex_names = new GLuint [total];
-	if (! checkNew(loadhere.myPalette.tex_names)) return false;
-
-	if (isFont) {
-		loadhere.myPalette.burnTex_names = new GLuint [total];
-		if (! checkNew(loadhere.myPalette.burnTex_names)) return false;
-	}
-	loadhere.myPalette.tex_w = new int [total];
-	if (! checkNew(loadhere.myPalette.tex_w)) return false;
-	loadhere.myPalette.tex_h = new int [total];
-	if (! checkNew(loadhere.myPalette.tex_h)) return false;
-
+	// version 1, 2, read how many now
 	if (spriteBankVersion && spriteBankVersion < 3) {
-		howmany = fgetc(bigDataFile);
+		howmany = bigDataFile->readByte();
 		startIndex = 1;
 	}
 
-	totalwidth[0] = maxheight[0] = 1;
-
-	for (i = 0; i < total; i ++) {
-		switch (spriteBankVersion) {
-			case 3: {
-				loadhere.sprites[i].xhot = getSigned(bigDataFile);
-				loadhere.sprites[i].yhot = getSigned(bigDataFile);
-
-				png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
-				if (!png_ptr) {
-					return fatal("Can't open sprite bank / font.");
-				}
-
-				png_infop info_ptr = png_create_info_struct(png_ptr);
-				if (!info_ptr) {
-					png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
-					return fatal("Can't open sprite bank / font.");
-				}
-
-				png_infop end_info = png_create_info_struct(png_ptr);
-				if (!end_info) {
-					png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
-					return fatal("Can't open sprite bank / font.");
-				}
-				png_init_io(png_ptr, bigDataFile); // Tell libpng which file to read
-				png_set_sig_bytes(png_ptr, 8);// No sig
-
-				png_read_info(png_ptr, info_ptr);
-
-				png_uint_32 width, height;
-				int bit_depth, color_type, interlace_type, compression_type, filter_method;
-				png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_method);
+	// version 3, sprite is png
+	if (spriteBankVersion == 3) {
+		for (int i = 0; i < total; i ++) {
+			howmany = bigDataFile->readByte();
+			startIndex = 1;
 
-				int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
-
-				unsigned char *row_pointers[height];
-				spriteData[i] = new unsigned char [rowbytes * height];
-				if (! checkNew(spriteData[i])) return false;
-
-				for (unsigned int row = 0; row < height; row++)
-				row_pointers[row] = spriteData[i] + row * rowbytes;
-
-				png_read_image(png_ptr, (png_byte **) row_pointers);
-				png_read_end(png_ptr, NULL);
-				png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
+			loadhere.sprites[i].xhot = getSigned(bigDataFile);
+			loadhere.sprites[i].yhot = getSigned(bigDataFile);
 
-				picwidth = loadhere.sprites[i].width = width;
-				picheight = loadhere.sprites[i].height = height;
-				break;
+			if (!ImgLoader::loadPNGImage(bigDataFile, &loadhere.sprites[i].surface)) {
+				return false;
 			}
-			case 2:
+		}
+		return true;
+	}
+
+	// version 0, 1, 2
+	for (int i = 0; i < total; i ++) {
+		// load sprite width, height, relative position
+		if (spriteBankVersion == 2) {
 			picwidth = bigDataFile->readUint16BE();
 			picheight = bigDataFile->readUint16BE();
 			loadhere.sprites[i].xhot = getSigned(bigDataFile);
 			loadhere.sprites[i].yhot = getSigned(bigDataFile);
-			break;
-
-			default:
-			picwidth = (byte) fgetc(bigDataFile);
-			picheight = (byte) fgetc(bigDataFile);
-			loadhere.sprites[i].xhot = fgetc(bigDataFile);
-			loadhere.sprites[i].yhot = fgetc(bigDataFile);
-			break;
-		}
-
-		if (((picwidth > 511) && (totalwidth[numTextures] + picwidth < 2047)) || ((picwidth < 511) && (totalwidth[numTextures] + picwidth < 511))) {
-			loadhere.sprites[i].tex_x = totalwidth[numTextures];
-			totalwidth[numTextures] += (loadhere.sprites[i].width = picwidth) + 1;
-			if ((loadhere.sprites[i].height = picheight) + 2 > maxheight[numTextures]) maxheight[numTextures] = picheight + 2;
 		} else {
-			numTextures++;
-			if (numTextures > 255) return fatal("Can't open sprite bank / font - it's too big.");
-			loadhere.sprites[i].tex_x = 0;
-			totalwidth[numTextures] = (loadhere.sprites[i].width = picwidth);
-			maxheight[numTextures] = loadhere.sprites[i].height = picheight;
+			picwidth = (byte)bigDataFile->readByte();
+			picheight = (byte)bigDataFile->readByte();
+			loadhere.sprites[i].xhot = bigDataFile->readByte();
+			loadhere.sprites[i].yhot = bigDataFile->readByte();
 		}
-		loadhere.sprites[i].texNum = numTextures;
-
-		if (spriteBankVersion < 3) {
-			data = (byte *) new byte [picwidth * (picheight + 1)];
-			if (! checkNew(data)) return false;
-			int ooo = picwidth * picheight;
-			for (int tt = 0; tt < picwidth; tt ++) {
-				data[ooo ++] = 0;
-			}
-			spriteData[i] = data;
-			switch (spriteBankVersion) {
-				case 2: {       // RUN LENGTH COMPRESSED DATA
-					unsigned size = picwidth * picheight;
-					unsigned pip = 0;
-
-					while (pip < size) {
-						byte col = fgetc(bigDataFile);
-						int looper;
-
-						if (col > howmany) {
-							col -= howmany + 1;
-							looper = fgetc(bigDataFile) + 1;
-						} else looper = 1;
-
-						while (looper --) {
-							data[pip ++] = col;
-						}
-					}
-				}
-				break;
 
-				default:        // RAW DATA
-				size_t bytes_read = fread(data, picwidth, picheight, bigDataFile);
-				if (bytes_read != picwidth * picheight && ferror(bigDataFile)) {
-					debugOut("Reading error in loadSpriteBank.\n");
+		// init data
+		data = (byte *)new byte[picwidth * (picheight + 1)];
+		if (!checkNew(data)) return false;
+		int ooo = picwidth * picheight;
+		for (int tt = 0; tt < picwidth; tt++) {
+			data[ooo++] = 0;
+		}
+		spriteData[i] = data;
+
+		// read color
+		if (spriteBankVersion == 2) {
+			unsigned size = picwidth * picheight;
+			unsigned pip = 0;
+
+			while (pip < size) {
+				byte col = bigDataFile->readByte();
+				int looper;
+				if (col > howmany) {
+					col -= howmany + 1;
+					looper = bigDataFile->readByte() + 1;
+				} else looper = 1;
+
+				while (looper --) {
+					data[pip ++] = col;
 				}
-				break;
+			}
+		} else { // RAW DATA
+			size_t bytes_read = bigDataFile->read(data, picwidth * picheight);
+			if (bytes_read != picwidth * picheight && bigDataFile->err()) {
+				debugOut("Reading error in loadSpriteBank.\n");
 			}
 		}
 	}
-	numTextures++;
 
-	if (! spriteBankVersion) {
-		howmany = fgetc(bigDataFile);
-		startIndex = fgetc(bigDataFile);
+	// read howmany for version 0
+	if (!spriteBankVersion) {
+		howmany = bigDataFile->readByte();
+		startIndex = bigDataFile->readByte();
 	}
 
-	if (spriteBankVersion < 3) {
-		if (! reserveSpritePal(loadhere.myPalette, howmany + startIndex)) return false;
-
-		for (i = 0; i < howmany; i ++) {
-			loadhere.myPalette.r[i + startIndex] = (byte) fgetc(bigDataFile);
-			loadhere.myPalette.g[i + startIndex] = (byte) fgetc(bigDataFile);
-			loadhere.myPalette.b[i + startIndex] = (byte) fgetc(bigDataFile);
-			loadhere.myPalette.pal[i + startIndex] = makeColour(loadhere.myPalette.r[i + startIndex], loadhere.myPalette.g[i + startIndex], loadhere.myPalette.b[i + startIndex]);
-		}
+	// Make palette for version 0, 1, 2
+	if (!reserveSpritePal(loadhere.myPalette, howmany + startIndex)) return false;
+	for (int i = 0; i < howmany; ++i) {
+		loadhere.myPalette.r[i + startIndex] = (byte)bigDataFile->readByte();
+		loadhere.myPalette.g[i + startIndex] = (byte)bigDataFile->readByte();
+		loadhere.myPalette.b[i + startIndex] = (byte)bigDataFile->readByte();
+		loadhere.myPalette.pal[i + startIndex] = makeColour(loadhere.myPalette.r[i + startIndex], loadhere.myPalette.g[i + startIndex], loadhere.myPalette.b[i + startIndex]);
 	}
-
 	loadhere.myPalette.originalRed = loadhere.myPalette.originalGreen = loadhere.myPalette.originalBlue = 255;
 
-	loadhere.myPalette.numTextures = numTextures;
-	GLubyte *tmp[numTextures];
-	GLubyte *tmp2[numTextures];
-	for (tex_num = 0; tex_num < numTextures; tex_num++) {
-		if (! NPOT_textures) {
-			totalwidth[tex_num] = getNextPOT(totalwidth[tex_num]);
-			maxheight[tex_num] = getNextPOT(maxheight[tex_num]);
-		}
-		tmp[tex_num] = new GLubyte [(maxheight[tex_num] + 1)*totalwidth[tex_num] * 4];
-		if (! checkNew(tmp[tex_num])) return false;
-		memset(tmp[tex_num], 0, maxheight[tex_num]*totalwidth[tex_num] * 4);
-		if (isFont) {
-			tmp2[tex_num] = new GLubyte [(maxheight[tex_num] + 1)*totalwidth[tex_num] * 4];
-			if (! checkNew(tmp2[tex_num])) return false;
-			memset(tmp2[tex_num], 0, maxheight[tex_num]*totalwidth[tex_num] * 4);
-		}
-		loadhere.myPalette.tex_w[tex_num] = totalwidth[tex_num];
-		loadhere.myPalette.tex_h[tex_num] = maxheight[tex_num];
-	}
-
-	int fromhere;
-	unsigned char s;
-
-	for (i = 0; i < total; i ++) {
-		fromhere = 0;
-
+	// convert
+	for (int i = 0; i < total; i ++) {
+		int fromhere = 0;
 		int transColour = -1;
-		if (spriteBankVersion < 3) {
-			int size = loadhere.sprites[i].height * loadhere.sprites[i].width;
-			while (fromhere < size) {
-				s = spriteData[i][fromhere++];
-				if (s) {
-					transColour = s;
-					break;
-				}
+		int size = picwidth * picheight;
+		while (fromhere < size) {
+			unsigned char s = spriteData[i][fromhere++];
+			if (s) {
+				transColour = s;
+				break;
 			}
-			fromhere = 0;
 		}
+		fromhere = 0;
 
-		for (int y = 1; y < 1 + loadhere.sprites[i].height; y ++) {
-			for (int x = loadhere.sprites[i].tex_x; x < loadhere.sprites[i].tex_x + loadhere.sprites[i].width; x ++) {
-				GLubyte *target = tmp[loadhere.sprites[i].texNum] + 4 * totalwidth[loadhere.sprites[i].texNum] * y + x * 4;
+		loadhere.sprites[i].surface.create(picwidth, picheight, Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0));
+		for (int y = 0; y < picheight; y++) {
+			for (int x = 0; x < picwidth; x ++) {
+				byte *target = (byte *)loadhere.sprites[i].surface.getBasePtr(x, y);
 				if (spriteBankVersion < 3) {
-					s = spriteData[i][fromhere++];
+					unsigned char s = spriteData[i][fromhere++];
 					if (s) {
-						target[0] = (GLubyte) loadhere.myPalette.r[s];
-						target[1] = (GLubyte) loadhere.myPalette.g[s];
-						target[2] = (GLubyte) loadhere.myPalette.b[s];
-						target[3] = (GLubyte) 255;
+						target[0] = (byte)255;
+						target[1] = (byte)loadhere.myPalette.b[s];
+						target[2] = (byte)loadhere.myPalette.g[s];
+						target[3] = (byte)loadhere.myPalette.r[s];
 						transColour = s;
 					} else if (transColour >= 0) {
-						target[0] = (GLubyte) loadhere.myPalette.r[transColour];
-						target[1] = (GLubyte) loadhere.myPalette.g[transColour];
-						target[2] = (GLubyte) loadhere.myPalette.b[transColour];
-						target[3] = (GLubyte) 0;
+						target[0] = (byte)0;
+						target[1] = (byte)loadhere.myPalette.b[transColour];
+						target[2] = (byte)loadhere.myPalette.g[transColour];
+						target[3] = (byte)loadhere.myPalette.r[transColour];
 					}
 					if (isFont) {
-						target = tmp2[loadhere.sprites[i].texNum] + 4 * totalwidth[loadhere.sprites[i].texNum] * y + x * 4;
-						target[0] = (GLubyte) 255;
-						target[1] = (GLubyte) 255;
-						target[2] = (GLubyte) 255;
+						target = (byte *)loadhere.sprites[i].surface.getBasePtr(x, y);
 						if (s)
-						target[3] = (GLubyte) loadhere.myPalette.r[s];
-						/*else
-						 target[3] = (GLubyte) 0;*/
+						target[0] = loadhere.myPalette.r[s];
+						target[1] = (byte)255;
+						target[2] = (byte)255;
+						target[3] = (byte)255;
 					}
-				} else {
-					target[0] = (GLubyte) spriteData[i][fromhere++];
-					target[1] = (GLubyte) spriteData[i][fromhere++];
-					target[2] = (GLubyte) spriteData[i][fromhere++];
-					target[3] = (GLubyte) spriteData[i][fromhere++];
 				}
 			}
 		}
@@ -387,52 +274,8 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 	delete[] spriteData;
 	spriteData = NULL;
 
-#if 0
-	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
-
-	glGenTextures(numTextures, loadhere.myPalette.tex_names);
-	if (isFont)
-	glGenTextures(numTextures, loadhere.myPalette.burnTex_names);
-
-#endif
-
-	for (tex_num = 0; tex_num < numTextures; tex_num++) {
-
-		glBindTexture(GL_TEXTURE_2D, loadhere.myPalette.tex_names[tex_num]);
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-		if (gameSettings.antiAlias < 0) {
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-		} else {
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-		}
-		texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, totalwidth[tex_num], maxheight[tex_num], 0, GL_RGBA, GL_UNSIGNED_BYTE, tmp[tex_num], loadhere.myPalette.tex_names[tex_num]);
-
-		delete[] tmp[tex_num];
-		tmp[tex_num] = NULL;
-
-		if (isFont) {
-
-			glBindTexture(GL_TEXTURE_2D, loadhere.myPalette.burnTex_names[tex_num]);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-			if (gameSettings.antiAlias < 0) {
-				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-			} else {
-				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-			}
-			texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, totalwidth[tex_num], maxheight[tex_num], 0, GL_RGBA, GL_UNSIGNED_BYTE, tmp2[tex_num], loadhere.myPalette.burnTex_names[tex_num]);
-			delete[] tmp2[tex_num];
-			tmp2[tex_num] = NULL;
-		}
-	}
-
 	finishAccess();
-#endif
+
 	setResourceForFatal(-1);
 
 	return true;
@@ -649,7 +492,7 @@ extern GLuint backdropTextureName;
 
 void fontSprite(bool flip, int x, int y, sprite &single,
 		const spritePalette &fontPal) {
-
+#if 0
 	float tx1 = (float) (single.tex_x - 0.5) / fontPal.tex_w[single.texNum];
 	float ty1 = 0.0;
 	float tx2 = (float) (single.tex_x + single.width + (flip ? 1.0 : 0.5))
@@ -661,7 +504,6 @@ void fontSprite(bool flip, int x, int y, sprite &single,
 	float x2 = x1 + (float) single.width / cameraZoom;
 	float y2 = y1 + (float) single.height / cameraZoom;
 
-#if 0
 	GLfloat vertices[] = {
 		x1, y1, 0.0f,
 		x2, y1, 0.0f,
diff --git a/engines/sludge/sprites.h b/engines/sludge/sprites.h
index 067c84a..efc0fcc 100644
--- a/engines/sludge/sprites.h
+++ b/engines/sludge/sprites.h
@@ -22,23 +22,15 @@
 #ifndef SLUDGE_SPRITE_H
 #define SLUDGE_SPRITE_H
 
-#if 0
-#if !defined(HAVE_GLES2)
-#include "GLee.h"
-#else
-#include <GLES2/gl2.h>
-#endif
-#endif
+#include "graphics/surface.h"
 
 namespace Sludge {
 
 struct onScreenPerson;
 
 struct sprite {
-	int width, height, xhot, yhot;
-	int tex_x;
-	int texNum;
-	//unsigned char * data;
+	int xhot, yhot;
+	Graphics::Surface surface;
 };
 
 class spritePalette {
@@ -47,17 +39,10 @@ public:
 	unsigned char *r;
 	unsigned char *g;
 	unsigned char *b;
-#if 0
-	GLuint *tex_names;
-	GLuint *burnTex_names;
-#endif
-	int *tex_w, *tex_h;
-	int numTextures;
 	unsigned char originalRed, originalGreen, originalBlue, total;
 
-	spritePalette() :
-			pal(0), r(0), g(0), b(0)/*, tex_names(0), burnTex_names(0)*/
-			, tex_w(0), tex_h(0), numTextures(0), total(0) {
+	spritePalette() : pal(0), r(0), g(0), b(0), total(0) {
+		originalRed = originalGreen = originalBlue = 255;
 	}
 
 	~spritePalette() {
@@ -65,10 +50,6 @@ public:
 		delete[] r;
 		delete[] g;
 		delete[] b;
-//		delete [] tex_names;
-//		delete [] burnTex_names;
-		delete[] tex_w;
-		delete[] tex_h;
 	}
 };
 


Commit: 733e758fcb16b824742450fe0d2a003abb977729
    https://github.com/scummvm/scummvm/commit/733e758fcb16b824742450fe0d2a003abb977729
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: move backdrop display code to backdrop.cpp

Changed paths:
    engines/sludge/backdrop.cpp
    engines/sludge/main_loop.cpp
    engines/sludge/sludger.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index a6cf71f..bd08776 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -536,6 +536,10 @@ inline int sortOutPCamera(int cX, int fX, int sceneMax, int boxMax) {
 }
 
 void drawBackDrop() {
+	g_system->copyRectToScreen(backdropSurface.getPixels(),
+			backdropSurface.pitch, 0, 0, backdropSurface.w,
+			backdropSurface.h);
+	g_system->updateScreen();
 #if 0
 	setPrimaryColor(1.0, 1.0, 1.0, 1.0);
 
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index 2c4648b..55e2fc6 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -479,10 +479,6 @@ int main_loop(char *filename)
 		walkAllPeople();
 		handleInput();
 		sludgeDisplay();
-		g_system->copyRectToScreen(backdropSurface.getPixels(),
-				backdropSurface.pitch, 0, 0, backdropSurface.w,
-				backdropSurface.h);
-		g_system->updateScreen();
 		g_system->delayMillis(100);
 #if 0
 		Wait_Frame();
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index 7fe2119..f44cbbc 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -702,19 +702,22 @@ void sludgeDisplay() {
 //	glClearColor(0.5, 0.5, 1.0, 0.0);
 	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Clear The Screen
 	glDepthMask(GL_FALSE);
-
+#endif
 	drawBackDrop();// Draw the room
 	drawZBuffer(cameraX, cameraY, false);
-
+#if 0
 	glEnable(GL_DEPTH_TEST);
+#endif
 	drawPeople();// Then add any moving characters...
+#if 0
 	glDisable(GL_DEPTH_TEST);
+#endif
 	viewSpeech();// ...and anything being said
 	drawStatusBar();
 	displayCursor();
 
 	if (brightnessLevel < 255) fixBrightness();// This is for transitionLevel special effects
-
+#if 0
 	glFlush();
 #if !defined(HAVE_GLES2)
 	SDL_GL_SwapBuffers();


Commit: 00b64e01d40a6d11f098b13ffd3ceda9d544bfc7
    https://github.com/scummvm/scummvm/commit/00b64e01d40a6d11f098b13ffd3ceda9d544bfc7
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: Add debug channel for fatal msg

Changed paths:
    engines/sludge/newfatal.cpp
    engines/sludge/sludge.cpp
    engines/sludge/sludge.h
    engines/sludge/sludger.cpp


diff --git a/engines/sludge/newfatal.cpp b/engines/sludge/newfatal.cpp
index 477a7f9..9441569 100644
--- a/engines/sludge/newfatal.cpp
+++ b/engines/sludge/newfatal.cpp
@@ -35,6 +35,7 @@
 #include "stringy.h"
 #include "errors.h"
 #include "graphics.h"
+#include "sludge.h"
 
 namespace Sludge {
 
@@ -133,7 +134,7 @@ void setFatalInfo(const char *userFunc, const char *BIF) {
 	if (fatalInfo)
 		sprintf(fatalInfo, "Currently in this sub: %s\nCalling: %s", userFunc,
 				BIF);
-	debug("%s", fatalInfo);
+	debug(kSludgeDebugFatal, "%s", fatalInfo);
 }
 
 void setResourceForFatal(int n) {
diff --git a/engines/sludge/sludge.cpp b/engines/sludge/sludge.cpp
index 86c4980..b679a09 100644
--- a/engines/sludge/sludge.cpp
+++ b/engines/sludge/sludge.cpp
@@ -40,7 +40,7 @@ SludgeEngine::SludgeEngine(OSystem *syst, const SludgeGameDescription *gameDesc)
 	_rnd = new Common::RandomSource("sludge");
 
 	// Add debug channels
-	DebugMan.addDebugChannel(kSludgeDebugScript, "Script", "Script debug level");
+	DebugMan.addDebugChannel(kSludgeDebugFatal, "Script", "Script debug level");
 	DebugMan.addDebugChannel(kSludgeDebugDataLoad, "Data Load", "Data loading debug level");
 	DebugMan.addDebugChannel(kSludgeDebugStackMachine, "Stack Machine", "Stack Machine debug level");
 	DebugMan.addDebugChannel(kSludgeDebugBuiltin, "Built-in", "Built-in debug level");
diff --git a/engines/sludge/sludge.h b/engines/sludge/sludge.h
index 73105c4..a4e96c7 100644
--- a/engines/sludge/sludge.h
+++ b/engines/sludge/sludge.h
@@ -37,7 +37,7 @@ struct SludgeGameDescription;
 
 // debug channels
 enum {
-	kSludgeDebugScript = 1 << 0,
+	kSludgeDebugFatal = 1 << 0,
 	kSludgeDebugDataLoad = 1 << 1,
 	kSludgeDebugStackMachine = 1 << 2,
 	kSludgeDebugBuiltin = 1 << 3,
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index f44cbbc..aca5272 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -172,9 +172,9 @@ Common::File *openAndVerify(char *filename, char extra1, char extra2,
 	}
 	char c;
 	c = fp->readByte();
-	debug("%c", c);
+	debug(kSludgeDebugDataLoad, "%c", c);
 	while ((c = fp->readByte())) {
-		debug("%c", c);
+		debug(kSludgeDebugDataLoad, "%c", c);
 	}
 
 	int majVersion = fp->readByte();
@@ -519,7 +519,7 @@ bool initSludge(char *filename) {
 	}
 
 	numGlobals = fp->readUint16BE();
-	debug("numGlobals : %i", numGlobals);
+	debug(kSludgeDebugDataLoad, "numGlobals : %i", numGlobals);
 
 	globalVars = new variable[numGlobals];
 	if (!checkNew(globalVars))


Commit: 54ad2661579ecc5606ae56f6f8184f84f716ea2b
    https://github.com/scummvm/scummvm/commit/54ad2661579ecc5606ae56f6f8184f84f716ea2b
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: fix sprite loading error

Changed paths:
    engines/sludge/sprites.cpp


diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index c62c31a..16ff87f 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -112,7 +112,7 @@ bool reserveSpritePal(spritePalette &sP, int n) {
 
 bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 
-	int total, picwidth, picheight, spriteBankVersion = 0, howmany = 0, startIndex = 0;
+	int total, spriteBankVersion = 0, howmany = 0, startIndex = 0;
 	byte *data;
 
 	setResourceForFatal(fileNum);
@@ -163,6 +163,7 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 
 	// version 0, 1, 2
 	for (int i = 0; i < total; i ++) {
+		int picwidth, picheight;
 		// load sprite width, height, relative position
 		if (spriteBankVersion == 2) {
 			picwidth = bigDataFile->readUint16BE();
@@ -177,6 +178,7 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 		}
 
 		// init data
+		loadhere.sprites[i].surface.create(picwidth, picheight, Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0));
 		data = (byte *)new byte[picwidth * (picheight + 1)];
 		if (!checkNew(data)) return false;
 		int ooo = picwidth * picheight;
@@ -186,7 +188,7 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 		spriteData[i] = data;
 
 		// read color
-		if (spriteBankVersion == 2) {
+		if (spriteBankVersion == 2) { // RUN LENGTH COMPRESSED DATA
 			unsigned size = picwidth * picheight;
 			unsigned pip = 0;
 
@@ -230,7 +232,7 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 	for (int i = 0; i < total; i ++) {
 		int fromhere = 0;
 		int transColour = -1;
-		int size = picwidth * picheight;
+		int size = loadhere.sprites[i].surface.w * loadhere.sprites[i].surface.h;
 		while (fromhere < size) {
 			unsigned char s = spriteData[i][fromhere++];
 			if (s) {
@@ -239,33 +241,29 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 			}
 		}
 		fromhere = 0;
-
-		loadhere.sprites[i].surface.create(picwidth, picheight, Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0));
-		for (int y = 0; y < picheight; y++) {
-			for (int x = 0; x < picwidth; x ++) {
+		for (int y = 0; y < loadhere.sprites[i].surface.h; ++y) {
+			for (int x = 0; x < loadhere.sprites[i].surface.w; ++x) {
 				byte *target = (byte *)loadhere.sprites[i].surface.getBasePtr(x, y);
-				if (spriteBankVersion < 3) {
-					unsigned char s = spriteData[i][fromhere++];
-					if (s) {
-						target[0] = (byte)255;
-						target[1] = (byte)loadhere.myPalette.b[s];
-						target[2] = (byte)loadhere.myPalette.g[s];
-						target[3] = (byte)loadhere.myPalette.r[s];
-						transColour = s;
-					} else if (transColour >= 0) {
-						target[0] = (byte)0;
-						target[1] = (byte)loadhere.myPalette.b[transColour];
-						target[2] = (byte)loadhere.myPalette.g[transColour];
-						target[3] = (byte)loadhere.myPalette.r[transColour];
-					}
-					if (isFont) {
-						target = (byte *)loadhere.sprites[i].surface.getBasePtr(x, y);
-						if (s)
-						target[0] = loadhere.myPalette.r[s];
-						target[1] = (byte)255;
-						target[2] = (byte)255;
-						target[3] = (byte)255;
-					}
+				unsigned char s = spriteData[i][fromhere++];
+				if (s) {
+					target[0] = (byte)255;
+					target[1] = (byte)loadhere.myPalette.b[s];
+					target[2] = (byte)loadhere.myPalette.g[s];
+					target[3] = (byte)loadhere.myPalette.r[s];
+					transColour = s;
+				} else if (transColour >= 0) {
+					target[0] = (byte)0;
+					target[1] = (byte)loadhere.myPalette.b[transColour];
+					target[2] = (byte)loadhere.myPalette.g[transColour];
+					target[3] = (byte)loadhere.myPalette.r[transColour];
+				}
+				if (isFont) {
+					target = (byte *)loadhere.sprites[i].surface.getBasePtr(x, y);
+					if (s)
+					target[0] = loadhere.myPalette.r[s];
+					target[1] = (byte)255;
+					target[2] = (byte)255;
+					target[3] = (byte)255;
 				}
 			}
 		}


Commit: 30eef2568cc77ae8a5cebf11ea63912fef7d6e2d
    https://github.com/scummvm/scummvm/commit/30eef2568cc77ae8a5cebf11ea63912fef7d6e2d
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: display sprites with TransparentSurface

Changed paths:
    engines/sludge/sprites.cpp


diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index 16ff87f..baa10da 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -21,6 +21,7 @@
  */
 
 #include "graphics/surface.h"
+#include "graphics/transparent_surface.h"
 #include "allfiles.h"
 #include "fileset.h"
 #include "people.h"
@@ -577,34 +578,26 @@ extern GLuint backdropTextureName;
 
 bool checkColourChange(bool reset);
 
-bool scaleSprite(sprite &single, const spritePalette &fontPal,
-		onScreenPerson *thisPerson, bool mirror) {
-#if 0
+bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *thisPerson, bool mirror) {
 	float x = thisPerson->x;
 	float y = thisPerson->y;
 
-	float scale = thisPerson-> scale;
-	bool light = !(thisPerson->extra & EXTRA_NOLITE);
+	float scale = thisPerson->scale;
 
 	if (scale <= 0.05) return false;
 
-	float tx1 = (float)(single.tex_x) / fontPal.tex_w[single.texNum];
-	float ty1 = (float) 1.0 / fontPal.tex_h[single.texNum];
-	float tx2 = (float)(single.tex_x + single.width) / fontPal.tex_w[single.texNum];
-	float ty2 = (float)(single.height + 1) / fontPal.tex_h[single.texNum];
-
-	int diffX = (int)(((float)single.width) * scale);
-	int diffY = (int)(((float)single.height) * scale);
+	int diffX = (int)(((float)single.surface.w) * scale);
+	int diffY = (int)(((float)single.surface.h) * scale);
 
-	GLfloat x1, y1, x2, y2;
+	float x1, y1, x2, y2;
 
-	if (thisPerson -> extra & EXTRA_FIXTOSCREEN) {
+	if (thisPerson->extra & EXTRA_FIXTOSCREEN) {
 		x = x / cameraZoom;
 		y = y / cameraZoom;
 		if (single.xhot < 0)
-		x1 = x - (int)((mirror ? (float)(single.width - single.xhot) : (float)(single.xhot + 1)) * scale / cameraZoom);
+			x1 = x - (int)((mirror ? (float)(single.surface.w - single.xhot) : (float)(single.xhot + 1)) * scale / cameraZoom);
 		else
-		x1 = x - (int)((mirror ? (float)(single.width - (single.xhot + 1)) : (float)single.xhot) * scale / cameraZoom);
+			x1 = x - (int)((mirror ? (float)(single.surface.w - (single.xhot + 1)) : (float)single.xhot) * scale / cameraZoom);
 		y1 = y - (int)((single.yhot - thisPerson->floaty) * scale / cameraZoom);
 		x2 = x1 + (int)(diffX / cameraZoom);
 		y2 = y1 + (int)(diffY / cameraZoom);
@@ -612,14 +605,22 @@ bool scaleSprite(sprite &single, const spritePalette &fontPal,
 		x -= cameraX;
 		y -= cameraY;
 		if (single.xhot < 0)
-		x1 = x - (int)((mirror ? (float)(single.width - single.xhot) : (float)(single.xhot + 1)) * scale);
+		x1 = x - (int)((mirror ? (float)(single.surface.w - single.xhot) : (float)(single.xhot + 1)) * scale);
 		else
-		x1 = x - (int)((mirror ? (float)(single.width - (single.xhot + 1)) : (float)single.xhot) * scale);
+		x1 = x - (int)((mirror ? (float)(single.surface.w - (single.xhot + 1)) : (float)single.xhot) * scale);
 		y1 = y - (int)((single.yhot - thisPerson->floaty) * scale);
 		x2 = x1 + diffX;
 		y2 = y1 + diffY;
 	}
 
+	// Use Transparent surface to scale and blit
+	Graphics::TransparentSurface tmp(single.surface, false);
+	Graphics::Surface *screen = g_system->lockScreen();
+	tmp.blit(*screen, x1, y1, (mirror? Graphics::FLIP_H : Graphics::FLIP_NONE), nullptr, TS_ARGB(255, 255, 255, 255), diffX, diffY);
+	g_system->unlockScreen();
+	g_system->updateScreen();
+
+#if 0
 	GLfloat z;
 
 	if ((!(thisPerson->extra & EXTRA_NOZB)) && zBuffer.numPanels) {
@@ -655,6 +656,7 @@ bool scaleSprite(sprite &single, const spritePalette &fontPal,
 		ltx2, lty2
 	};
 
+	bool light = !(thisPerson->extra & EXTRA_NOLITE);
 	if (light && lightMap.data) {
 		if (lightMapMode == LIGHTMAPMODE_HOTSPOT) {
 			int lx = (int)(x + cameraX);
@@ -737,7 +739,6 @@ bool scaleSprite(sprite &single, const spritePalette &fontPal,
 	}
 
 	setSecondaryColor(0., 0., 0., 1.);
-	//glDisable(GL_COLOR_SUM); FIXME: replace line?
 
 	// Are we pointing at the sprite?
 	if (input.mouseX >= x1 && input.mouseX <= x2 && input.mouseY >= y1 && input.mouseY <= y2) {
@@ -748,8 +749,8 @@ bool scaleSprite(sprite &single, const spritePalette &fontPal,
 		return checkColourChange(false);
 #endif
 	}
-#endif
 	return false;
+#endif
 }
 
 // Paste a scaled sprite onto the backdrop


Commit: a589fac89527f2aebe8c5685d5f4620fc30b20f1
    https://github.com/scummvm/scummvm/commit/a589fac89527f2aebe8c5685d5f4620fc30b20f1
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: fix sprite flickering by using a full screen surface

Changed paths:
    engines/sludge/backdrop.cpp
    engines/sludge/main_loop.cpp
    engines/sludge/sludger.cpp
    engines/sludge/sprites.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index bd08776..1079b57 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -45,10 +45,12 @@
 #include "graphics/palette.h"
 #include "sludge.h"
 #include "imgloader.h"
+#include "common/rect.h"
 
 namespace Sludge {
 
 extern inputType input;
+extern Graphics::Surface renderSurface;
 
 bool freeze();
 void unfreeze(bool);    // Because FREEZE.H needs a load of other includes
@@ -536,10 +538,7 @@ inline int sortOutPCamera(int cX, int fX, int sceneMax, int boxMax) {
 }
 
 void drawBackDrop() {
-	g_system->copyRectToScreen(backdropSurface.getPixels(),
-			backdropSurface.pitch, 0, 0, backdropSurface.w,
-			backdropSurface.h);
-	g_system->updateScreen();
+	renderSurface.copyRectToSurface(backdropSurface, 0, 0, Common::Rect(0, 0, backdropSurface.w, backdropSurface.h));
 #if 0
 	setPrimaryColor(1.0, 1.0, 1.0, 1.0);
 
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index 55e2fc6..14ffed0 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -100,6 +100,7 @@ extern int specialSettings;
 extern inputType input;
 extern variableStack *noStack;
 extern Graphics::Surface backdropSurface;
+Graphics::Surface renderSurface;
 
 int dialogValue = 0;
 
@@ -473,6 +474,7 @@ int main_loop(char *filename)
 
 	SDL_EnableUNICODE(1);
 #endif
+	renderSurface.create(g_system->getWidth(), g_system->getHeight(), g_system->getScreenFormat());
 	weAreDoneSoQuit = 0;
 	while (!weAreDoneSoQuit) {
 		checkInput();
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index aca5272..9f80228 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -76,6 +76,7 @@ extern char *launchMe;
 extern variable *launchResult;
 
 extern bool reallyWantToQuit;
+extern Graphics::Surface renderSurface;
 
 int numBIFNames = 0;
 char * *allBIFNames = NULL;
@@ -715,7 +716,8 @@ void sludgeDisplay() {
 	viewSpeech();// ...and anything being said
 	drawStatusBar();
 	displayCursor();
-
+	g_system->copyRectToScreen((byte *)renderSurface.getPixels(), renderSurface.pitch, 0, 0, renderSurface.w, renderSurface.h);
+	g_system->updateScreen();
 	if (brightnessLevel < 255) fixBrightness();// This is for transitionLevel special effects
 #if 0
 	glFlush();
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index baa10da..ef6d521 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -48,6 +48,7 @@ extern GLuint backdropTextureName;
 extern inputType input;
 extern int cameraX, cameraY;
 extern float cameraZoom;
+extern Graphics::Surface renderSurface;
 
 unsigned char currentBurnR = 0, currentBurnG = 0, currentBurnB = 0;
 
@@ -615,10 +616,7 @@ bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *t
 
 	// Use Transparent surface to scale and blit
 	Graphics::TransparentSurface tmp(single.surface, false);
-	Graphics::Surface *screen = g_system->lockScreen();
-	tmp.blit(*screen, x1, y1, (mirror? Graphics::FLIP_H : Graphics::FLIP_NONE), nullptr, TS_ARGB(255, 255, 255, 255), diffX, diffY);
-	g_system->unlockScreen();
-	g_system->updateScreen();
+	tmp.blit(renderSurface, x1, y1, (mirror? Graphics::FLIP_H : Graphics::FLIP_NONE), nullptr, TS_ARGB(255, 255, 255, 255), diffX, diffY);
 
 #if 0
 	GLfloat z;


Commit: 414b3c47146ebcc684fb37bccbbb66ff2ac68e2d
    https://github.com/scummvm/scummvm/commit/414b3c47146ebcc684fb37bccbbb66ff2ac68e2d
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: text display

Changed paths:
    engines/sludge/sprites.cpp
    engines/sludge/sprites.h
    engines/sludge/talk.cpp
    engines/sludge/talk.h


diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index ef6d521..936bb67 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -181,6 +181,9 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 
 		// init data
 		loadhere.sprites[i].surface.create(picwidth, picheight, Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0));
+		if (isFont) {
+			loadhere.sprites[i].burnSurface.create(picwidth, picheight, Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0));
+		}
 		data = (byte *)new byte[picwidth * (picheight + 1)];
 		if (!checkNew(data)) return false;
 		int ooo = picwidth * picheight;
@@ -260,9 +263,9 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 					target[3] = (byte)loadhere.myPalette.r[transColour];
 				}
 				if (isFont) {
-					target = (byte *)loadhere.sprites[i].surface.getBasePtr(x, y);
+					target = (byte *)loadhere.sprites[i].burnSurface.getBasePtr(x, y);
 					if (s)
-					target[0] = loadhere.myPalette.r[s];
+						target[0] = loadhere.myPalette.r[s];
 					target[1] = (byte)255;
 					target[2] = (byte)255;
 					target[3] = (byte)255;
@@ -490,20 +493,25 @@ void burnSpriteToBackDrop(int x1, int y1, sprite &single,
 extern GLuint backdropTextureName;
 #endif
 
-void fontSprite(bool flip, int x, int y, sprite &single,
-		const spritePalette &fontPal) {
+void fontSprite(bool flip, int x, int y, sprite &single, const spritePalette &fontPal) {
+	float x1 = (float) x - (float) single.xhot / cameraZoom;
+	float y1 = (float) y - (float) single.yhot / cameraZoom;
+
+	// Use Transparent surface to scale and blit
+	Graphics::TransparentSurface tmp(single.surface, false);
+	Graphics::TransparentSurface tmp2(single.burnSurface, false);
+	tmp.blit(renderSurface, x1, y1, (flip? Graphics::FLIP_H : Graphics::FLIP_NONE));
+	tmp2.blit(renderSurface, x1, y1, (flip? Graphics::FLIP_H : Graphics::FLIP_NONE), 0, TS_RGB(fontPal.originalRed, fontPal.originalGreen, fontPal.originalBlue));
+
 #if 0
+	float x2 = x1 + (float) single.surface.w / cameraZoom;
+	float y2 = y1 + (float) single.surface.h / cameraZoom;
 	float tx1 = (float) (single.tex_x - 0.5) / fontPal.tex_w[single.texNum];
 	float ty1 = 0.0;
 	float tx2 = (float) (single.tex_x + single.width + (flip ? 1.0 : 0.5))
 			/ fontPal.tex_w[single.texNum];
 	float ty2 = (float) (single.height + 2) / fontPal.tex_h[single.texNum];
 
-	float x1 = (float) x - (float) single.xhot / cameraZoom;
-	float y1 = (float) y - (float) single.yhot / cameraZoom;
-	float x2 = x1 + (float) single.width / cameraZoom;
-	float y2 = y1 + (float) single.height / cameraZoom;
-
 	GLfloat vertices[] = {
 		x1, y1, 0.0f,
 		x2, y1, 0.0f,
diff --git a/engines/sludge/sprites.h b/engines/sludge/sprites.h
index efc0fcc..c09ae39 100644
--- a/engines/sludge/sprites.h
+++ b/engines/sludge/sprites.h
@@ -31,6 +31,7 @@ struct onScreenPerson;
 struct sprite {
 	int xhot, yhot;
 	Graphics::Surface surface;
+	Graphics::Surface burnSurface;
 };
 
 class spritePalette {
diff --git a/engines/sludge/talk.cpp b/engines/sludge/talk.cpp
index 0b66815..86e2174 100644
--- a/engines/sludge/talk.cpp
+++ b/engines/sludge/talk.cpp
@@ -78,9 +78,7 @@ void killAllSpeech() {
 #define TF_min(a, b) ((a > b) ? b : a)
 
 inline void setObjFontColour(objectType *t) {
-#if 0
 	setFontColour(speech->talkCol, t->r, t->g, t->b);
-#endif
 }
 
 void addSpeechLine(char *theLine, int x, int &offset) {
@@ -203,7 +201,6 @@ int wrapSpeech(char *theText, int objT, int sampleFile, bool animPerson) {
 }
 
 void viewSpeech() {
-#if 0
 	int viewY = speech->speechY;
 	speechLine *viewLine = speech->allSpeech;
 	fixFont(speech->talkCol);
@@ -212,7 +209,6 @@ void viewSpeech() {
 		viewY -= fontHeight / cameraZoom;
 		viewLine = viewLine->next;
 	}
-#endif
 }
 
 void saveSpeech(speechStruct *sS, Common::WriteStream *stream) {
diff --git a/engines/sludge/talk.h b/engines/sludge/talk.h
index 5e32def..39da742 100644
--- a/engines/sludge/talk.h
+++ b/engines/sludge/talk.h
@@ -36,9 +36,7 @@ struct speechStruct {
 	onScreenPerson *currentTalker;
 	speechLine *allSpeech;
 	int speechY, lastFile, lookWhosTalking;
-#if 0
 	spritePalette talkCol;
-#endif
 };
 
 int wrapSpeech(char *theText, int objT, int sampleFile, bool);


Commit: 10ff6994ae8a8f6ba1f49d8cf1590762b1ae1be8
    https://github.com/scummvm/scummvm/commit/10ff6994ae8a8f6ba1f49d8cf1590762b1ae1be8
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: format code and remove oneliners

Changed paths:
    engines/sludge/backdrop.cpp
    engines/sludge/bg_effects.cpp
    engines/sludge/builtin.cpp
    engines/sludge/errors.h
    engines/sludge/fileset.cpp
    engines/sludge/floor.cpp
    engines/sludge/floor.h
    engines/sludge/fonttext.cpp
    engines/sludge/freeze.cpp
    engines/sludge/language.cpp
    engines/sludge/line.cpp
    engines/sludge/loadsave.cpp
    engines/sludge/moreio.cpp
    engines/sludge/newfatal.cpp
    engines/sludge/objtypes.cpp
    engines/sludge/people.cpp
    engines/sludge/people.h
    engines/sludge/region.cpp
    engines/sludge/savedata.cpp
    engines/sludge/sludge.cpp
    engines/sludge/sludger.cpp
    engines/sludge/sludger.h
    engines/sludge/sound_bass.cpp
    engines/sludge/sprbanks.cpp
    engines/sludge/sprites.h
    engines/sludge/statusba.cpp
    engines/sludge/thumbnail.cpp
    engines/sludge/transition.cpp
    engines/sludge/variable.cpp
    engines/sludge/vid.cpp
    engines/sludge/zbuffer.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index 1079b57..2418593 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -251,11 +251,11 @@ void killParallax() {
 bool reserveBackdrop() {
 	cameraX = 0;
 	cameraY = 0;
-	input.mouseX = (int) ((float) input.mouseX * cameraZoom);
-	input.mouseY = (int) ((float) input.mouseY * cameraZoom);
+	input.mouseX = (int)((float)input.mouseX * cameraZoom);
+	input.mouseY = (int)((float)input.mouseY * cameraZoom);
 	cameraZoom = 1.0;
-	input.mouseX = (int) ((float) input.mouseX / cameraZoom);
-	input.mouseY = (int) ((float) input.mouseY / cameraZoom);
+	input.mouseX = (int)((float)input.mouseX / cameraZoom);
+	input.mouseY = (int)((float)input.mouseY / cameraZoom);
 	setPixelCoords(false);
 	int picWidth = sceneWidth;
 	int picHeight = sceneHeight;
@@ -317,9 +317,7 @@ void loadBackDrop(int fileNum, int x, int y) {
 
 	if (!loadHSI(bigDataFile, x, y, false)) {
 		char mess[200];
-		sprintf(mess,
-				"Can't paste overlay image outside scene dimensions\n\nX = %i\nY = %i\nWidth = %i\nHeight = %i",
-				x, y, sceneWidth, sceneHeight);
+		sprintf(mess, "Can't paste overlay image outside scene dimensions\n\nX = %i\nY = %i\nWidth = %i\nHeight = %i", x, y, sceneWidth, sceneHeight);
 		fatal(mess);
 	}
 
@@ -348,10 +346,10 @@ void blankScreen(int x1, int y1, int x2, int y2) {
 		y1 = 0;
 	if (x1 < 0)
 		x1 = 0;
-	if (x2 > (int) sceneWidth)
-		x2 = (int) sceneWidth;
-	if (y2 > (int) sceneHeight)
-		y2 = (int) sceneHeight;
+	if (x2 > (int)sceneWidth)
+		x2 = (int)sceneWidth;
+	if (y2 > (int)sceneHeight)
+		y2 = (int)sceneHeight;
 
 	int picWidth = x2 - x1;
 	int picHeight = y2 - y1;
@@ -467,13 +465,11 @@ void darkScreen() {
 
 	int xoffset = 0;
 	while (xoffset < sceneWidth) {
-		int w = (sceneWidth - xoffset < viewportWidth) ?
-				sceneWidth - xoffset : viewportWidth;
+		int w = (sceneWidth - xoffset < viewportWidth) ? sceneWidth - xoffset : viewportWidth;
 
 		int yoffset = 0;
 		while (yoffset < sceneHeight) {
-			int h = (sceneHeight - yoffset < viewportHeight) ?
-					sceneHeight - yoffset : viewportHeight;
+			int h = (sceneHeight - yoffset < viewportHeight) ? sceneHeight - yoffset : viewportHeight;
 
 			// Render the scene - first the old backdrop
 #if 0
@@ -533,8 +529,7 @@ void darkScreen() {
 }
 
 inline int sortOutPCamera(int cX, int fX, int sceneMax, int boxMax) {
-	return (fX == 65535) ?
-			(sceneMax ? ((cX * boxMax) / sceneMax) : 0) : ((cX * fX) / 100);
+	return (fX == 65535) ? (sceneMax ? ((cX * boxMax) / sceneMax) : 0) : ((cX * fX) / 100);
 }
 
 void drawBackDrop() {
@@ -624,7 +619,8 @@ void drawBackDrop() {
 
 bool loadLightMap(int v) {
 	setResourceForFatal(v);
-	if (!openFileFromNum(v)) return fatal("Can't open light map.");
+	if (!openFileFromNum(v))
+		return fatal("Can't open light map.");
 
 	killLightMap();
 	lightMapNumber = v;
@@ -714,10 +710,12 @@ void reloadParallaxTextures() {
 
 bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY) {
 	setResourceForFatal(v);
-	if (!openFileFromNum(v)) return fatal("Can't open parallax image");
+	if (!openFileFromNum(v))
+		return fatal("Can't open parallax image");
 
 	parallaxLayer *nP = new parallaxLayer;
-	if (!checkNew(nP)) return false;
+	if (!checkNew(nP))
+		return false;
 
 	nP->next = parallaxStuff;
 	parallaxStuff = nP;
@@ -924,15 +922,15 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 	int realPicHeight = backdropSurface.h;
 
 	if (reserve) { // resize backdrop
-		if (!resizeBackdrop(realPicWidth, realPicHeight)) return false;
+		if (!resizeBackdrop(realPicWidth, realPicHeight))
+			return false;
 	}
 
 	if (x == IN_THE_CENTRE)
 		x = (sceneWidth - realPicWidth) >> 1;
 	if (y == IN_THE_CENTRE)
 		y = (sceneHeight - realPicHeight) >> 1;
-	if (x < 0 || x + realPicWidth > sceneWidth || y < 0
-			|| y + realPicHeight > sceneHeight) {
+	if (x < 0 || x + realPicWidth > sceneWidth || y < 0 || y + realPicHeight > sceneHeight) {
 		debug(kSludgeDebugGraphics, "Illegal back drop size");
 		return false;
 	}
@@ -957,9 +955,12 @@ bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 	int realPicWidth = backdropSurface.w;
 	int realPicHeight = backdropSurface.h;
 
-	if (x == IN_THE_CENTRE) x = (sceneWidth - realPicWidth) >> 1;
-	if (y == IN_THE_CENTRE) y = (sceneHeight - realPicHeight) >> 1;
-	if (x < 0 || x + realPicWidth > sceneWidth || y < 0 || y + realPicHeight > sceneHeight) return false;
+	if (x == IN_THE_CENTRE)
+		x = (sceneWidth - realPicWidth) >> 1;
+	if (y == IN_THE_CENTRE)
+		y = (sceneHeight - realPicHeight) >> 1;
+	if (x < 0 || x + realPicWidth > sceneWidth || y < 0 || y + realPicHeight > sceneHeight)
+		return false;
 #if 0
 	float btx1, tx1;
 	float btx2, tx2;
@@ -1160,27 +1161,22 @@ void saveCorePNG(Common::WriteStream *stream, GLuint texture, int w, int h) {
 #endif
 }
 #endif
-
 #if 0
 void saveCoreHSI(Common::WriteStream *stream, GLuint texture, int w, int h) {
 	GLint tw, th;
 	glBindTexture(GL_TEXTURE_2D, texture);
 	getTextureDimensions(texture, &tw, &th);
 
-	GLushort *image = new GLushort [tw * th];
-	if (!checkNew(image)) return;
+	GLushort *image = new GLushort[tw * th];
+	if (!checkNew(image))
+		return;
 	glPixelStorei(GL_PACK_ALIGNMENT, 1);
 //	glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, image);
 	setPixelCoords(true);
 
 	//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
 
-	const GLfloat texCoords[] = {
-		0.0f, 0.0f,
-		1.0f, 0.0f,
-		0.0f, 1.0f,
-		1.0f, 1.0f
-	};
+	const GLfloat texCoords[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f };
 
 	int xoffset = 0;
 	while (xoffset < tw) {
@@ -1189,13 +1185,9 @@ void saveCoreHSI(Common::WriteStream *stream, GLuint texture, int w, int h) {
 		int yoffset = 0;
 		while (yoffset < th) {
 			int h = (th - yoffset < viewportHeight) ? th - yoffset : viewportHeight;
-			glClear(GL_COLOR_BUFFER_BIT);   // Clear The Screen
-			const GLfloat vertices[] = {
-				(GLfloat) - xoffset, (GLfloat) - yoffset, 0.,
-				(GLfloat)w - xoffset, (GLfloat) - yoffset, 0.,
-				(GLfloat) - xoffset, (GLfloat) - yoffset + h, 0.,
-				(GLfloat)w - xoffset, (GLfloat) - yoffset + h, 0.
-			};
+			glClear (GL_COLOR_BUFFER_BIT);   // Clear The Screen
+			const GLfloat vertices[] = { (GLfloat)-xoffset, (GLfloat)-yoffset, 0., (GLfloat)w - xoffset, (GLfloat)-yoffset, 0., (GLfloat)-xoffset, (GLfloat)-yoffset + h, 0., (GLfloat)w - xoffset,
+					(GLfloat)-yoffset + h, 0. };
 
 			glUseProgram(shader.texture);
 			setPMVMatrix(shader.texture);
@@ -1203,7 +1195,7 @@ void saveCoreHSI(Common::WriteStream *stream, GLuint texture, int w, int h) {
 			glUseProgram(0);
 
 			for (int i = 0; i < h; i++) {
-				glReadPixels(viewportOffsetX, viewportOffsetY + i, w, 1, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, image + xoffset + (yoffset + i)*tw);
+				glReadPixels(viewportOffsetX, viewportOffsetY + i, w, 1, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, image + xoffset + (yoffset + i) * tw);
 			}
 			yoffset += viewportHeight;
 		}
@@ -1214,32 +1206,34 @@ void saveCoreHSI(Common::WriteStream *stream, GLuint texture, int w, int h) {
 	setPixelCoords(false);
 
 	int x, y, lookAhead;
-	unsigned short int *fromHere, * lookPointer;
+	unsigned short int *fromHere, *lookPointer;
 
 	stream->writeUint16BE(w);
 	stream->writeUint16BE(h);
 
-	for (y = 0; y < h; y ++) {
+	for (y = 0; y < h; y++) {
 		fromHere = image + (y * tw);
 		x = 0;
 		while (x < w) {
 			lookPointer = fromHere + 1;
-			for (lookAhead = x + 1; lookAhead < w; lookAhead ++) {
-				if (lookAhead - x == 256) break;
-				if (* fromHere != * lookPointer) break;
-				lookPointer ++;
+			for (lookAhead = x + 1; lookAhead < w; lookAhead++) {
+				if (lookAhead - x == 256)
+					break;
+				if (*fromHere != *lookPointer)
+					break;
+				lookPointer++;
 			}
 			if (lookAhead == x + 1) {
-				put2bytes((* fromHere) & 65503, stream);
+				put2bytes((*fromHere) & 65503, stream);
 			} else {
-				stream->writeUint16BE(* fromHere | 32);
+				stream->writeUint16BE(*fromHere | 32);
 				stream->writeByte(lookAhead - x - 1);
 			}
 			fromHere = lookPointer;
 			x = lookAhead;
 		}
 	}
-	delete [] image;
+	delete[] image;
 	image = NULL;
 }
 #endif
diff --git a/engines/sludge/bg_effects.cpp b/engines/sludge/bg_effects.cpp
index 9c8bcb3..3692026 100644
--- a/engines/sludge/bg_effects.cpp
+++ b/engines/sludge/bg_effects.cpp
@@ -64,14 +64,14 @@ static int s_matrixEffectBase = 15;
 static int s_matrixEffectDivide = 4;
 static int s_matrixEffectWidth = 3;
 static int s_matrixEffectHeight = 3;
-static int s_matrixEffectData[9] = { -2, -1, 0, -1, 1, 1, 0, 1, 2};
+static int s_matrixEffectData[9] = {-2, -1, 0, -1, 1, 1, 0, 1, 2};
 static int s_matrixEffectBase = 16;
 #elif 0
 // Standard emboss
 static int s_matrixEffectDivide = 2;
 static int s_matrixEffectWidth = 3;
 static int s_matrixEffectHeight = 3;
-static int s_matrixEffectData[9] = { -1, 0, 0, 0, 0, 0, 0, 0, 1};
+static int s_matrixEffectData[9] = {-1, 0, 0, 0, 0, 0, 0, 0, 1};
 static int s_matrixEffectBase = 128;
 #elif 0
 // Horizontal blur
@@ -92,7 +92,7 @@ static int s_matrixEffectBase = 0;
 static int s_matrixEffectDivide = 1;
 static int s_matrixEffectWidth = 1;
 static int s_matrixEffectHeight = 1;
-static int s_matrixEffectData[9] = { -1};
+static int s_matrixEffectData[9] = {-1};
 static int s_matrixEffectBase = 255;
 #elif 0
 // Fog
@@ -136,7 +136,7 @@ static int *blur_allocateMemoryForEffect() {
 	s_matrixEffectData = NULL;
 
 	if (s_matrixEffectWidth && s_matrixEffectHeight) {
-		s_matrixEffectData = (int *) malloc(sizeof(int) * s_matrixEffectHeight * s_matrixEffectWidth);
+		s_matrixEffectData = (int *)malloc(sizeof(int) * s_matrixEffectHeight * s_matrixEffectWidth);
 		checkNew(s_matrixEffectData);
 	}
 	return s_matrixEffectData;
@@ -169,7 +169,7 @@ bool blur_createSettings(int numParams, variableStack *&stack) {
 		int width = 0;
 
 		variableStack *justToCheckSizes = stack;
-		for (int a = 0; a < height; a ++) {
+		for (int a = 0; a < height; a++) {
 			if (justToCheckSizes->thisVar.varType != SVT_STACK) {
 				error = "Third and subsequent parameters in setBackgroundEffect should be arrays";
 				break;
@@ -189,19 +189,19 @@ bool blur_createSettings(int numParams, variableStack *&stack) {
 			}
 		}
 
-		if (width == 0 && ! error) {
+		if (width == 0 && !error) {
 			error = "Empty arrays found in setBackgroundEffect parameters";
 		}
 
-		if (! error) {
+		if (!error) {
 			s_matrixEffectWidth = width;
 			s_matrixEffectHeight = height;
 
 			if (blur_allocateMemoryForEffect()) {
-				for (int y = height - 1; y >= 0; y --) {
+				for (int y = height - 1; y >= 0; y--) {
 					variableStack *eachNumber = stack->thisVar.varData.theStack->first;
-					if (! error) {
-						for (int x = 0; x < width; x ++) {
+					if (!error) {
+						for (int x = 0; x < width; x++) {
 							int arraySlot = x + (y * width);
 //							s_matrixEffectData[arraySlot] = (rand() % 4);
 							if (!getValueType(s_matrixEffectData[arraySlot], SVT_INT, eachNumber->thisVar)) {
@@ -213,13 +213,13 @@ bool blur_createSettings(int numParams, variableStack *&stack) {
 						trimStack(stack);
 					}
 				}
-				if (! error && !getValueType(s_matrixEffectDivide, SVT_INT, stack -> thisVar))
+				if (!error && !getValueType(s_matrixEffectDivide, SVT_INT, stack->thisVar))
 					error = "";
 				trimStack(stack);
-				if (! error && !getValueType(s_matrixEffectBase, SVT_INT, stack -> thisVar))
+				if (!error && !getValueType(s_matrixEffectBase, SVT_INT, stack->thisVar))
 					error = "";
 				trimStack(stack);
-				if (! error) {
+				if (!error) {
 					if (s_matrixEffectDivide) {
 						createNullThing = false;
 					} else {
@@ -249,7 +249,7 @@ bool blur_createSettings(int numParams, variableStack *&stack) {
 		fatal(error);
 	}
 
-	return ! createNullThing;
+	return !createNullThing;
 }
 
 static inline int clampi(int i, int min, int max) {
@@ -260,13 +260,13 @@ static inline void blur_createSourceLine(unsigned char *createLine, unsigned cha
 	int miniX;
 	memcpy(createLine + overlapOnLeft * 4, fromLine, width * 4);
 
-	for (miniX = 0; miniX < overlapOnLeft; miniX ++) {
+	for (miniX = 0; miniX < overlapOnLeft; miniX++) {
 		createLine[miniX * 4] = fromLine[0];
 		createLine[miniX * 4 + 1] = fromLine[1];
 		createLine[miniX * 4 + 2] = fromLine[2];
 	}
 
-	for (miniX = width + overlapOnLeft; miniX < width + s_matrixEffectWidth - 1; miniX ++) {
+	for (miniX = width + overlapOnLeft; miniX < width + s_matrixEffectWidth - 1; miniX++) {
 		createLine[miniX * 4] = fromLine[width * 4 - 4];
 		createLine[miniX * 4 + 1] = fromLine[width * 4 - 3];
 		createLine[miniX * 4 + 2] = fromLine[width * 4 - 2];
@@ -280,15 +280,16 @@ bool blurScreen() {
 		int y, x;
 		bool ok = true;
 		int overlapOnLeft = s_matrixEffectWidth / 2;
-		int overlapAbove  = s_matrixEffectHeight / 2;
+		int overlapAbove = s_matrixEffectHeight / 2;
 
 		unsigned char **sourceLine = new unsigned char *[s_matrixEffectHeight];
-		if (! checkNew(sourceLine)) return false;
+		if (!checkNew(sourceLine))
+			return false;
 
 		int picWidth = sceneWidth;
 		int picHeight = sceneHeight;
 
-		if (! NPOT_textures) {
+		if (!NPOT_textures) {
 			picWidth = getNextPOT(sceneWidth);
 			picHeight = getNextPOT(sceneHeight);
 		}
@@ -296,26 +297,26 @@ bool blurScreen() {
 		// Retrieve the texture
 		saveTexture(backdropTextureName, backdropTexture);
 
-		for (y = 0; y < s_matrixEffectHeight; y ++) {
+		for (y = 0; y < s_matrixEffectHeight; y++) {
 			sourceLine[y] = new unsigned char[(s_matrixEffectWidth - 1 + picWidth) * 4];
 			ok &= (sourceLine[y] != NULL);
 		}
 
 		if (ok) {
-			for (y = 0; y < s_matrixEffectHeight; y ++) {
+			for (y = 0; y < s_matrixEffectHeight; y++) {
 				int miniY = clampi(y - overlapAbove - 1, 0, sceneHeight - 1);
 
 				blur_createSourceLine(sourceLine[y], backdropTexture + miniY * picWidth * 4, overlapOnLeft, picWidth);
 			}
 
-			for (y = 0; y < sceneHeight; y ++) {
+			for (y = 0; y < sceneHeight; y++) {
 				thisLine = backdropTexture + y * picWidth * 4;
 
 				//-------------------------
 				// Scroll source lines
 				//-------------------------
 				unsigned char *tempLine = sourceLine[0];
-				for (int miniY = 0; miniY < s_matrixEffectHeight - 1; miniY ++) {
+				for (int miniY = 0; miniY < s_matrixEffectHeight - 1; miniY++) {
 					sourceLine[miniY] = sourceLine[miniY + 1];
 				}
 				sourceLine[s_matrixEffectHeight - 1] = tempLine;
@@ -325,19 +326,19 @@ bool blurScreen() {
 
 					blur_createSourceLine(sourceLine[h], backdropTexture + miniY * picWidth * 4, overlapOnLeft, picWidth);
 				}
-				for (x = 0; x < sceneWidth; x ++) {
+				for (x = 0; x < sceneWidth; x++) {
 					int totalRed = 0;
 					int totalGreen = 0;
 					int totalBlue = 0;
 					int *matrixElement = s_matrixEffectData;
-					for (int miniY = 0; miniY < s_matrixEffectHeight; ++ miniY) {
-						unsigned char *pixel = & sourceLine[miniY][x * 4];
-						for (int miniX = 0; miniX < s_matrixEffectWidth; ++ miniX) {
-
-							totalRed    += pixel[0]     * * matrixElement;
-							totalGreen  += pixel[1]     * * matrixElement;
-							totalBlue   += pixel[2]     * * matrixElement;
-							++ matrixElement;
+					for (int miniY = 0; miniY < s_matrixEffectHeight; ++miniY) {
+						unsigned char *pixel = &sourceLine[miniY][x * 4];
+						for (int miniX = 0; miniX < s_matrixEffectWidth; ++miniX) {
+
+							totalRed += pixel[0] * *matrixElement;
+							totalGreen += pixel[1] * *matrixElement;
+							totalBlue += pixel[2] * *matrixElement;
+							++matrixElement;
 							pixel += 4;
 						}
 					}
@@ -350,19 +351,19 @@ bool blurScreen() {
 					totalBlue = (totalBlue + s_matrixEffectDivide / 2) / s_matrixEffectDivide + s_matrixEffectBase;
 					totalBlue = (totalBlue < 0) ? 0 : ((totalBlue > 255) ? 255 : totalBlue);
 
-					* thisLine = totalRed;
-					++ thisLine;
-					* thisLine = totalGreen;
-					++ thisLine;
-					* thisLine = totalBlue;
-					++ thisLine;
-//					* thisLine = totalAlpha;
-					++ thisLine;
+					*thisLine = totalRed;
+					++thisLine;
+					*thisLine = totalGreen;
+					++thisLine;
+					*thisLine = totalBlue;
+					++thisLine;
+//					*thisLine = totalAlpha;
+					++thisLine;
 				}
 			}
 		}
 
-		for (y = 0; y < s_matrixEffectHeight; y ++) {
+		for (y = 0; y < s_matrixEffectHeight; y++) {
 			delete sourceLine[y];
 		}
 		delete sourceLine;
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 5eb52f9..58926b2 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -125,37 +125,38 @@ int paramNum[] = { -1, 0, 1, 1, -1, -1, 1, 3, 4, 1, 0, 0, 8, -1,    // SAY->MOVE
                  };
 
 bool failSecurityCheck(char *fn) {
-	if (fn == NULL) return true;
+	if (fn == NULL)
+		return true;
 
 	int a = 0;
 
 	while (fn[a]) {
 		switch (fn[a]) {
-		case ':':
-		case '\\':
-		case '/':
-		case '*':
-		case '?':
-		case '"':
-		case '<':
-		case '>':
-		case '|':
-			fatal("Filenames may not contain the following characters: \n\n\\  /  :  \"  <  >  |  ?  *\n\nConsequently, the following filename is not allowed:", fn);
-			return true;
+			case ':':
+			case '\\':
+			case '/':
+			case '*':
+			case '?':
+			case '"':
+			case '<':
+			case '>':
+			case '|':
+				fatal("Filenames may not contain the following characters: \n\n\\  /  :  \"  <  >  |  ?  *\n\nConsequently, the following filename is not allowed:", fn);
+				return true;
 		}
-		a ++;
+		a++;
 	}
 	return false;
 }
 
 loadedFunction *saverFunc;
 
-typedef builtReturn(* builtInSludgeFunc)(int numParams, loadedFunction *fun);
+typedef builtReturn (*builtInSludgeFunc)(int numParams, loadedFunction *fun);
 struct builtInFunctionData {
 	builtInSludgeFunc func;
 };
 
-#define builtIn(a)          static builtReturn builtIn_ ## a (int numParams, loadedFunction * fun)
+#define builtIn(a)          static builtReturn builtIn_ ## a (int numParams, loadedFunction *fun)
 #define UNUSEDALL           (void) (0 && sizeof(numParams) && sizeof (fun));
 
 static builtReturn sayCore(int numParams, loadedFunction *fun, bool sayIt) {
@@ -165,24 +166,27 @@ static builtReturn sayCore(int numParams, loadedFunction *fun, bool sayIt) {
 	killSpeechTimers();
 
 	switch (numParams) {
-	case 3:
-		if (!getValueType(fileNum, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
-		trimStack(fun->stack);
-	// No break; here
+		case 3:
+			if (!getValueType(fileNum, SVT_FILE, fun->stack->thisVar))
+				return BR_ERROR;
+			trimStack(fun->stack);
+			// No break; here
 
-	case 2:
-		newText = getTextFromAnyVar(fun->stack->thisVar);
-		if (!newText) return BR_ERROR;
-		trimStack(fun->stack);
-		if (!getValueType(objT, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
-		trimStack(fun->stack);
-		p = wrapSpeech(newText, objT, fileNum, sayIt);
-		fun->timeLeft = p;
-		//debugOut ("BUILTIN: sayCore: %s (%i)\n", newText, p);
-		fun->isSpeech = true;
-		delete newText;
-		newText = NULL;
-		return BR_KEEP_AND_PAUSE;
+		case 2:
+			newText = getTextFromAnyVar(fun->stack->thisVar);
+			if (!newText)
+				return BR_ERROR;
+			trimStack(fun->stack);
+			if (!getValueType(objT, SVT_OBJTYPE, fun->stack->thisVar))
+				return BR_ERROR;
+			trimStack(fun->stack);
+			p = wrapSpeech(newText, objT, fileNum, sayIt);
+			fun->timeLeft = p;
+			//debugOut ("BUILTIN: sayCore: %s (%i)\n", newText, p);
+			fun->isSpeech = true;
+			delete newText;
+			newText = NULL;
+			return BR_KEEP_AND_PAUSE;
 	}
 
 	fatal("Function should have either 2 or 3 parameters");
@@ -264,18 +268,21 @@ builtIn(getStatusText) {
 builtIn(getMatchingFiles) {
 	UNUSEDALL
 	char *newText = getTextFromAnyVar(fun->stack->thisVar);
-	if (!newText) return BR_ERROR;
+	if (!newText)
+		return BR_ERROR;
 	trimStack(fun->stack);
 	unlinkVar(fun->reg);
 
 	// Return value
 	fun->reg.varType = SVT_STACK;
 	fun->reg.varData.theStack = new stackHandler;
-	if (!checkNew(fun->reg.varData.theStack)) return BR_ERROR;
+	if (!checkNew(fun->reg.varData.theStack))
+		return BR_ERROR;
 	fun->reg.varData.theStack->first = NULL;
 	fun->reg.varData.theStack->last = NULL;
 	fun->reg.varData.theStack->timesUsed = 1;
-	if (!getSavedGamesStack(fun->reg.varData.theStack, newText)) return BR_ERROR;
+	if (!getSavedGamesStack(fun->reg.varData.theStack, newText))
+		return BR_ERROR;
 	delete newText;
 	newText = NULL;
 	return BR_CONTINUE;
@@ -293,7 +300,8 @@ builtIn(saveGame) {
 
 	char *aaaaa = encodeFilename(loadNow);
 	delete[] loadNow;
-	if (failSecurityCheck(aaaaa)) return BR_ERROR;      // Won't fail if encoded, how cool is that? OK, not very.
+	if (failSecurityCheck(aaaaa))
+		return BR_ERROR;      // Won't fail if encoded, how cool is that? OK, not very.
 
 	loadNow = joinStrings(":", aaaaa);
 	delete[] aaaaa;
@@ -309,7 +317,8 @@ builtIn(fileExists) {
 	trimStack(fun->stack);
 	char *aaaaa = encodeFilename(loadNow);
 	delete loadNow;
-	if (failSecurityCheck(aaaaa)) return BR_ERROR;
+	if (failSecurityCheck(aaaaa))
+		return BR_ERROR;
 #if 0
 	FILE *fp = fopen(aaaaa, "rb");
 	if (!fp) {
@@ -328,11 +337,11 @@ builtIn(fileExists) {
 	}
 #endif
 	// Return value
-	setVariable(fun->reg, SVT_INT, 0/*(fp != NULL)*/);//TODO:false value
+	setVariable(fun->reg, SVT_INT, 0/*(fp != NULL)*/);      //TODO:false value
 #if 0
-	if (fp) fclose(fp);
-	delete[] aaaaa;
-	loadNow = NULL;
+			if (fp) fclose(fp);
+			delete[] aaaaa;
+			loadNow = NULL;
 #endif
 	return BR_CONTINUE;
 }
@@ -347,7 +356,8 @@ builtIn(loadGame) {
 	if (frozenStuff) {
 		fatal("Can't load a saved game while the engine is frozen");
 	}
-	if (failSecurityCheck(loadNow)) return BR_ERROR;
+	if (failSecurityCheck(loadNow))
+		return BR_ERROR;
 	Common::File fd;
 	if (fd.open(loadNow)) {
 		fd.close();
@@ -372,13 +382,17 @@ builtIn(blankScreen) {
 builtIn(blankArea) {
 	UNUSEDALL
 	int x1, y1, x2, y2;
-	if (!getValueType(y2, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(y2, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(x2, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(x2, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(y1, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(y1, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(x1, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(x1, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	blankScreen(x1, y1, x2, y2);
 	return BR_CONTINUE;
@@ -393,11 +407,14 @@ builtIn(darkBackground) {
 builtIn(addOverlay) {
 	UNUSEDALL
 	int fileNumber, xPos, yPos;
-	if (!getValueType(yPos, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(yPos, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(xPos, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(xPos, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	loadBackDrop(fileNumber, xPos, yPos);
 	return BR_CONTINUE;
@@ -406,11 +423,14 @@ builtIn(addOverlay) {
 builtIn(mixOverlay) {
 	UNUSEDALL
 	int fileNumber, xPos, yPos;
-	if (!getValueType(yPos, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(yPos, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(xPos, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(xPos, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	mixBackDrop(fileNumber, xPos, yPos);
 	return BR_CONTINUE;
@@ -419,13 +439,16 @@ builtIn(mixOverlay) {
 builtIn(pasteImage) {
 	UNUSEDALL
 	int x, y;
-	if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(y, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	personaAnimation *pp = getAnimationFromVar(fun->stack->thisVar);
 	trimStack(fun->stack);
-	if (pp == NULL) return BR_CONTINUE;
+	if (pp == NULL)
+		return BR_CONTINUE;
 
 	pasteCursor(x, y, pp);
 	return BR_CONTINUE;
@@ -437,9 +460,11 @@ builtIn(pasteImage) {
 builtIn(setSceneDimensions) {
 	UNUSEDALL
 	int x, y;
-	if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(y, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	if (killResizeBackdrop(x, y)) {
 		blankScreen(0, 0, x, y);
@@ -451,35 +476,42 @@ builtIn(setSceneDimensions) {
 
 builtIn(aimCamera) {
 	UNUSEDALL
-	if (!getValueType(cameraY, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(cameraY, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(cameraX, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(cameraX, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	cameraX -= (float)(winWidth >> 1) / cameraZoom;
 	cameraY -= (float)(winHeight >> 1) / cameraZoom;
 
-	if (cameraX < 0) cameraX = 0;
-	else if (cameraX > sceneWidth - (float)winWidth / cameraZoom) cameraX = sceneWidth - (float)winWidth / cameraZoom;
-	if (cameraY < 0) cameraY = 0;
-	else if (cameraY > sceneHeight - (float)winHeight / cameraZoom) cameraY = sceneHeight - (float)winHeight / cameraZoom;
+	if (cameraX < 0)
+		cameraX = 0;
+	else if (cameraX > sceneWidth - (float)winWidth / cameraZoom)
+		cameraX = sceneWidth - (float)winWidth / cameraZoom;
+	if (cameraY < 0)
+		cameraY = 0;
+	else if (cameraY > sceneHeight - (float)winHeight / cameraZoom)
+		cameraY = sceneHeight - (float)winHeight / cameraZoom;
 	return BR_CONTINUE;
 }
 
-
 builtIn(zoomCamera) {
 	UNUSEDALL
 	int z;
-	if (!getValueType(z, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(z, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	input.mouseX = input.mouseX * cameraZoom;
 	input.mouseY = input.mouseY * cameraZoom;
 
-
-	cameraZoom = (float) z * 0.01;
-	if ((float) winWidth / cameraZoom > sceneWidth) cameraZoom = (float)winWidth / sceneWidth;
-	if ((float) winHeight / cameraZoom > sceneHeight) cameraZoom = (float)winHeight / sceneHeight;
+	cameraZoom = (float)z * 0.01;
+	if ((float)winWidth / cameraZoom > sceneWidth)
+		cameraZoom = (float)winWidth / sceneWidth;
+	if ((float)winHeight / cameraZoom > sceneHeight)
+		cameraZoom = (float)winHeight / sceneHeight;
 	setPixelCoords(false);
 
 	input.mouseX = input.mouseX / cameraZoom;
@@ -491,7 +523,6 @@ builtIn(zoomCamera) {
 #pragma mark -
 #pragma mark Variables
 
-
 builtIn(pickOne) {
 	UNUSEDALL
 	if (!numParams) {
@@ -505,8 +536,9 @@ builtIn(pickOne) {
 #endif
 
 	// Return value
-	while (numParams --) {
-		if (i == numParams) copyVariable(fun->stack->thisVar, fun->reg);
+	while (numParams--) {
+		if (i == numParams)
+			copyVariable(fun->stack->thisVar, fun->reg);
 		trimStack(fun->stack);
 	}
 	return BR_CONTINUE;
@@ -520,9 +552,11 @@ builtIn(substring) {
 
 	//debugOut ("BUILTIN: substring\n");
 
-	if (!getValueType(length, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(length, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(start, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(start, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	wholeString = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
@@ -569,12 +603,14 @@ builtIn(newStack) {
 	// Return value
 	fun->reg.varType = SVT_STACK;
 	fun->reg.varData.theStack = new stackHandler;
-	if (!checkNew(fun->reg.varData.theStack)) return BR_ERROR;
+	if (!checkNew(fun->reg.varData.theStack))
+		return BR_ERROR;
 	fun->reg.varData.theStack->first = NULL;
 	fun->reg.varData.theStack->last = NULL;
 	fun->reg.varData.theStack->timesUsed = 1;
-	while (numParams --) {
-		if (!addVarToStack(fun->stack->thisVar, fun->reg.varData.theStack->first)) return BR_ERROR;
+	while (numParams--) {
+		if (!addVarToStack(fun->stack->thisVar, fun->reg.varData.theStack->first))
+			return BR_ERROR;
 		if (fun->reg.varData.theStack->last == NULL) {
 			fun->reg.varData.theStack->last = fun->reg.varData.theStack->first;
 		}
@@ -589,20 +625,20 @@ builtIn(newStack) {
 builtIn(stackSize) {
 	UNUSEDALL
 	switch (fun->stack->thisVar.varType) {
-	case SVT_STACK:
-		// Return value
-		setVariable(fun->reg, SVT_INT, stackSize(fun->stack->thisVar.varData.theStack));
-		trimStack(fun->stack);
-		return BR_CONTINUE;
+		case SVT_STACK:
+			// Return value
+			setVariable(fun->reg, SVT_INT, stackSize(fun->stack->thisVar.varData.theStack));
+			trimStack(fun->stack);
+			return BR_CONTINUE;
 
-	case SVT_FASTARRAY:
-		// Return value
-		setVariable(fun->reg, SVT_INT, fun->stack->thisVar.varData.fastArray->size);
-		trimStack(fun->stack);
-		return BR_CONTINUE;
+		case SVT_FASTARRAY:
+			// Return value
+			setVariable(fun->reg, SVT_INT, fun->stack->thisVar.varData.fastArray->size);
+			trimStack(fun->stack);
+			return BR_CONTINUE;
 
-	default:
-		break;
+		default:
+			break;
 	}
 	fatal("Parameter isn't a stack or a fast array.");
 	return BR_ERROR;
@@ -615,7 +651,8 @@ builtIn(copyStack) {
 		return BR_ERROR;
 	}
 	// Return value
-	if (!copyStack(fun->stack->thisVar, fun->reg)) return BR_ERROR;
+	if (!copyStack(fun->stack->thisVar, fun->reg))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	return BR_CONTINUE;
 }
@@ -651,8 +688,7 @@ builtIn(enqueue) {
 
 		fun->stack->next->thisVar.varData.theStack->last = fun->stack->next->thisVar.varData.theStack->first;
 	} else {
-		if (!addVarToStack(fun->stack->thisVar,
-		                    fun->stack->next->thisVar.varData.theStack->last->next))
+		if (!addVarToStack(fun->stack->thisVar, fun->stack->next->thisVar.varData.theStack->last->next))
 			return BR_ERROR;
 		fun->stack->next->thisVar.varData.theStack->last = fun->stack->next->thisVar.varData.theStack->last->next;
 	}
@@ -670,9 +706,7 @@ builtIn(deleteFromStack) {
 	}
 
 	// Return value
-	setVariable(fun->reg, SVT_INT,
-	            deleteVarFromStack(fun->stack->thisVar,
-	                               fun->stack->next->thisVar.varData.theStack->first, false));
+	setVariable(fun->reg, SVT_INT, deleteVarFromStack(fun->stack->thisVar, fun->stack->next->thisVar.varData.theStack->first, false));
 
 	// Horrible hacking because 'last' value might now be wrong!
 	fun->stack->next->thisVar.varData.theStack->last = stackFindLast(fun->stack->next->thisVar.varData.theStack->first);
@@ -690,9 +724,7 @@ builtIn(deleteAllFromStack) {
 	}
 
 	// Return value
-	setVariable(fun->reg, SVT_INT,
-	            deleteVarFromStack(fun->stack->thisVar,
-	                               fun->stack->next->thisVar.varData.theStack->first, true));
+	setVariable(fun->reg, SVT_INT, deleteVarFromStack(fun->stack->thisVar, fun->stack->next->thisVar.varData.theStack->first, true));
 
 	// Horrible hacking because 'last' value might now be wrong!
 	fun->stack->next->thisVar.varData.theStack->last = stackFindLast(fun->stack->next->thisVar.varData.theStack->first);
@@ -762,17 +794,21 @@ builtIn(random) {
 		return BR_ERROR;
 
 	trimStack(fun->stack);
-	if (num <= 0) num = 1;
+	if (num <= 0)
+		num = 1;
 	setVariable(fun->reg, SVT_INT, 0 /*rand() % num*/); //TODO:false value
 	return BR_CONTINUE;
 }
 
 static bool getRGBParams(int &red, int &green, int &blue, loadedFunction *fun) {
-	if (!getValueType(blue, SVT_INT, fun->stack->thisVar)) return false;
+	if (!getValueType(blue, SVT_INT, fun->stack->thisVar))
+		return false;
 	trimStack(fun->stack);
-	if (!getValueType(green, SVT_INT, fun->stack->thisVar)) return false;
+	if (!getValueType(green, SVT_INT, fun->stack->thisVar))
+		return false;
 	trimStack(fun->stack);
-	if (!getValueType(red, SVT_INT, fun->stack->thisVar)) return false;
+	if (!getValueType(red, SVT_INT, fun->stack->thisVar))
+		return false;
 	trimStack(fun->stack);
 	return true;
 }
@@ -784,7 +820,7 @@ builtIn(setStatusColour) {
 	if (!getRGBParams(red, green, blue, fun))
 		return BR_ERROR;
 
-	statusBarColour((byte) red, (byte) green, (byte) blue);
+	statusBarColour((byte)red, (byte)green, (byte)blue);
 	return BR_CONTINUE;
 }
 
@@ -795,7 +831,7 @@ builtIn(setLitStatusColour) {
 	if (!getRGBParams(red, green, blue, fun))
 		return BR_ERROR;
 
-	statusBarLitColour((byte) red, (byte) green, (byte) blue);
+	statusBarLitColour((byte)red, (byte)green, (byte)blue);
 	return BR_CONTINUE;
 }
 
@@ -806,7 +842,7 @@ builtIn(setPasteColour) {
 	if (!getRGBParams(red, green, blue, fun))
 		return BR_ERROR;
 
-	setFontColour(pastePalette, (byte) red, (byte) green, (byte) blue);
+	setFontColour(pastePalette, (byte)red, (byte)green, (byte)blue);
 	return BR_CONTINUE;
 }
 
@@ -836,21 +872,24 @@ builtIn(setBurnColour) {
 	return BR_CONTINUE;
 }
 
-
 builtIn(setFont) {
 	UNUSEDALL
 	int fileNumber, newHeight;
-	if (!getValueType(newHeight, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(newHeight, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	//              newDebug ("  Height:", newHeight);
 	trimStack(fun->stack);
 	char *newText = getTextFromAnyVar(fun->stack->thisVar);
-	if (!newText) return BR_ERROR;
+	if (!newText)
+		return BR_ERROR;
 	//              newDebug ("  Character supported:", newText);
 	trimStack(fun->stack);
-	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar))
+		return BR_ERROR;
 	//              newDebug ("  File:", fileNumber);
 	trimStack(fun->stack);
-	if (!loadFont(fileNumber, newText, newHeight)) return BR_ERROR;
+	if (!loadFont(fileNumber, newText, newHeight))
+		return BR_ERROR;
 	//              newDebug ("  Done!");
 	delete newText;
 
@@ -860,7 +899,8 @@ builtIn(setFont) {
 builtIn(inFont) {
 	UNUSEDALL
 	char *newText = getTextFromAnyVar(fun->stack->thisVar);
-	if (!newText) return BR_ERROR;
+	if (!newText)
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	// Return value
@@ -874,11 +914,14 @@ builtIn(pasteString) {
 	char *newText = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
 	int y, x;
-	if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(y, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (x == IN_THE_CENTRE) x = (winWidth - stringWidth(newText)) >> 1;
+	if (x == IN_THE_CENTRE)
+		x = (winWidth - stringWidth(newText)) >> 1;
 	fixFont(pastePalette);
 	pasteStringToBackdrop(newText, x, y, pastePalette);
 	delete[] newText;
@@ -897,12 +940,14 @@ builtIn(anim) {
 
 	// Only remaining paramter is the file number
 	int fileNumber;
-	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	// Load the required sprite bank
 	loadedSpriteBank *sprBanky = loadBankForAnim(fileNumber);
-	if (!sprBanky) return BR_ERROR;    // File not found, fatal done already
+	if (!sprBanky)
+		return BR_ERROR;    // File not found, fatal done already
 	setBankFile(ba, sprBanky);
 
 	// Return value
@@ -914,16 +959,18 @@ builtIn(anim) {
 builtIn(costume) {
 	UNUSEDALL
 	persona *newPersona = new persona;
-	if (!checkNew(newPersona)) return BR_ERROR;
+	if (!checkNew(newPersona))
+		return BR_ERROR;
 	newPersona->numDirections = numParams / 3;
 	if (numParams == 0 || newPersona->numDirections * 3 != numParams) {
 		fatal("Illegal number of parameters (should be greater than 0 and divisible by 3)");
 		return BR_ERROR;
 	}
 	int iii;
-	newPersona->animation = new personaAnimation * [numParams];
-	if (!checkNew(newPersona->animation)) return BR_ERROR;
-	for (iii = numParams - 1; iii >= 0; iii --) {
+	newPersona->animation = new personaAnimation *[numParams];
+	if (!checkNew(newPersona->animation))
+		return BR_ERROR;
+	for (iii = numParams - 1; iii >= 0; iii--) {
 		newPersona->animation[iii] = getAnimationFromVar(fun->stack->thisVar);
 		trimStack(fun->stack);
 	}
@@ -936,16 +983,13 @@ builtIn(costume) {
 builtIn(launch) {
 	UNUSEDALL
 	char *newTextA = getTextFromAnyVar(fun->stack->thisVar);
-	if (!newTextA) return BR_ERROR;
+	if (!newTextA)
+		return BR_ERROR;
 
 	char *newText = encodeFilename(newTextA);
 
 	trimStack(fun->stack);
-	if (newTextA[0] == 'h' &&
-	        newTextA[1] == 't' &&
-	        newTextA[2] == 't' &&
-	        newTextA[3] == 'p' &&
-	        (newTextA[4] == ':' || (newTextA[4] == 's' && newTextA[5] == ':'))) {
+	if (newTextA[0] == 'h' && newTextA[1] == 't' && newTextA[2] == 't' && newTextA[3] == 'p' && (newTextA[4] == ':' || (newTextA[4] == 's' && newTextA[5] == ':'))) {
 
 		// IT'S A WEBSITE!
 		launchMe = copyString(newTextA);
@@ -958,7 +1002,8 @@ builtIn(launch) {
 #endif
 		launchMe = joinStrings(gameDir, newText);
 		delete newText;
-		if (!launchMe) return BR_ERROR;
+		if (!launchMe)
+			return BR_ERROR;
 	}
 	delete newTextA;
 	setGraphicsWindow(false);
@@ -971,7 +1016,8 @@ builtIn(launch) {
 builtIn(pause) {
 	UNUSEDALL
 	int theTime;
-	if (!getValueType(theTime, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(theTime, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	if (theTime > 0) {
 		fun->timeLeft = theTime - 1;
@@ -990,9 +1036,11 @@ builtIn(completeTimers) {
 builtIn(callEvent) {
 	UNUSEDALL
 	int obj1, obj2;
-	if (!getValueType(obj2, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(obj2, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(obj1, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(obj1, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	int fNum = getCombinationFunction(obj1, obj2);
@@ -1022,7 +1070,6 @@ builtIn(quitGame) {
 	return BR_CONTINUE;
 }
 
-
 #pragma mark -
 #pragma mark Movie functions
 
@@ -1049,9 +1096,11 @@ builtIn(playMovie) {
 	UNUSEDALL
 	int fileNumber, r;
 
-	if (movieIsPlaying) return BR_PAUSE;
+	if (movieIsPlaying)
+		return BR_PAUSE;
 
-	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	r = playMovie(fileNumber);
@@ -1085,27 +1134,31 @@ builtIn(pauseMovie) {
 	return BR_CONTINUE;
 }
 
-
 #pragma mark -
 #pragma mark Audio functions
 
 builtIn(startMusic) {
 	UNUSEDALL
 	int fromTrack, musChan, fileNumber;
-	if (!getValueType(fromTrack, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(fromTrack, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(musChan, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(musChan, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!playMOD(fileNumber, musChan, fromTrack)) return BR_CONTINUE;  //BR_ERROR;
+	if (!playMOD(fileNumber, musChan, fromTrack))
+		return BR_CONTINUE;  //BR_ERROR;
 	return BR_CONTINUE;
 }
 
 builtIn(stopMusic) {
 	UNUSEDALL
 	int v;
-	if (!getValueType(v, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(v, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	stopMOD(v);
 	return BR_CONTINUE;
@@ -1114,9 +1167,11 @@ builtIn(stopMusic) {
 builtIn(setMusicVolume) {
 	UNUSEDALL
 	int musChan, v;
-	if (!getValueType(v, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(v, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(musChan, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(musChan, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	setMusicVolume(musChan, v);
 	return BR_CONTINUE;
@@ -1125,7 +1180,8 @@ builtIn(setMusicVolume) {
 builtIn(setDefaultMusicVolume) {
 	UNUSEDALL
 	int v;
-	if (!getValueType(v, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(v, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	setDefaultMusicVolume(v);
 	return BR_CONTINUE;
@@ -1134,9 +1190,11 @@ builtIn(setDefaultMusicVolume) {
 builtIn(playSound) {
 	UNUSEDALL
 	int fileNumber;
-	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!startSound(fileNumber, false)) return BR_CONTINUE;    // Was BR_ERROR
+	if (!startSound(fileNumber, false))
+		return BR_CONTINUE;    // Was BR_ERROR
 	return BR_CONTINUE;
 }
 builtIn(loopSound) {
@@ -1148,9 +1206,11 @@ builtIn(loopSound) {
 		return BR_ERROR;
 	} else if (numParams < 2) {
 
-		if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+		if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar))
+			return BR_ERROR;
 		trimStack(fun->stack);
-		if (!startSound(fileNumber, true)) return BR_CONTINUE;     // Was BR_ERROR
+		if (!startSound(fileNumber, true))
+			return BR_CONTINUE;     // Was BR_ERROR
 		return BR_CONTINUE;
 	} else {
 		// We have more than one sound to play!
@@ -1171,17 +1231,19 @@ builtIn(loopSound) {
 				return BR_ERROR;
 			}
 			s = new soundList;
-			if (!checkNew(s)) return BR_ERROR;
+			if (!checkNew(s))
+				return BR_ERROR;
 
-			s-> next = old;
-			s-> prev = NULL;
-			s-> sound = fileNumber;
+			s->next = old;
+			s->prev = NULL;
+			s->sound = fileNumber;
 			old = s;
 
 			trimStack(fun->stack);
 			numParams--;
 		}
-		while (s->next) s = s-> next;
+		while (s->next)
+			s = s->next;
 		if (doLoop > 1) {
 			s->next = old;
 			old->prev = s;
@@ -1197,7 +1259,8 @@ builtIn(loopSound) {
 builtIn(stopSound) {
 	UNUSEDALL
 	int v;
-	if (!getValueType(v, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(v, SVT_FILE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	huntKillSound(v);
 	return BR_CONTINUE;
@@ -1206,7 +1269,8 @@ builtIn(stopSound) {
 builtIn(setDefaultSoundVolume) {
 	UNUSEDALL
 	int v;
-	if (!getValueType(v, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(v, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	setDefaultSoundVolume(v);
 	return BR_CONTINUE;
@@ -1215,23 +1279,27 @@ builtIn(setDefaultSoundVolume) {
 builtIn(setSoundVolume) {
 	UNUSEDALL
 	int musChan, v;
-	if (!getValueType(v, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(v, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(musChan, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(musChan, SVT_FILE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	setSoundVolume(musChan, v);
 	return BR_CONTINUE;
 }
 
-
 builtIn(setSoundLoopPoints) {
 	UNUSEDALL
 	int musChan, theEnd, theStart;
-	if (!getValueType(theEnd, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(theEnd, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(theStart, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(theStart, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(musChan, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(musChan, SVT_FILE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	setSoundLoop(musChan, theStart, theEnd);
 	return BR_CONTINUE;
@@ -1246,7 +1314,8 @@ builtIn(setFloor) {
 		int v;
 		getValueType(v, SVT_FILE, fun->stack->thisVar);
 		trimStack(fun->stack);
-		if (!setFloor(v)) return BR_ERROR;
+		if (!setFloor(v))
+			return BR_ERROR;
 	} else {
 		trimStack(fun->stack);
 		setFloorNull();
@@ -1266,7 +1335,8 @@ builtIn(setZBuffer) {
 		int v;
 		getValueType(v, SVT_FILE, fun->stack->thisVar);
 		trimStack(fun->stack);
-		if (!setZBuffer(v)) return BR_ERROR;
+		if (!setZBuffer(v))
+			return BR_ERROR;
 	} else {
 		trimStack(fun->stack);
 		killZBuffer();
@@ -1277,40 +1347,42 @@ builtIn(setZBuffer) {
 builtIn(setLightMap) {
 	UNUSEDALL
 	switch (numParams) {
-	case 2:
-		if (!getValueType(lightMapMode, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
-		trimStack(fun->stack);
-		lightMapMode %= LIGHTMAPMODE_NUM;
-	// No break;
-
-	case 1:
-		if (fun->stack->thisVar.varType == SVT_FILE) {
-			int v;
-			getValueType(v, SVT_FILE, fun->stack->thisVar);
-			trimStack(fun->stack);
-			if (!loadLightMap(v)) return BR_ERROR;
-			setVariable(fun->reg, SVT_INT, 1);
-		} else {
+		case 2:
+			if (!getValueType(lightMapMode, SVT_INT, fun->stack->thisVar))
+				return BR_ERROR;
 			trimStack(fun->stack);
-			killLightMap();
-			setVariable(fun->reg, SVT_INT, 0);
-		}
-		break;
+			lightMapMode %= LIGHTMAPMODE_NUM;
+			// No break;
+
+		case 1:
+			if (fun->stack->thisVar.varType == SVT_FILE) {
+				int v;
+				getValueType(v, SVT_FILE, fun->stack->thisVar);
+				trimStack(fun->stack);
+				if (!loadLightMap(v))
+					return BR_ERROR;
+				setVariable(fun->reg, SVT_INT, 1);
+			} else {
+				trimStack(fun->stack);
+				killLightMap();
+				setVariable(fun->reg, SVT_INT, 0);
+			}
+			break;
 
-	default:
-		fatal("Function should have either 2 or 3 parameters");
-		return BR_ERROR;
+		default:
+			fatal("Function should have either 2 or 3 parameters");
+			return BR_ERROR;
 	}
 	return BR_CONTINUE;
 }
 
-
 #pragma mark -
 #pragma mark Objects
 
 builtIn(setSpeechMode) {
 	UNUSEDALL
-	if (!getValueType(speechMode, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(speechMode, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	if (speechMode < 0 || speechMode > 2) {
 		fatal("Valid parameters are be SPEECHANDTEXT, SPEECHONLY or TEXTONLY");
@@ -1351,9 +1423,11 @@ builtIn(rename) {
 	UNUSEDALL
 	char *newText = getTextFromAnyVar(fun->stack->thisVar);
 	int objT;
-	if (!newText) return BR_ERROR;
+	if (!newText)
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(objT, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(objT, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	objectType *o = findObjectType(objT);
 	delete o->screenName;
@@ -1364,7 +1438,8 @@ builtIn(rename) {
 builtIn(getObjectX) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	onScreenPerson *pers = findPerson(objectNumber);
@@ -1384,7 +1459,8 @@ builtIn(getObjectX) {
 builtIn(getObjectY) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	onScreenPerson *pers = findPerson(objectNumber);
@@ -1401,27 +1477,35 @@ builtIn(getObjectY) {
 	return BR_CONTINUE;
 }
 
-
 builtIn(addScreenRegion) {
 	UNUSEDALL
 	int sX, sY, x1, y1, x2, y2, di, objectNumber;
-	if (!getValueType(di, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(di, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(sY, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(sY, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(sX, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(sX, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(y2, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(y2, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(x2, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(x2, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(y1, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(y1, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(x1, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(x1, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (addScreenRegion(x1, y1, x2, y2, sX, sY, di, objectNumber)) return BR_CONTINUE;
+	if (addScreenRegion(x1, y1, x2, y2, sX, sY, di, objectNumber))
+		return BR_CONTINUE;
 	return BR_ERROR;
 
 }
@@ -1429,7 +1513,8 @@ builtIn(addScreenRegion) {
 builtIn(removeScreenRegion) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	removeScreenRegion(objectNumber);
 	return BR_CONTINUE;
@@ -1453,23 +1538,29 @@ builtIn(addCharacter) {
 	int x, y, objectNumber;
 
 	p = getCostumeFromVar(fun->stack->thisVar);
-	if (p == NULL) return BR_ERROR;
+	if (p == NULL)
+		return BR_ERROR;
 
 	trimStack(fun->stack);
-	if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(y, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (addPerson(x, y, objectNumber, p)) return BR_CONTINUE;
+	if (addPerson(x, y, objectNumber, p))
+		return BR_CONTINUE;
 	return BR_ERROR;
 }
 
 builtIn(hideCharacter) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	setShown(false, objectNumber);
 	return BR_CONTINUE;
@@ -1478,7 +1569,8 @@ builtIn(hideCharacter) {
 builtIn(showCharacter) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	setShown(true, objectNumber);
 	return BR_CONTINUE;
@@ -1494,9 +1586,11 @@ builtIn(removeAllCharacters) {
 builtIn(setCharacterDrawMode) {
 	UNUSEDALL
 	int obj, di;
-	if (!getValueType(di, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(di, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	setDrawMode(di, obj);
 	return BR_CONTINUE;
@@ -1504,9 +1598,11 @@ builtIn(setCharacterDrawMode) {
 builtIn(setCharacterTransparency) {
 	UNUSEDALL
 	int obj, x;
-	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	setPersonTransparency(obj, x);
 	return BR_CONTINUE;
@@ -1514,15 +1610,20 @@ builtIn(setCharacterTransparency) {
 builtIn(setCharacterColourise) {
 	UNUSEDALL
 	int obj, r, g, b, mix;
-	if (!getValueType(mix, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(mix, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(b, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(b, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(g, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(g, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(r, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(r, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	setPersonColourise(obj, r, g, b, mix);
 	return BR_CONTINUE;
@@ -1531,18 +1632,21 @@ builtIn(setCharacterColourise) {
 builtIn(setScale) {
 	UNUSEDALL
 	int val1, val2;
-	if (!getValueType(val2, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(val2, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(val1, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(val1, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	setScale((short int) val1, (short int) val2);
+	setScale((short int)val1, (short int)val2);
 	return BR_CONTINUE;
 }
 
 builtIn(stopCharacter) {
 	UNUSEDALL
 	int obj;
-	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	// Return value
@@ -1553,7 +1657,8 @@ builtIn(stopCharacter) {
 builtIn(pasteCharacter) {
 	UNUSEDALL
 	int obj;
-	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	onScreenPerson *thisPerson = findPerson(obj);
@@ -1579,9 +1684,11 @@ builtIn(animate) {
 	UNUSEDALL
 	int obj;
 	personaAnimation *pp = getAnimationFromVar(fun->stack->thisVar);
-	if (pp == NULL) return BR_ERROR;
+	if (pp == NULL)
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	animatePerson(obj, pp);
 	setVariable(fun->reg, SVT_INT, timeForAnim(pp));
@@ -1592,9 +1699,11 @@ builtIn(setCostume) {
 	UNUSEDALL
 	int obj;
 	persona *pp = getCostumeFromVar(fun->stack->thisVar);
-	if (pp == NULL) return BR_ERROR;
+	if (pp == NULL)
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	animatePerson(obj, pp);
 	return BR_CONTINUE;
@@ -1603,9 +1712,11 @@ builtIn(setCostume) {
 builtIn(floatCharacter) {
 	UNUSEDALL
 	int obj, di;
-	if (!getValueType(di, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(di, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	setVariable(fun->reg, SVT_INT, floatCharacter(di, obj));
 	return BR_CONTINUE;
@@ -1614,9 +1725,11 @@ builtIn(floatCharacter) {
 builtIn(setCharacterWalkSpeed) {
 	UNUSEDALL
 	int obj, di;
-	if (!getValueType(di, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(di, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	setVariable(fun->reg, SVT_INT, setCharacterWalkSpeed(di, obj));
 	return BR_CONTINUE;
@@ -1625,9 +1738,11 @@ builtIn(setCharacterWalkSpeed) {
 builtIn(turnCharacter) {
 	UNUSEDALL
 	int obj, di;
-	if (!getValueType(di, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(di, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	setVariable(fun->reg, SVT_INT, turnPersonToFace(obj, di));
 	return BR_CONTINUE;
@@ -1636,9 +1751,11 @@ builtIn(turnCharacter) {
 builtIn(setCharacterExtra) {
 	UNUSEDALL
 	int obj, di;
-	if (!getValueType(di, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(di, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(obj, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	setVariable(fun->reg, SVT_INT, setPersonExtra(obj, di));
 	return BR_CONTINUE;
@@ -1647,7 +1764,8 @@ builtIn(setCharacterExtra) {
 builtIn(removeCharacter) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	removeOneCharacter(objectNumber);
 	return BR_CONTINUE;
@@ -1655,50 +1773,60 @@ builtIn(removeCharacter) {
 
 static builtReturn moveChr(int numParams, loadedFunction *fun, bool force, bool immediate) {
 	switch (numParams) {
-	case 3: {
-		int x, y, objectNumber;
+		case 3: {
+			int x, y, objectNumber;
 
-		if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
-		trimStack(fun->stack);
-		if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
-		trimStack(fun->stack);
-		if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
-		trimStack(fun->stack);
+			if (!getValueType(y, SVT_INT, fun->stack->thisVar))
+				return BR_ERROR;
+			trimStack(fun->stack);
+			if (!getValueType(x, SVT_INT, fun->stack->thisVar))
+				return BR_ERROR;
+			trimStack(fun->stack);
+			if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar))
+				return BR_ERROR;
+			trimStack(fun->stack);
 
-		if (force) {
-			if (forceWalkingPerson(x, y, objectNumber, fun, -1)) return BR_PAUSE;
-		} else if (immediate) {
-			jumpPerson(x, y, objectNumber);
-		} else {
-			if (makeWalkingPerson(x, y, objectNumber, fun, -1)) return BR_PAUSE;
+			if (force) {
+				if (forceWalkingPerson(x, y, objectNumber, fun, -1))
+					return BR_PAUSE;
+			} else if (immediate) {
+				jumpPerson(x, y, objectNumber);
+			} else {
+				if (makeWalkingPerson(x, y, objectNumber, fun, -1))
+					return BR_PAUSE;
+			}
+			return BR_CONTINUE;
 		}
-		return BR_CONTINUE;
-	}
-
-	case 2: {
-		int toObj, objectNumber;
-		screenRegion *reggie;
 
-		if (!getValueType(toObj, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
-		trimStack(fun->stack);
-		if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
-		trimStack(fun->stack);
-		reggie = getRegionForObject(toObj);
-		if (reggie == NULL) return BR_CONTINUE;
+		case 2: {
+			int toObj, objectNumber;
+			screenRegion *reggie;
 
-		if (force) {
-			if (forceWalkingPerson(reggie->sX, reggie->sY, objectNumber, fun, reggie->di)) return BR_PAUSE;
-		} else if (immediate) {
-			jumpPerson(reggie->sX, reggie->sY, objectNumber);
-		} else {
-			if (makeWalkingPerson(reggie->sX, reggie->sY, objectNumber, fun, reggie->di)) return BR_PAUSE;
+			if (!getValueType(toObj, SVT_OBJTYPE, fun->stack->thisVar))
+				return BR_ERROR;
+			trimStack(fun->stack);
+			if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar))
+				return BR_ERROR;
+			trimStack(fun->stack);
+			reggie = getRegionForObject(toObj);
+			if (reggie == NULL)
+				return BR_CONTINUE;
+
+			if (force) {
+				if (forceWalkingPerson(reggie->sX, reggie->sY, objectNumber, fun, reggie->di))
+					return BR_PAUSE;
+			} else if (immediate) {
+				jumpPerson(reggie->sX, reggie->sY, objectNumber);
+			} else {
+				if (makeWalkingPerson(reggie->sX, reggie->sY, objectNumber, fun, reggie->di))
+					return BR_PAUSE;
+			}
+			return BR_CONTINUE;
 		}
-		return BR_CONTINUE;
-	}
 
-	default:
-		fatal("Built-in function must have either 2 or 3 parameters.");
-		return BR_ERROR;
+		default:
+			fatal("Built-in function must have either 2 or 3 parameters.");
+			return BR_ERROR;
 	}
 }
 
@@ -1738,7 +1866,8 @@ builtIn(addStatus) {
 builtIn(statusText) {
 	UNUSEDALL
 	char *newText = getTextFromAnyVar(fun->stack->thisVar);
-	if (!newText) return BR_ERROR;
+	if (!newText)
+		return BR_ERROR;
 	trimStack(fun->stack);
 	setStatusBar(newText);
 	delete newText;
@@ -1748,7 +1877,8 @@ builtIn(statusText) {
 builtIn(lightStatus) {
 	UNUSEDALL
 	int val;
-	if (!getValueType(val, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(val, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	setLitStatus(val);
 	return BR_CONTINUE;
@@ -1757,9 +1887,11 @@ builtIn(lightStatus) {
 builtIn(positionStatus) {
 	UNUSEDALL
 	int x, y;
-	if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(y, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	positionStatus(x, y);
 	return BR_CONTINUE;
@@ -1768,26 +1900,28 @@ builtIn(positionStatus) {
 builtIn(alignStatus) {
 	UNUSEDALL
 	int val;
-	if (!getValueType(val, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(val, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	nowStatus->alignStatus = (short) val;
+	nowStatus->alignStatus = (short)val;
 	return BR_CONTINUE;
 }
 
 static bool getFuncNumForCallback(int numParams, loadedFunction *fun, int &functionNum) {
 	switch (numParams) {
-	case 0:
-		functionNum = 0;
-		break;
+		case 0:
+			functionNum = 0;
+			break;
 
-	case 1:
-		if (!getValueType(functionNum, SVT_FUNC, fun->stack->thisVar)) return false;
-		trimStack(fun->stack);
-		break;
+		case 1:
+			if (!getValueType(functionNum, SVT_FUNC, fun->stack->thisVar))
+				return false;
+			trimStack(fun->stack);
+			break;
 
-	default:
-		fatal("Too many parameters.");
-		return false;
+		default:
+			fatal("Too many parameters.");
+			return false;
 	}
 	return true;
 }
@@ -1866,7 +2000,8 @@ builtIn(spawnSub) {
 	UNUSEDALL
 	int functionNum;
 	if (getFuncNumForCallback(numParams, fun, functionNum)) {
-		if (!startNewFunctionNum(functionNum, 0, NULL, noStack)) return BR_ERROR;
+		if (!startNewFunctionNum(functionNum, 0, NULL, noStack))
+			return BR_ERROR;
 		return BR_CONTINUE;
 	}
 	return BR_ERROR;
@@ -1890,7 +2025,8 @@ builtIn(cancelSub) {
 builtIn(stringWidth) {
 	UNUSEDALL
 	char *theText = getTextFromAnyVar(fun->stack->thisVar);
-	if (!theText) return BR_ERROR;
+	if (!theText)
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	// Return value
@@ -1902,17 +2038,18 @@ builtIn(stringWidth) {
 builtIn(hardScroll) {
 	UNUSEDALL
 	int v;
-	if (!getValueType(v, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(v, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	hardScroll(v);
 	return BR_CONTINUE;
 }
 
-
 builtIn(isScreenRegion) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	setVariable(fun->reg, SVT_INT, getRegionForObject(objectNumber) != NULL);
 	return BR_CONTINUE;
@@ -1921,7 +2058,8 @@ builtIn(isScreenRegion) {
 builtIn(setSpeechSpeed) {
 	UNUSEDALL
 	int number;
-	if (!getValueType(number, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(number, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	speechSpeed = number * 0.01;
 	setVariable(fun->reg, SVT_INT, 1);
@@ -1931,7 +2069,8 @@ builtIn(setSpeechSpeed) {
 builtIn(setFontSpacing) {
 	UNUSEDALL
 	int fontSpaceI;
-	if (!getValueType(fontSpaceI, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(fontSpaceI, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	fontSpace = fontSpaceI;
 	trimStack(fun->stack);
 	setVariable(fun->reg, SVT_INT, 1);
@@ -1941,7 +2080,8 @@ builtIn(setFontSpacing) {
 builtIn(transitionLevel) {
 	UNUSEDALL
 	int number;
-	if (!getValueType(number, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(number, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	if (number < 0)
@@ -1963,13 +2103,14 @@ builtIn(captureAllKeys) {
 	return BR_CONTINUE;
 }
 
-
 builtIn(spinCharacter) {
 	UNUSEDALL
 	int number, objectNumber;
-	if (!getValueType(number, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(number, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	onScreenPerson *thisPerson = findPerson(objectNumber);
@@ -1988,7 +2129,8 @@ builtIn(spinCharacter) {
 builtIn(getCharacterDirection) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	onScreenPerson *thisPerson = findPerson(objectNumber);
 	if (thisPerson) {
@@ -2002,7 +2144,8 @@ builtIn(getCharacterDirection) {
 builtIn(isCharacter) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	onScreenPerson *thisPerson = findPerson(objectNumber);
 	setVariable(fun->reg, SVT_INT, thisPerson != NULL);
@@ -2012,7 +2155,8 @@ builtIn(isCharacter) {
 builtIn(normalCharacter) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	onScreenPerson *thisPerson = findPerson(objectNumber);
 	if (thisPerson) {
@@ -2027,7 +2171,8 @@ builtIn(normalCharacter) {
 builtIn(isMoving) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	onScreenPerson *thisPerson = findPerson(objectNumber);
 	if (thisPerson) {
@@ -2041,9 +2186,11 @@ builtIn(isMoving) {
 builtIn(fetchEvent) {
 	UNUSEDALL
 	int obj1, obj2;
-	if (!getValueType(obj2, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(obj2, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(obj1, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(obj1, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	int fNum = getCombinationFunction(obj1, obj2);
@@ -2064,7 +2211,8 @@ builtIn(deleteFile) {
 	trimStack(fun->stack);
 	char *nam = encodeFilename(namNormal);
 	delete namNormal;
-	if (failSecurityCheck(nam)) return BR_ERROR;
+	if (failSecurityCheck(nam))
+		return BR_ERROR;
 	setVariable(fun->reg, SVT_INT, remove(nam));
 	delete nam;
 
@@ -2078,29 +2226,32 @@ builtIn(renameFile) {
 	temp = getTextFromAnyVar(fun->stack->thisVar);
 	char *newnam = encodeFilename(temp);
 	trimStack(fun->stack);
-	if (failSecurityCheck(newnam)) return BR_ERROR;
+	if (failSecurityCheck(newnam))
+		return BR_ERROR;
 	delete temp;
 
 	temp = getTextFromAnyVar(fun->stack->thisVar);
 	char *nam = encodeFilename(temp);
 	trimStack(fun->stack);
-	if (failSecurityCheck(nam)) return BR_ERROR;
+	if (failSecurityCheck(nam))
+		return BR_ERROR;
 	delete temp;
 
 	setVariable(fun->reg, SVT_INT, rename(nam, newnam));
 	delete nam;
 	delete newnam;
 
-
 	return BR_CONTINUE;
 }
 
 builtIn(cacheSound) {
 	UNUSEDALL
 	int fileNumber;
-	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (cacheSound(fileNumber) == -1) return BR_ERROR;
+	if (cacheSound(fileNumber) == -1)
+		return BR_ERROR;
 	return BR_CONTINUE;
 }
 
@@ -2109,11 +2260,14 @@ builtIn(burnString) {
 	char *newText = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
 	int y, x;
-	if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(y, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (x == IN_THE_CENTRE) x = (winWidth - stringWidth(newText)) >> 1;
+	if (x == IN_THE_CENTRE)
+		x = (winWidth - stringWidth(newText)) >> 1;
 	fixFont(pastePalette);
 	burnStringToBackdrop(newText, x, y, pastePalette);
 	delete[] newText;
@@ -2123,9 +2277,11 @@ builtIn(burnString) {
 builtIn(setCharacterSpinSpeed) {
 	UNUSEDALL
 	int speed, who;
-	if (!getValueType(speed, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(speed, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(who, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(who, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	onScreenPerson *thisPerson = findPerson(who);
@@ -2142,9 +2298,11 @@ builtIn(setCharacterSpinSpeed) {
 builtIn(setCharacterAngleOffset) {
 	UNUSEDALL
 	int angle, who;
-	if (!getValueType(angle, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(angle, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(who, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(who, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	onScreenPerson *thisPerson = findPerson(who);
@@ -2158,18 +2316,17 @@ builtIn(setCharacterAngleOffset) {
 	return BR_CONTINUE;
 }
 
-
 builtIn(transitionMode) {
 	UNUSEDALL
 	int n;
-	if (!getValueType(n, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(n, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	fadeMode = n;
 	trimStack(fun->stack);
 	setVariable(fun->reg, SVT_INT, 1);
 	return BR_CONTINUE;
 }
 
-
 // Removed function - does nothing
 builtIn(_rem_updateDisplay) {
 	UNUSEDALL
@@ -2182,11 +2339,13 @@ builtIn(getSoundCache) {
 	UNUSEDALL
 	fun->reg.varType = SVT_STACK;
 	fun->reg.varData.theStack = new stackHandler;
-	if (!checkNew(fun->reg.varData.theStack)) return BR_ERROR;
+	if (!checkNew(fun->reg.varData.theStack))
+		return BR_ERROR;
 	fun->reg.varData.theStack->first = NULL;
 	fun->reg.varData.theStack->last = NULL;
 	fun->reg.varData.theStack->timesUsed = 1;
-	if (!getSoundCacheStack(fun->reg.varData.theStack)) return BR_ERROR;
+	if (!getSoundCacheStack(fun->reg.varData.theStack))
+		return BR_ERROR;
 	return BR_CONTINUE;
 }
 
@@ -2194,19 +2353,22 @@ builtIn(saveCustomData) {
 	UNUSEDALL
 	// saveCustomData (thisStack, fileName);
 	char *fileNameB = getTextFromAnyVar(fun->stack->thisVar);
-	if (!checkNew(fileNameB)) return BR_ERROR;
+	if (!checkNew(fileNameB))
+		return BR_ERROR;
 
 	char *fileName = encodeFilename(fileNameB);
 	delete fileNameB;
 
-	if (failSecurityCheck(fileName)) return BR_ERROR;
+	if (failSecurityCheck(fileName))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	if (fun->stack->thisVar.varType != SVT_STACK) {
 		fatal("First parameter isn't a stack");
 		return BR_ERROR;
 	}
-	if (!stackToFile(fileName, fun->stack->thisVar)) return BR_ERROR;
+	if (!stackToFile(fileName, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	delete fileName;
 	return BR_CONTINUE;
@@ -2216,22 +2378,26 @@ builtIn(loadCustomData) {
 	UNUSEDALL
 
 	char *newTextA = getTextFromAnyVar(fun->stack->thisVar);
-	if (!checkNew(newTextA)) return BR_ERROR;
+	if (!checkNew(newTextA))
+		return BR_ERROR;
 
 	char *newText = encodeFilename(newTextA);
 	delete newTextA;
 
-	if (failSecurityCheck(newText)) return BR_ERROR;
+	if (failSecurityCheck(newText))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	unlinkVar(fun->reg);
 	fun->reg.varType = SVT_STACK;
 	fun->reg.varData.theStack = new stackHandler;
-	if (!checkNew(fun->reg.varData.theStack)) return BR_ERROR;
+	if (!checkNew(fun->reg.varData.theStack))
+		return BR_ERROR;
 	fun->reg.varData.theStack->first = NULL;
 	fun->reg.varData.theStack->last = NULL;
 	fun->reg.varData.theStack->timesUsed = 1;
-	if (!fileToStack(newText, fun->reg.varData.theStack)) return BR_ERROR;
+	if (!fileToStack(newText, fun->reg.varData.theStack))
+		return BR_ERROR;
 	delete newText;
 	return BR_CONTINUE;
 }
@@ -2239,7 +2405,8 @@ builtIn(loadCustomData) {
 builtIn(setCustomEncoding) {
 	UNUSEDALL
 	int n;
-	if (!getValueType(n, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(n, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	saveEncoding = n;
 	trimStack(fun->stack);
 	setVariable(fun->reg, SVT_INT, 1);
@@ -2249,7 +2416,8 @@ builtIn(setCustomEncoding) {
 builtIn(freeSound) {
 	UNUSEDALL
 	int v;
-	if (!getValueType(v, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(v, SVT_FILE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	huntKillFreeSound(v);
 	return BR_CONTINUE;
@@ -2262,14 +2430,18 @@ builtIn(parallaxAdd) {
 		return BR_ERROR;
 	} else {
 		int wrapX, wrapY, v;
-		if (!getValueType(wrapY, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+		if (!getValueType(wrapY, SVT_INT, fun->stack->thisVar))
+			return BR_ERROR;
 		trimStack(fun->stack);
-		if (!getValueType(wrapX, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+		if (!getValueType(wrapX, SVT_INT, fun->stack->thisVar))
+			return BR_ERROR;
 		trimStack(fun->stack);
-		if (!getValueType(v, SVT_FILE, fun->stack->thisVar)) return BR_ERROR;
+		if (!getValueType(v, SVT_FILE, fun->stack->thisVar))
+			return BR_ERROR;
 		trimStack(fun->stack);
 
-		if (!loadParallax(v, wrapX, wrapY)) return BR_ERROR;
+		if (!loadParallax(v, wrapX, wrapY))
+			return BR_ERROR;
 		setVariable(fun->reg, SVT_INT, 1);
 	}
 	return BR_CONTINUE;
@@ -2285,19 +2457,23 @@ builtIn(parallaxClear) {
 builtIn(getPixelColour) {
 	UNUSEDALL
 	int x, y;
-	if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(y, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	unlinkVar(fun->reg);
 	fun->reg.varType = SVT_STACK;
 	fun->reg.varData.theStack = new stackHandler;
-	if (!checkNew(fun->reg.varData.theStack)) return BR_ERROR;
+	if (!checkNew(fun->reg.varData.theStack))
+		return BR_ERROR;
 	fun->reg.varData.theStack->first = NULL;
 	fun->reg.varData.theStack->last = NULL;
 	fun->reg.varData.theStack->timesUsed = 1;
-	if (!getRGBIntoStack(x, y, fun->reg.varData.theStack)) return BR_ERROR;
+	if (!getRGBIntoStack(x, y, fun->reg.varData.theStack))
+		return BR_ERROR;
 
 	return BR_CONTINUE;
 }
@@ -2305,22 +2481,22 @@ builtIn(getPixelColour) {
 builtIn(makeFastArray) {
 	UNUSEDALL
 	switch (fun->stack->thisVar.varType) {
-	case SVT_STACK: {
-		bool success = makeFastArrayFromStack(fun->reg, fun->stack->thisVar.varData.theStack);
-		trimStack(fun->stack);
-		return success ? BR_CONTINUE : BR_ERROR;
-	}
-	break;
+		case SVT_STACK: {
+			bool success = makeFastArrayFromStack(fun->reg, fun->stack->thisVar.varData.theStack);
+			trimStack(fun->stack);
+			return success ? BR_CONTINUE : BR_ERROR;
+		}
+			break;
 
-	case SVT_INT: {
-		int i = fun->stack->thisVar.varData.intValue;
-		trimStack(fun->stack);
-		return makeFastArraySize(fun->reg, i) ? BR_CONTINUE : BR_ERROR;
-	}
-	break;
+		case SVT_INT: {
+			int i = fun->stack->thisVar.varData.intValue;
+			trimStack(fun->stack);
+			return makeFastArraySize(fun->reg, i) ? BR_CONTINUE : BR_ERROR;
+		}
+			break;
 
-	default:
-		break;
+		default:
+			break;
 	}
 	fatal("Parameter must be a number or a stack.");
 	return BR_ERROR;
@@ -2329,7 +2505,8 @@ builtIn(makeFastArray) {
 builtIn(getCharacterScale) {
 	UNUSEDALL
 	int objectNumber;
-	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(objectNumber, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	onScreenPerson *pers = findPerson(objectNumber);
@@ -2368,9 +2545,11 @@ builtIn(getFramesPerSecond) {
 builtIn(showThumbnail) {
 	UNUSEDALL
 	int x, y;
-	if (!getValueType(y, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(y, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(x, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(x, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 
 	// Encode the name!Encode the name!
@@ -2390,9 +2569,11 @@ builtIn(showThumbnail) {
 
 builtIn(setThumbnailSize) {
 	UNUSEDALL
-	if (!getValueType(thumbHeight, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(thumbHeight, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(thumbWidth, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(thumbWidth, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	if (thumbWidth < 0 || thumbHeight < 0 || thumbWidth > winWidth || thumbHeight > winHeight) {
 		char buff[50];
@@ -2406,12 +2587,15 @@ builtIn(setThumbnailSize) {
 builtIn(hasFlag) {
 	UNUSEDALL
 	int objNum, flagIndex;
-	if (!getValueType(flagIndex, SVT_INT, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(flagIndex, SVT_INT, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
-	if (!getValueType(objNum, SVT_OBJTYPE, fun->stack->thisVar)) return BR_ERROR;
+	if (!getValueType(objNum, SVT_OBJTYPE, fun->stack->thisVar))
+		return BR_ERROR;
 	trimStack(fun->stack);
 	objectType *objT = findObjectType(objNum);
-	if (!objT) return BR_ERROR;
+	if (!objT)
+		return BR_ERROR;
 	setVariable(fun->reg, SVT_INT, objT->flags & (1 << flagIndex));
 	return BR_CONTINUE;
 }
@@ -2498,19 +2682,17 @@ builtIn(doBackgroundEffect) {
 #define FUNC(special,name)      {builtIn_ ## name},
 static builtInFunctionData builtInFunctionArray[] = {
 #include "CommonCode/functionlist.h"
-};
+		};
 #undef FUNC
 
 #define FUNC(special,name)      {#name},
 char builtInFunctionNames[][25] = {
 #include "CommonCode/functionlist.h"
-};
+		};
 #undef FUNC
 
 #define NUM_FUNCS           (sizeof (builtInFunctionArray) / sizeof (builtInFunctionArray[0]))
 
-
-
 builtReturn callBuiltIn(int whichFunc, int numParams, loadedFunction *fun) {
 	// fprintf (stderr, "Calling function %d: %s\n", whichFunc, builtInFunctionNames[whichFunc]);    fflush (stderr);
 	if (numBIFNames) {
@@ -2518,18 +2700,15 @@ builtReturn callBuiltIn(int whichFunc, int numParams, loadedFunction *fun) {
 		//      deb ("IN:", (fun->originalNumber < numUserFunc) ? allUserFunc[fun->originalNumber] : "Unknown user function");
 		//      deb ("GO:", (whichFunc < numBIFNames) ? allBIFNames[whichFunc] : "Unknown built-in function");
 
-		setFatalInfo(
-		    (fun->originalNumber < numUserFunc) ? allUserFunc[fun->originalNumber] : "Unknown user function",
-		    (whichFunc < numBIFNames) ? allBIFNames[whichFunc] : "Unknown built-in function");
+		setFatalInfo((fun->originalNumber < numUserFunc) ? allUserFunc[fun->originalNumber] : "Unknown user function",
+				(whichFunc < numBIFNames) ? allBIFNames[whichFunc] : "Unknown built-in function");
 	}
 
 	if (whichFunc < NUM_FUNCS) {
 		if (paramNum[whichFunc] != -1) {
 			if (paramNum[whichFunc] != numParams) {
 				char buff[100];
-				sprintf(buff, "Built in function must have %i parameter%s",
-				        paramNum[whichFunc],
-						(paramNum[whichFunc] == 1) ? "" : "s");
+				sprintf(buff, "Built in function must have %i parameter%s", paramNum[whichFunc], (paramNum[whichFunc] == 1) ? "" : "s");
 
 				fatal(copyString(buff));
 				return BR_ERROR;
diff --git a/engines/sludge/errors.h b/engines/sludge/errors.h
index f706bad..388d4a0 100644
--- a/engines/sludge/errors.h
+++ b/engines/sludge/errors.h
@@ -56,9 +56,9 @@ namespace Sludge {
 #define ERROR_MUSIC_MEMORY_LOW      "Your computer doesn't have enough memory available to load a music resource that needs playing." _NO_MEMORY_GENERAL_
 #define ERROR_SOUND_MEMORY_LOW      "Your computer doesn't have enough memory available to load a sound resource that needs playing." _NO_MEMORY_GENERAL_
 #define ERROR_MUSIC_UNKNOWN         "I can't understand a piece of music which I've been told to play!\n\n" \
-	"Maybe it's stored in a format that SLUDGE doesn't know about... " \
-	"make sure you've got a recent version of the SLUDGE engine from http://opensludge.github.io/. " \
-	"Failing that, maybe the resource in question isn't a valid music format at all... in which case, contact the game's author and tell them what's happened."
+									"Maybe it's stored in a format that SLUDGE doesn't know about... " \
+									"make sure you've got a recent version of the SLUDGE engine from http://opensludge.github.io/. " \
+									"Failing that, maybe the resource in question isn't a valid music format at all... in which case, contact the game's author and tell them what's happened."
 #define ERROR_SOUND_UNKNOWN         "I can't understand a sample which I've been told to play!\nMake sure you've got the latest SLUDGE engine from http://opensludge.github.io/. Failing that, maybe the resource in question isn't a valid sound at all... in which case, contact the game's author and tell them what's happened."
 #define ERROR_MUSIC_ODDNESS         "I can't load a music resource I've been told to play. Sorry."
 #define ERROR_SOUND_ODDNESS         "I can't load a sound resource I've been told to play. Sorry."
diff --git a/engines/sludge/fileset.cpp b/engines/sludge/fileset.cpp
index d6ecdef..cf85814 100644
--- a/engines/sludge/fileset.cpp
+++ b/engines/sludge/fileset.cpp
@@ -44,8 +44,7 @@ bool sliceBusy = true;
 
 Common::File *bigDataFile = NULL;
 
-uint32_t startOfDataIndex, startOfTextIndex, startOfSubIndex,
-		startOfObjectIndex;
+uint32_t startOfDataIndex, startOfTextIndex, startOfSubIndex, startOfObjectIndex;
 
 bool openSubSlice(int num) {
 //	FILE * dbug = fopen ("debuggy.txt", "at");
@@ -199,8 +198,7 @@ void finishAccess() {
 
 int32_t startIndex;
 
-void setFileIndices(Common::File *fp, int numLanguages,
-		unsigned int skipBefore) {
+void setFileIndices(Common::File *fp, int numLanguages, unsigned int skipBefore) {
 	if (fp) {
 		// Keep hold of the file handle, and let things get at it
 		bigDataFile = fp;
diff --git a/engines/sludge/floor.cpp b/engines/sludge/floor.cpp
index cfb64d5..29038b3 100644
--- a/engines/sludge/floor.cpp
+++ b/engines/sludge/floor.cpp
@@ -42,17 +42,14 @@ bool pointInFloorPolygon(floorPolygon &floorPoly, int x, int y) {
 		xp_j = currentFloor->vertex[floorPoly.vertexID[j]].x;
 		yp_j = currentFloor->vertex[floorPoly.vertexID[j]].y;
 
-		if ((((yp_i <= y) && (y < yp_j)) || ((yp_j <= y) && (y < yp_i)))
-				&& (x < (xp_j - xp_i) * (y - yp_i) / (yp_j - yp_i) + xp_i)) {
-
+		if ((((yp_i <= y) && (y < yp_j)) || ((yp_j <= y) && (y < yp_i))) && (x < (xp_j - xp_i) * (y - yp_i) / (yp_j - yp_i) + xp_i)) {
 			c = !c;
 		}
 	}
 	return c;
 }
 
-bool getMatchingCorners(floorPolygon &a, floorPolygon &b, int &cornerA,
-		int &cornerB) {
+bool getMatchingCorners(floorPolygon &a, floorPolygon &b, int &cornerA, int &cornerB) {
 	int sharedVertices = 0;
 	int i, j;
 
@@ -147,8 +144,7 @@ bool setFloor(int fileNum) {
 		// Find out how many vertex IDs there are and reserve memory
 
 		currentFloor->polygon[i].numVertices = bigDataFile->readByte();
-		currentFloor->polygon[i].vertexID =
-				new int[currentFloor->polygon[i].numVertices];
+		currentFloor->polygon[i].vertexID = new int[currentFloor->polygon[i].numVertices];
 		if (!checkNew(currentFloor->polygon[i].vertexID))
 			return false;
 
@@ -196,8 +192,7 @@ bool setFloor(int fileNum) {
 	for (i = 0; i < currentFloor->numPolygons; i++) {
 		for (j = 0; j < currentFloor->numPolygons; j++) {
 			if (i != j) {
-				if (polysShareSide(currentFloor->polygon[i],
-						currentFloor->polygon[j])) {
+				if (polysShareSide(currentFloor->polygon[i], currentFloor->polygon[j])) {
 					currentFloor->matrix[i][j] = j;
 					distanceMatrix[i][j] = 1;
 				}
@@ -222,11 +217,7 @@ bool setFloor(int fileNum) {
 					// OK, so we don't know how to get from i to j...
 					for (int d = 0; d < currentFloor->numPolygons; d++) {
 						if (d != i && d != j) {
-							if (currentFloor->matrix[i][d] == d
-									&& currentFloor->matrix[d][j] >= 0
-									&& distanceMatrix[d][j]
-											<= lookForDistance) {
-
+							if (currentFloor->matrix[i][d] == d && currentFloor->matrix[d][j] >= 0 && distanceMatrix[d][j] <= lookForDistance) {
 								currentFloor->matrix[i][j] = d;
 								distanceMatrix[i][j] = lookForDistance + 1;
 								madeChange = true;
@@ -257,21 +248,11 @@ void drawFloor() {
 		nV = currentFloor->polygon[i].numVertices;
 		if (nV > 1) {
 			for (j = 1; j < nV; j++) {
-				drawLine(
-						currentFloor->vertex[currentFloor->polygon[i].vertexID[j
-								- 1]].x,
-						currentFloor->vertex[currentFloor->polygon[i].vertexID[j
-								- 1]].y,
-						currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].x,
-						currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].y);
+				drawLine(currentFloor->vertex[currentFloor->polygon[i].vertexID[j - 1]].x, currentFloor->vertex[currentFloor->polygon[i].vertexID[j - 1]].y,
+						currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].x, currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].y);
 			}
-			drawLine(
-					currentFloor->vertex[currentFloor->polygon[i].vertexID[0]].x,
-					currentFloor->vertex[currentFloor->polygon[i].vertexID[0]].y,
-					currentFloor->vertex[currentFloor->polygon[i].vertexID[nV
-							- 1]].x,
-					currentFloor->vertex[currentFloor->polygon[i].vertexID[nV
-							- 1]].y);
+			drawLine(currentFloor->vertex[currentFloor->polygon[i].vertexID[0]].x, currentFloor->vertex[currentFloor->polygon[i].vertexID[0]].y,
+					currentFloor->vertex[currentFloor->polygon[i].vertexID[nV - 1]].x, currentFloor->vertex[currentFloor->polygon[i].vertexID[nV - 1]].y);
 		}
 	}
 }
@@ -286,8 +267,7 @@ int inFloor(int x, int y) {
 	return r;
 }
 
-bool closestPointOnLine(int &closestX, int &closestY, int x1, int y1, int x2,
-		int y2, int xP, int yP) {
+bool closestPointOnLine(int &closestX, int &closestY, int x1, int y1, int x2, int y2, int xP, int yP) {
 	int xDiff = x2 - x1;
 	int yDiff = y2 - y1;
 
diff --git a/engines/sludge/floor.h b/engines/sludge/floor.h
index 50fe56e..193b6d1 100644
--- a/engines/sludge/floor.h
+++ b/engines/sludge/floor.h
@@ -54,8 +54,7 @@ bool setFloor(int fileNum);
 void drawFloor();
 int inFloor(int x, int y);
 bool getMatchingCorners(floorPolygon &, floorPolygon &, int &, int &);
-bool closestPointOnLine(int &closestX, int &closestY, int x1, int y1, int x2,
-		int y2, int xP, int yP);
+bool closestPointOnLine(int &closestX, int &closestY, int x1, int y1, int x2, int y2, int xP, int yP);
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/fonttext.cpp b/engines/sludge/fonttext.cpp
index 505078d..4dfdd10 100644
--- a/engines/sludge/fonttext.cpp
+++ b/engines/sludge/fonttext.cpp
@@ -94,17 +94,16 @@ void pasteString(char *theText, int xOff, int y, spritePalette &thePal) {
 	if (!fontTableSize)
 		return;
 
-	xOff += (int) ((float) (fontSpace >> 1) / cameraZoom);
+	xOff += (int)((float)(fontSpace >> 1) / cameraZoom);
 	while (theText[a]) {
 		c = u8_nextchar(theText, &a);
 		mySprite = &theFont.sprites[fontInTable(c)];
 		fontSprite(xOff, y, *mySprite, thePal);
-		xOff += (int) ((double) (mySprite->surface.w + fontSpace) / cameraZoom);
+		xOff += (int)((double)(mySprite->surface.w + fontSpace) / cameraZoom);
 	}
 }
 
-void pasteStringToBackdrop(char *theText, int xOff, int y,
-		spritePalette &thePal) {
+void pasteStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal) {
 	sprite *mySprite;
 	int a = 0;
 	uint32_t c;
@@ -121,8 +120,7 @@ void pasteStringToBackdrop(char *theText, int xOff, int y,
 	}
 }
 
-void burnStringToBackdrop(char *theText, int xOff, int y,
-		spritePalette &thePal) {
+void burnStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal) {
 	sprite *mySprite;
 	int a = 0;
 	uint32_t c;
diff --git a/engines/sludge/freeze.cpp b/engines/sludge/freeze.cpp
index 0d797b2..d5aa29d 100644
--- a/engines/sludge/freeze.cpp
+++ b/engines/sludge/freeze.cpp
@@ -156,7 +156,7 @@ bool freeze() {
 	// Grab a copy of the current scene
 	freezeGraphics();
 #if 0
-	newFreezer -> backdropTextureName = backdropTextureName;
+	newFreezer->backdropTextureName = backdropTextureName;
 #endif
 	int picWidth = sceneWidth;
 	int picHeight = sceneHeight;
@@ -165,8 +165,9 @@ bool freeze() {
 		picHeight = getNextPOT(picHeight);
 	}
 #if 0
-	newFreezer -> backdropTexture = new GLubyte [picHeight * picWidth * 4];
-	if (! checkNew(newFreezer -> backdropTexture)) return false;
+	newFreezer->backdropTexture = new GLubyte[picHeight * picWidth * 4];
+	if (!checkNew(newFreezer->backdropTexture))
+		return false;
 
 	saveTexture(backdropTextureName, newFreezer->backdropTexture);
 
@@ -178,16 +179,16 @@ bool freeze() {
 	newFreezer->cameraY = cameraY;
 	newFreezer->cameraZoom = cameraZoom;
 #if 0
-	newFreezer -> lightMapTexture = lightMap.data;
-	newFreezer -> lightMapTextureName = lightMap.name;
-	newFreezer -> lightMapNumber = lightMapNumber;
+	newFreezer->lightMapTexture = lightMap.data;
+	newFreezer->lightMapTextureName = lightMap.name;
+	newFreezer->lightMapNumber = lightMapNumber;
 	lightMap.data = NULL;
 	lightMap.name = 0;
-	newFreezer -> parallaxStuff = parallaxStuff;
+	newFreezer->parallaxStuff = parallaxStuff;
 	parallaxStuff = NULL;
-	newFreezer -> zBufferImage = zBuffer.tex;
-	newFreezer -> zBufferNumber = zBuffer.originalNum;
-	newFreezer -> zPanels = zBuffer.numPanels;
+	newFreezer->zBufferImage = zBuffer.tex;
+	newFreezer->zBufferNumber = zBuffer.originalNum;
+	newFreezer->zPanels = zBuffer.numPanels;
 	zBuffer.tex = NULL;
 #endif
 	// resizeBackdrop kills parallax stuff, light map, z-buffer...
@@ -198,8 +199,8 @@ bool freeze() {
 		picWidth = getNextPOT(sceneWidth);
 		picHeight = getNextPOT(sceneHeight);
 #if 0
-		backdropTexW = (double) sceneWidth / picWidth;
-		backdropTexH = (double) sceneHeight / picHeight;
+		backdropTexW = (double)sceneWidth / picWidth;
+		backdropTexH = (double)sceneHeight / picHeight;
 #endif
 	}
 
@@ -210,19 +211,19 @@ bool freeze() {
 	backdropExists = true;
 
 	// Free texture memory used by old stuff
-	parallaxStuff = newFreezer -> parallaxStuff;
+	parallaxStuff = newFreezer->parallaxStuff;
 	while (parallaxStuff) {
-		deleteTextures(1, &parallaxStuff -> textureName);
-		parallaxStuff = parallaxStuff -> next;
+		deleteTextures(1, &parallaxStuff->textureName);
+		parallaxStuff = parallaxStuff->next;
 	}
-	if (newFreezer -> zBufferImage) {
+	if (newFreezer->zBufferImage) {
 		deleteTextures(1, &zBuffer.texName);
 	}
-	if (newFreezer -> lightMapTextureName) {
-		deleteTextures(1, &newFreezer -> lightMapTextureName);
+	if (newFreezer->lightMapTextureName) {
+		deleteTextures(1, &newFreezer->lightMapTextureName);
 	}
-	if (newFreezer -> backdropTextureName) {
-		deleteTextures(1, &newFreezer -> backdropTextureName);
+	if (newFreezer->backdropTextureName) {
+		deleteTextures(1, &newFreezer->backdropTextureName);
 	}
 #endif
 	newFreezer->allPeople = allPeople;
@@ -282,11 +283,11 @@ void unfreeze(bool killImage) {
 
 	cameraX = frozenStuff->cameraX;
 	cameraY = frozenStuff->cameraY;
-	input.mouseX = (int) (input.mouseX * cameraZoom);
-	input.mouseY = (int) (input.mouseY * cameraZoom);
+	input.mouseX = (int)(input.mouseX * cameraZoom);
+	input.mouseY = (int)(input.mouseY * cameraZoom);
 	cameraZoom = frozenStuff->cameraZoom;
-	input.mouseX = (int) (input.mouseX / cameraZoom);
-	input.mouseY = (int) (input.mouseY / cameraZoom);
+	input.mouseX = (int)(input.mouseX / cameraZoom);
+	input.mouseY = (int)(input.mouseY / cameraZoom);
 	setPixelCoords(false);
 
 	killAllPeople();
@@ -297,31 +298,33 @@ void unfreeze(bool killImage) {
 
 	killLightMap();
 #if 0
-	lightMap.data = frozenStuff -> lightMapTexture;
-	lightMap.name = frozenStuff -> lightMapTextureName;
-	lightMapNumber = frozenStuff -> lightMapNumber;
+	lightMap.data = frozenStuff->lightMapTexture;
+	lightMap.name = frozenStuff->lightMapTextureName;
+	lightMapNumber = frozenStuff->lightMapNumber;
 	if (lightMapNumber) {
 		lightMap.name = 0;
 		loadLightMap(lightMapNumber);
 	}
 
 	killZBuffer();
-	zBuffer.tex = frozenStuff -> zBufferImage;
-	zBuffer.originalNum = frozenStuff -> zBufferNumber;
-	zBuffer.numPanels = frozenStuff -> zPanels;
+	zBuffer.tex = frozenStuff->zBufferImage;
+	zBuffer.originalNum = frozenStuff->zBufferNumber;
+	zBuffer.numPanels = frozenStuff->zPanels;
 	if (zBuffer.numPanels) {
 		zBuffer.texName = 0;
 		setZBuffer(zBuffer.originalNum);
 	}
 
 	killParallax();
-	parallaxStuff = frozenStuff -> parallaxStuff;
+	parallaxStuff = frozenStuff->parallaxStuff;
 	reloadParallaxTextures();
 
-	if (killImage) killBackDrop();
-	backdropTextureName = frozenStuff -> backdropTextureName;
-	if (backdropTexture) delete[] backdropTexture;
-	backdropTexture = frozenStuff -> backdropTexture;
+	if (killImage)
+		killBackDrop();
+	backdropTextureName = frozenStuff->backdropTextureName;
+	if (backdropTexture)
+		delete[] backdropTexture;
+	backdropTexture = frozenStuff->backdropTexture;
 	backdropExists = true;
 	if (backdropTextureName) {
 		backdropTextureName = 0;
@@ -340,12 +343,12 @@ void unfreeze(bool killImage) {
 
 		int picWidth = sceneWidth;
 		int picHeight = sceneHeight;
-		if (! NPOT_textures) {
+		if (!NPOT_textures) {
 			picWidth = getNextPOT(picWidth);
 			picHeight = getNextPOT(picHeight);
 		}
 		// Restore the backdrop
-		texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, frozenStuff -> backdropTexture, backdropTextureName);
+		texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, frozenStuff->backdropTexture, backdropTextureName);
 	}
 #endif
 	deleteAnim(mouseCursorAnim);
diff --git a/engines/sludge/language.cpp b/engines/sludge/language.cpp
index b6a7ab6..8d795a0 100644
--- a/engines/sludge/language.cpp
+++ b/engines/sludge/language.cpp
@@ -91,8 +91,7 @@ void readIniFile(char *filename) {
 
 	Common::File fd;
 	if (!fd.open(langName)) {
-		debug(kSludgeDebugDataLoad, "Fail to open language file : %s",
-				langName);
+		debug(kSludgeDebugDataLoad, "Fail to open language file : %s", langName);
 		return;
 	}
 
@@ -121,45 +120,45 @@ void readIniFile(char *filename) {
 			keepGoing = false;
 		}
 		switch (readChar) {
-		case '\n':
-		case '\r':
-			if (doingSecond) {
-				if (strcmp(lineSoFar, "LANGUAGE") == 0) {
-					gameSettings.languageID = stringToInt(secondSoFar);
-				} else if (strcmp(lineSoFar, "WINDOW") == 0) {
-					gameSettings.userFullScreen = !stringToInt(secondSoFar);
-				} else if (strcmp(lineSoFar, "REFRESH") == 0) {
-					gameSettings.refreshRate = stringToInt(secondSoFar);
-				} else if (strcmp(lineSoFar, "ANTIALIAS") == 0) {
-					gameSettings.antiAlias = stringToInt(secondSoFar);
-				} else if (strcmp(lineSoFar, "FIXEDPIXELS") == 0) {
-					gameSettings.fixedPixels = stringToInt(secondSoFar);
-				} else if (strcmp(lineSoFar, "NOSTARTWINDOW") == 0) {
-					gameSettings.noStartWindow = stringToInt(secondSoFar);
-				} else if (strcmp(lineSoFar, "DEBUGMODE") == 0) {
-					gameSettings.debugMode = stringToInt(secondSoFar);
+			case '\n':
+			case '\r':
+				if (doingSecond) {
+					if (strcmp(lineSoFar, "LANGUAGE") == 0) {
+						gameSettings.languageID = stringToInt(secondSoFar);
+					} else if (strcmp(lineSoFar, "WINDOW") == 0) {
+						gameSettings.userFullScreen = !stringToInt(secondSoFar);
+					} else if (strcmp(lineSoFar, "REFRESH") == 0) {
+						gameSettings.refreshRate = stringToInt(secondSoFar);
+					} else if (strcmp(lineSoFar, "ANTIALIAS") == 0) {
+						gameSettings.antiAlias = stringToInt(secondSoFar);
+					} else if (strcmp(lineSoFar, "FIXEDPIXELS") == 0) {
+						gameSettings.fixedPixels = stringToInt(secondSoFar);
+					} else if (strcmp(lineSoFar, "NOSTARTWINDOW") == 0) {
+						gameSettings.noStartWindow = stringToInt(secondSoFar);
+					} else if (strcmp(lineSoFar, "DEBUGMODE") == 0) {
+						gameSettings.debugMode = stringToInt(secondSoFar);
+					}
 				}
-			}
-			here = 0;
-			doingSecond = false;
-			lineSoFar[0] = 0;
-			secondSoFar[0] = 0;
-			break;
-
-		case '=':
-			doingSecond = true;
-			here = 0;
-			break;
-
-		default:
-			if (doingSecond) {
-				secondSoFar[here++] = readChar;
-				secondSoFar[here] = 0;
-			} else {
-				lineSoFar[here++] = readChar;
-				lineSoFar[here] = 0;
-			}
-			break;
+				here = 0;
+				doingSecond = false;
+				lineSoFar[0] = 0;
+				secondSoFar[0] = 0;
+				break;
+
+			case '=':
+				doingSecond = true;
+				here = 0;
+				break;
+
+			default:
+				if (doingSecond) {
+					secondSoFar[here++] = readChar;
+					secondSoFar[here] = 0;
+				} else {
+					lineSoFar[here++] = readChar;
+					lineSoFar[here] = 0;
+				}
+				break;
 		}
 	} while (keepGoing);
 
@@ -194,14 +193,12 @@ void makeLanguageTable(Common::File *table) {
 
 	for (unsigned int i = 0; i <= gameSettings.numLanguages; i++) {
 		languageTable[i] = i ? table->readUint16BE() : 0;
-		debug(kSludgeDebugDataLoad, "languageTable %i: %i", i,
-				languageTable[i]);
+		debug(kSludgeDebugDataLoad, "languageTable %i: %i", i, languageTable[i]);
 		languageName[i] = 0;
 		if (gameVersion >= VERSION(2, 0)) {
 			if (gameSettings.numLanguages) {
 				languageName[i] = readString(table);
-				debug(kSludgeDebugDataLoad, "languageName %i: %s\n", i,
-						languageName[i]);
+				debug(kSludgeDebugDataLoad, "languageName %i: %s\n", i, languageName[i]);
 			}
 		}
 	}
diff --git a/engines/sludge/line.cpp b/engines/sludge/line.cpp
index 1feba03..0067163 100644
--- a/engines/sludge/line.cpp
+++ b/engines/sludge/line.cpp
@@ -37,35 +37,47 @@ void drawLine(int x1, int y1, int x2, int y2) {
 	int x, y;
 	bool backwards = false;
 #if 0
-	if (x1 < 0) x1 = 0;
-	if (y1 < 0) y1 = 0;
-	if (x2 < 0) x2 = 0;
-	if (y2 < 0) y2 = 0;
-	if (x1 > sceneWidth) x1 = sceneWidth - 1;
-	if (x2 > sceneWidth) x2 = sceneWidth - 1;
-	if (y1 > sceneHeight) y1 = sceneHeight - 1;
-	if (y2 > sceneHeight) y2 = sceneHeight - 1;
+	if (x1 < 0)
+		x1 = 0;
+	if (y1 < 0)
+		y1 = 0;
+	if (x2 < 0)
+		x2 = 0;
+	if (y2 < 0)
+		y2 = 0;
+	if (x1 > sceneWidth)
+		x1 = sceneWidth - 1;
+	if (x2 > sceneWidth)
+		x2 = sceneWidth - 1;
+	if (y1 > sceneHeight)
+		y1 = sceneHeight - 1;
+	if (y2 > sceneHeight)
+		y2 = sceneHeight - 1;
 
 	if (x1 > x2) {
 		x = x2;
 		backwards = !backwards;
-	} else x = x1;
+	} else
+		x = x1;
 
 	if (y1 > y2) {
 		y = y2;
 		backwards = !backwards;
-	} else y = y1;
+	} else
+		y = y1;
 
 	int diffX = abs(x2 - x1);
 	int diffY = abs(y2 - y1);
 
-	if (! diffX) {
+	if (!diffX) {
 		diffX = 1;
-		if (x == sceneWidth - 1) x = sceneWidth - 2;
+		if (x == sceneWidth - 1)
+			x = sceneWidth - 2;
 	}
-	if (! diffY) {
+	if (!diffY) {
 		diffY = 1;
-		if (y == sceneHeight - 1) y = sceneHeight - 2;
+		if (y == sceneHeight - 1)
+			y = sceneHeight - 2;
 	}
 	setPixelCoords(true);
 
@@ -82,19 +94,10 @@ void drawLine(int x1, int y1, int x2, int y2) {
 			// Render the scene - first the old backdrop
 			glBindTexture(GL_TEXTURE_2D, backdropTextureName);
 			//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
-			const GLfloat vertices[] = {
-				(GLfloat) - x - xoffset, (GLfloat)1 - y - yoffset, 0.,
-				(GLfloat)sceneWidth - x - xoffset, (GLfloat)1 - y - yoffset, 0.,
-				(GLfloat) - x - xoffset, (GLfloat)sceneHeight - y - yoffset, 0.,
-				(GLfloat)sceneWidth - x - xoffset, (GLfloat)sceneHeight - y - yoffset, 0.
-			};
-
-			const GLfloat texCoords[] = {
-				0.0f, 0.0f,
-				backdropTexW, 0.0f,
-				0.0f, backdropTexH,
-				backdropTexW, backdropTexH
-			};
+			const GLfloat vertices[] = { (GLfloat)-x - xoffset, (GLfloat)1 - y - yoffset, 0., (GLfloat)sceneWidth - x - xoffset, (GLfloat)1 - y - yoffset, 0., (GLfloat)-x - xoffset,
+					(GLfloat)sceneHeight - y - yoffset, 0., (GLfloat)sceneWidth - x - xoffset, (GLfloat)sceneHeight - y - yoffset, 0. };
+
+			const GLfloat texCoords[] = { 0.0f, 0.0f, backdropTexW, 0.0f, 0.0f, backdropTexH, backdropTexW, backdropTexH };
 
 			glUseProgram(shader.texture);
 
@@ -105,15 +108,12 @@ void drawLine(int x1, int y1, int x2, int y2) {
 			//FIXME:Removing the lines doesn't work, but also didn't work properly before.
 
 			GLint xo1 = -xoffset, xo2 = -xoffset;
-			if (! backwards) {
+			if (!backwards) {
 				xo2 += diffX;
 			} else {
 				xo1 += diffX;
 			}
-			const GLint lineVertices[] = {
-				xo1, -yoffset, 0,
-				xo2, -yoffset + diffY, 0,
-			};
+			const GLint lineVertices[] = { xo1, -yoffset, 0, xo2, -yoffset + diffY, 0, };
 
 			glUseProgram(shader.color);
 
diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index f3eb93f..50ef4cc 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -113,14 +113,13 @@ void saveStack(variableStack *vs, Common::WriteStream *stream) {
 	}
 }
 
-variableStack *loadStack(Common::SeekableReadStream *stream,
-		variableStack **last) {
+variableStack *loadStack(Common::SeekableReadStream *stream, variableStack **last) {
 	int elements = stream->readUint16BE();
 	int a;
 	variableStack *first = NULL;
 	variableStack * * changeMe = &first;
 
-	for (a = 0; a < elements; ++a) {
+	for (a = 0; a < elements; a++) {
 		variableStack *nS = new variableStack;
 		if (!checkNew(nS))
 			return NULL;
@@ -147,7 +146,7 @@ bool saveStackRef(stackHandler *vs, Common::WriteStream *stream) {
 			return true;
 		}
 		s = s->next;
-		++a;
+		a++;
 	}
 	stream->writeByte(0);
 	saveStack(vs->first, stream);
@@ -233,36 +232,34 @@ bool saveVariable(variable *from, Common::WriteStream *stream) {
 
 	stream->writeByte(from->varType);
 	switch (from->varType) {
-	case SVT_INT:
-	case SVT_FUNC:
-	case SVT_BUILT:
-	case SVT_FILE:
-	case SVT_OBJTYPE:
-		stream->writeUint32LE(from->varData.intValue);
-		return true;
-
-	case SVT_STRING:
-		writeString(from->varData.theString, stream);
-		return true;
-
-	case SVT_STACK:
-		return saveStackRef(from->varData.theStack, stream);
-
-	case SVT_COSTUME:
-		saveCostume(from->varData.costumeHandler, stream);
-		return false;
+		case SVT_INT:
+		case SVT_FUNC:
+		case SVT_BUILT:
+		case SVT_FILE:
+		case SVT_OBJTYPE:
+			stream->writeUint32LE(from->varData.intValue);
+			return true;
 
-	case SVT_ANIM:
-		saveAnim(from->varData.animHandler, stream);
-		return false;
+		case SVT_STRING:
+			writeString(from->varData.theString, stream);
+			return true;
 
-	case SVT_NULL:
-		return false;
+		case SVT_STACK:
+			return saveStackRef(from->varData.theStack, stream);
+
+		case SVT_COSTUME:
+			saveCostume(from->varData.costumeHandler, stream);
+			return false;
+
+		case SVT_ANIM:
+			saveAnim(from->varData.animHandler, stream);
+			return false;
+
+		case SVT_NULL:
+			return false;
 
-	default:
-		fatal("Can't save variables of this type:",
-				(from->varType < SVT_NUM_TYPES) ?
-						typeName[from->varType] : "bad ID");
+		default:
+			fatal("Can't save variables of this type:", (from->varType < SVT_NUM_TYPES) ? typeName[from->varType] : "bad ID");
 	}
 	return true;
 }
@@ -270,45 +267,45 @@ bool saveVariable(variable *from, Common::WriteStream *stream) {
 bool loadVariable(variable *to, Common::SeekableReadStream *stream) {
 	to->varType = (variableType)stream->readByte();
 	switch (to->varType) {
-	case SVT_INT:
-	case SVT_FUNC:
-	case SVT_BUILT:
-	case SVT_FILE:
-	case SVT_OBJTYPE:
-		to->varData.intValue = stream->readUint32LE();
-		return true;
-
-	case SVT_STRING:
-		to->varData.theString = readString(stream);
-		return true;
-
-	case SVT_STACK:
-		to->varData.theStack = loadStackRef(stream);
+		case SVT_INT:
+		case SVT_FUNC:
+		case SVT_BUILT:
+		case SVT_FILE:
+		case SVT_OBJTYPE:
+			to->varData.intValue = stream->readUint32LE();
+			return true;
+
+		case SVT_STRING:
+			to->varData.theString = readString(stream);
+			return true;
+
+		case SVT_STACK:
+			to->varData.theStack = loadStackRef(stream);
 #if DEBUG_STACKINESS
-		{
-			char *str = getTextFromAnyVar(*to);
-			stackDebug((stackfp, "just loaded %s\n", str));
-			delete str;
-		}
+			{
+				char *str = getTextFromAnyVar(*to);
+				stackDebug((stackfp, "just loaded %s\n", str));
+				delete str;
+			}
 #endif
-		return true;
+			return true;
 
-	case SVT_COSTUME:
-		to->varData.costumeHandler = new persona;
-		if (!checkNew(to->varData.costumeHandler))
-			return false;
-		loadCostume(to->varData.costumeHandler, stream);
-		return true;
+		case SVT_COSTUME:
+			to->varData.costumeHandler = new persona;
+			if (!checkNew(to->varData.costumeHandler))
+				return false;
+			loadCostume(to->varData.costumeHandler, stream);
+			return true;
 
-	case SVT_ANIM:
-		to->varData.animHandler = new personaAnimation;
-		if (!checkNew(to->varData.animHandler))
-			return false;
-		loadAnim(to->varData.animHandler, stream);
-		return true;
+		case SVT_ANIM:
+			to->varData.animHandler = new personaAnimation;
+			if (!checkNew(to->varData.animHandler))
+				return false;
+			loadAnim(to->varData.animHandler, stream);
+			return true;
 
-	default:
-		break;
+		default:
+			break;
 	}
 	return true;
 }
diff --git a/engines/sludge/moreio.cpp b/engines/sludge/moreio.cpp
index ed3a7ec..da86553 100644
--- a/engines/sludge/moreio.cpp
+++ b/engines/sludge/moreio.cpp
@@ -136,50 +136,50 @@ char *encodeFilename(char *nameIn) {
 		int i = 0;
 		while (*nameIn) {
 			switch (*nameIn) {
-			case '<':
-				newName[i++] = '_';
-				newName[i++] = 'L';
-				break;
-			case '>':
-				newName[i++] = '_';
-				newName[i++] = 'G';
-				break;
-			case '|':
-				newName[i++] = '_';
-				newName[i++] = 'P';
-				break;
-			case '_':
-				newName[i++] = '_';
-				newName[i++] = 'U';
-				break;
-			case '\"':
-				newName[i++] = '_';
-				newName[i++] = 'S';
-				break;
-			case '\\':
-				newName[i++] = '_';
-				newName[i++] = 'B';
-				break;
-			case '/':
-				newName[i++] = '_';
-				newName[i++] = 'F';
-				break;
-			case ':':
-				newName[i++] = '_';
-				newName[i++] = 'C';
-				break;
-			case '*':
-				newName[i++] = '_';
-				newName[i++] = 'A';
-				break;
-			case '?':
-				newName[i++] = '_';
-				newName[i++] = 'Q';
-				break;
+				case '<':
+					newName[i++] = '_';
+					newName[i++] = 'L';
+					break;
+				case '>':
+					newName[i++] = '_';
+					newName[i++] = 'G';
+					break;
+				case '|':
+					newName[i++] = '_';
+					newName[i++] = 'P';
+					break;
+				case '_':
+					newName[i++] = '_';
+					newName[i++] = 'U';
+					break;
+				case '\"':
+					newName[i++] = '_';
+					newName[i++] = 'S';
+					break;
+				case '\\':
+					newName[i++] = '_';
+					newName[i++] = 'B';
+					break;
+				case '/':
+					newName[i++] = '_';
+					newName[i++] = 'F';
+					break;
+				case ':':
+					newName[i++] = '_';
+					newName[i++] = 'C';
+					break;
+				case '*':
+					newName[i++] = '_';
+					newName[i++] = 'A';
+					break;
+				case '?':
+					newName[i++] = '_';
+					newName[i++] = 'Q';
+					break;
 
-			default:
-				newName[i++] = *nameIn;
-				break;
+				default:
+					newName[i++] = *nameIn;
+					break;
 			}
 			newName[i] = 0;
 			nameIn++;
@@ -211,48 +211,48 @@ char *decodeFilename(char *nameIn) {
 			if (*nameIn == '_') {
 				nameIn++;
 				switch (*nameIn) {
-				case 'L':
-					newName[i] = '<';
-					nameIn++;
-					break;
-				case 'G':
-					newName[i] = '>';
-					nameIn++;
-					break;
-				case 'P':
-					newName[i] = '|';
-					nameIn++;
-					break;
-				case 'U':
-					newName[i] = '_';
-					nameIn++;
-					break;
-				case 'S':
-					newName[i] = '\"';
-					nameIn++;
-					break;
-				case 'B':
-					newName[i] = '\\';
-					nameIn++;
-					break;
-				case 'F':
-					newName[i] = '/';
-					nameIn++;
-					break;
-				case 'C':
-					newName[i] = ':';
-					nameIn++;
-					break;
-				case 'A':
-					newName[i] = '*';
-					nameIn++;
-					break;
-				case 'Q':
-					newName[i] = '?';
-					nameIn++;
-					break;
-				default:
-					newName[i] = '_';
+					case 'L':
+						newName[i] = '<';
+						nameIn++;
+						break;
+					case 'G':
+						newName[i] = '>';
+						nameIn++;
+						break;
+					case 'P':
+						newName[i] = '|';
+						nameIn++;
+						break;
+					case 'U':
+						newName[i] = '_';
+						nameIn++;
+						break;
+					case 'S':
+						newName[i] = '\"';
+						nameIn++;
+						break;
+					case 'B':
+						newName[i] = '\\';
+						nameIn++;
+						break;
+					case 'F':
+						newName[i] = '/';
+						nameIn++;
+						break;
+					case 'C':
+						newName[i] = ':';
+						nameIn++;
+						break;
+					case 'A':
+						newName[i] = '*';
+						nameIn++;
+						break;
+					case 'Q':
+						newName[i] = '?';
+						nameIn++;
+						break;
+					default:
+						newName[i] = '_';
 				}
 			} else {
 				newName[i] = *nameIn;
diff --git a/engines/sludge/newfatal.cpp b/engines/sludge/newfatal.cpp
index 9441569..a6887d4 100644
--- a/engines/sludge/newfatal.cpp
+++ b/engines/sludge/newfatal.cpp
@@ -42,9 +42,7 @@ namespace Sludge {
 const char emergencyMemoryMessage[] = "Out of memory displaying error message!";
 
 static char *fatalMessage = NULL;
-static char *fatalInfo =
-		joinStrings("Initialisation error! Something went wrong before we even got started!",
-					"");
+static char *fatalInfo = joinStrings("Initialisation error! Something went wrong before we even got started!", "");
 
 extern int numResourceNames /* = 0*/;
 extern char * *allResourceNames /*= NULL*/;
@@ -85,9 +83,7 @@ void warning(const char *l) {
 void registerWindowForFatal() {
 	delete fatalInfo;
 	fatalInfo =
-			joinStrings(
-					"There's an error with this SLUDGE game! If you're designing this game, please turn on verbose error messages in the project manager and recompile. If not, please contact the author saying where and how this problem occured.",
-					"");
+			joinStrings("There's an error with this SLUDGE game! If you're designing this game, please turn on verbose error messages in the project manager and recompile. If not, please contact the author saying where and how this problem occured.", "");
 }
 
 #if 0
@@ -132,8 +128,7 @@ void setFatalInfo(const char *userFunc, const char *BIF) {
 	delete fatalInfo;
 	fatalInfo = new char[strlen(userFunc) + strlen(BIF) + 38];
 	if (fatalInfo)
-		sprintf(fatalInfo, "Currently in this sub: %s\nCalling: %s", userFunc,
-				BIF);
+		sprintf(fatalInfo, "Currently in this sub: %s\nCalling: %s", userFunc, BIF);
 	debug(kSludgeDebugFatal, "%s", fatalInfo);
 }
 
@@ -144,8 +139,7 @@ void setResourceForFatal(int n) {
 int fatal(const char *str1) {
 	if (numResourceNames && resourceForFatal != -1) {
 		const char *r = resourceNameFromNum(resourceForFatal);
-		char *newStr = new char[strlen(str1) + strlen(r) + strlen(fatalInfo)
-				+ 14];
+		char *newStr = new char[strlen(str1) + strlen(r) + strlen(fatalInfo) + 14];
 		if (checkNew(newStr)) {
 			sprintf(newStr, "%s\nResource: %s\n\n%s", fatalInfo, r, str1);
 			inFatal(newStr);
diff --git a/engines/sludge/objtypes.cpp b/engines/sludge/objtypes.cpp
index 3c79374..a765f3f 100644
--- a/engines/sludge/objtypes.cpp
+++ b/engines/sludge/objtypes.cpp
@@ -79,8 +79,7 @@ objectType *loadObjectType(int i) {
 			}
 
 			newType->numCom = bigDataFile->readUint16BE();
-			newType->allCombis =
-					(newType->numCom) ? new combination[newType->numCom] : NULL;
+			newType->allCombis = (newType->numCom) ? new combination[newType->numCom] : NULL;
 
 #if DEBUG_COMBINATIONS
 			FILE *callEventLog = fopen("callEventLog.txt", "at");
diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index 9b19bbf..fb21037 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -71,8 +71,7 @@ inline int TF_abs(int a) {
 }
 
 void setFrames(onScreenPerson &m, int a) {
-	m.myAnim = m.myPersona->animation[(a * m.myPersona->numDirections)
-			+ m.direction];
+	m.myAnim = m.myPersona->animation[(a * m.myPersona->numDirections) + m.direction];
 }
 
 personaAnimation *createPersonaAnim(int num, variableStack *&stacky) {
@@ -93,10 +92,8 @@ personaAnimation *createPersonaAnim(int num, variableStack *&stacky) {
 		} else if (stacky->thisVar.varType == SVT_FUNC) {
 			newP->frames[a].noise = -stacky->thisVar.varData.intValue;
 		} else if (stacky->thisVar.varType == SVT_STACK) {
-			getValueType(frameNum, SVT_INT,
-					stacky->thisVar.varData.theStack->first->thisVar);
-			getValueType(howMany, SVT_INT,
-					stacky->thisVar.varData.theStack->first->next->thisVar);
+			getValueType(frameNum, SVT_INT, stacky->thisVar.varData.theStack->first->thisVar);
+			getValueType(howMany, SVT_INT, stacky->thisVar.varData.theStack->first->next->thisVar);
 		} else {
 			getValueType(frameNum, SVT_INT, stacky->thisVar);
 			howMany = 1;
@@ -182,10 +179,7 @@ bool initPeople() {
 
 void spinStep(onScreenPerson *thisPerson) {
 	int diff = (thisPerson->angle + 360) - thisPerson->wantAngle;
-	int eachSlice =
-			thisPerson->spinSpeed ?
-					thisPerson->spinSpeed :
-					(360 / thisPerson->myPersona->numDirections);
+	int eachSlice = thisPerson->spinSpeed ? thisPerson->spinSpeed : (360 / thisPerson->myPersona->numDirections);
 	while (diff > 180) {
 		diff -= 360;
 	}
@@ -217,8 +211,7 @@ bool turnPersonToFace(int thisNum, int direc) {
 		thisPerson->walking = false;
 		thisPerson->spinning = false;
 		turnMeAngle(thisPerson, direc);
-		setFrames(*thisPerson,
-				(thisPerson == speech->currentTalker) ? ANI_TALK : ANI_STAND);
+		setFrames(*thisPerson, (thisPerson == speech->currentTalker) ? ANI_TALK : ANI_STAND);
 		return true;
 	}
 	return false;
@@ -295,106 +288,106 @@ enum drawModes {
 
 void setMyDrawMode(onScreenPerson *moveMe, int h) {
 	switch (h) {
-	case drawModeTransparent3:
-		moveMe->r = moveMe->g = moveMe->b = 0;
-		moveMe->colourmix = 0;
-		moveMe->transparency = 64;
-		break;
-	case drawModeTransparent2:
-		moveMe->r = moveMe->g = moveMe->b = 0;
-		moveMe->colourmix = 0;
-		moveMe->transparency = 128;
-		break;
-	case drawModeTransparent1:
-		moveMe->r = moveMe->g = moveMe->b = 0;
-		moveMe->colourmix = 0;
-		moveMe->transparency = 192;
-		break;
-	case drawModeInvisible:
-		moveMe->r = moveMe->g = moveMe->b = 0;
-		moveMe->colourmix = 0;
-		moveMe->transparency = 254;
-		break;
-	case drawModeDark1:
-		moveMe->r = moveMe->g = moveMe->b = 0;
-		moveMe->colourmix = 192;
-		moveMe->transparency = 0;
-		break;
-	case drawModeDark2:
-		moveMe->r = moveMe->g = moveMe->b = 0;
-		moveMe->colourmix = 128;
-		moveMe->transparency = 0;
-		break;
-	case drawModeDark3:
-		moveMe->r = moveMe->g = moveMe->b = 0;
-		moveMe->colourmix = 64;
-		moveMe->transparency = 0;
-		break;
-	case drawModeBlack:
-		moveMe->r = moveMe->g = moveMe->b = 0;
-		moveMe->colourmix = 255;
-		moveMe->transparency = 0;
-		break;
-	case drawModeShadow1:
-		moveMe->r = moveMe->g = moveMe->b = 0;
-		moveMe->colourmix = 255;
-		moveMe->transparency = 64;
-		break;
-	case drawModeShadow2:
-		moveMe->r = moveMe->g = moveMe->b = 0;
-		moveMe->colourmix = 255;
-		moveMe->transparency = 128;
-		break;
-	case drawModeShadow3:
-		moveMe->r = moveMe->g = moveMe->b = 0;
-		moveMe->colourmix = 255;
-		moveMe->transparency = 192;
-		break;
-	case drawModeFoggy3:
-		moveMe->r = moveMe->g = moveMe->b = 128;
-		moveMe->colourmix = 192;
-		moveMe->transparency = 0;
-		break;
-	case drawModeFoggy2:
-		moveMe->r = moveMe->g = moveMe->b = 128;
-		moveMe->colourmix = 128;
-		moveMe->transparency = 0;
-		break;
-	case drawModeFoggy1:
-		moveMe->r = moveMe->g = moveMe->b = 128;
-		moveMe->colourmix = 64;
-		moveMe->transparency = 0;
-		break;
-	case drawModeFoggy4:
-		moveMe->r = moveMe->g = moveMe->b = 128;
-		moveMe->colourmix = 255;
-		moveMe->transparency = 0;
-		break;
-	case drawModeGlow3:
-		moveMe->r = moveMe->g = moveMe->b = 255;
-		moveMe->colourmix = 192;
-		moveMe->transparency = 0;
-		break;
-	case drawModeGlow2:
-		moveMe->r = moveMe->g = moveMe->b = 255;
-		moveMe->colourmix = 128;
-		moveMe->transparency = 0;
-		break;
-	case drawModeGlow1:
-		moveMe->r = moveMe->g = moveMe->b = 255;
-		moveMe->colourmix = 64;
-		moveMe->transparency = 0;
-		break;
-	case drawModeGlow4:
-		moveMe->r = moveMe->g = moveMe->b = 255;
-		moveMe->colourmix = 255;
-		moveMe->transparency = 0;
-		break;
-	default:
-		moveMe->r = moveMe->g = moveMe->b = 0;
-		moveMe->colourmix = 0;
-		moveMe->transparency = 0;
-		break;
+		case drawModeTransparent3:
+			moveMe->r = moveMe->g = moveMe->b = 0;
+			moveMe->colourmix = 0;
+			moveMe->transparency = 64;
+			break;
+		case drawModeTransparent2:
+			moveMe->r = moveMe->g = moveMe->b = 0;
+			moveMe->colourmix = 0;
+			moveMe->transparency = 128;
+			break;
+		case drawModeTransparent1:
+			moveMe->r = moveMe->g = moveMe->b = 0;
+			moveMe->colourmix = 0;
+			moveMe->transparency = 192;
+			break;
+		case drawModeInvisible:
+			moveMe->r = moveMe->g = moveMe->b = 0;
+			moveMe->colourmix = 0;
+			moveMe->transparency = 254;
+			break;
+		case drawModeDark1:
+			moveMe->r = moveMe->g = moveMe->b = 0;
+			moveMe->colourmix = 192;
+			moveMe->transparency = 0;
+			break;
+		case drawModeDark2:
+			moveMe->r = moveMe->g = moveMe->b = 0;
+			moveMe->colourmix = 128;
+			moveMe->transparency = 0;
+			break;
+		case drawModeDark3:
+			moveMe->r = moveMe->g = moveMe->b = 0;
+			moveMe->colourmix = 64;
+			moveMe->transparency = 0;
+			break;
+		case drawModeBlack:
+			moveMe->r = moveMe->g = moveMe->b = 0;
+			moveMe->colourmix = 255;
+			moveMe->transparency = 0;
+			break;
+		case drawModeShadow1:
+			moveMe->r = moveMe->g = moveMe->b = 0;
+			moveMe->colourmix = 255;
+			moveMe->transparency = 64;
+			break;
+		case drawModeShadow2:
+			moveMe->r = moveMe->g = moveMe->b = 0;
+			moveMe->colourmix = 255;
+			moveMe->transparency = 128;
+			break;
+		case drawModeShadow3:
+			moveMe->r = moveMe->g = moveMe->b = 0;
+			moveMe->colourmix = 255;
+			moveMe->transparency = 192;
+			break;
+		case drawModeFoggy3:
+			moveMe->r = moveMe->g = moveMe->b = 128;
+			moveMe->colourmix = 192;
+			moveMe->transparency = 0;
+			break;
+		case drawModeFoggy2:
+			moveMe->r = moveMe->g = moveMe->b = 128;
+			moveMe->colourmix = 128;
+			moveMe->transparency = 0;
+			break;
+		case drawModeFoggy1:
+			moveMe->r = moveMe->g = moveMe->b = 128;
+			moveMe->colourmix = 64;
+			moveMe->transparency = 0;
+			break;
+		case drawModeFoggy4:
+			moveMe->r = moveMe->g = moveMe->b = 128;
+			moveMe->colourmix = 255;
+			moveMe->transparency = 0;
+			break;
+		case drawModeGlow3:
+			moveMe->r = moveMe->g = moveMe->b = 255;
+			moveMe->colourmix = 192;
+			moveMe->transparency = 0;
+			break;
+		case drawModeGlow2:
+			moveMe->r = moveMe->g = moveMe->b = 255;
+			moveMe->colourmix = 128;
+			moveMe->transparency = 0;
+			break;
+		case drawModeGlow1:
+			moveMe->r = moveMe->g = moveMe->b = 255;
+			moveMe->colourmix = 64;
+			moveMe->transparency = 0;
+			break;
+		case drawModeGlow4:
+			moveMe->r = moveMe->g = moveMe->b = 255;
+			moveMe->colourmix = 255;
+			moveMe->transparency = 0;
+			break;
+		default:
+			moveMe->r = moveMe->g = moveMe->b = 0;
+			moveMe->colourmix = 0;
+			moveMe->transparency = 0;
+			break;
 	}
 
 }
@@ -417,8 +410,7 @@ void setPersonTransparency(int ob, unsigned char x) {
 	moveMe->transparency = x;
 }
 
-void setPersonColourise(int ob, unsigned char r, unsigned char g,
-		unsigned char b, unsigned char colourmix) {
+void setPersonColourise(int ob, unsigned char r, unsigned char g, unsigned char b, unsigned char colourmix) {
 	onScreenPerson *moveMe = findPerson(ob);
 	if (!moveMe)
 		return;
@@ -474,20 +466,16 @@ void drawPeople() {
 				thisPerson->frameNum = 0;
 				thisPerson->frameTick = myAnim->frames[0].howMany;
 				if (myAnim->frames[thisPerson->frameNum].noise > 0) {
-					startSound(myAnim->frames[thisPerson->frameNum].noise,
-							false);
+					startSound(myAnim->frames[thisPerson->frameNum].noise, false);
 					thisPerson->frameNum++;
 					thisPerson->frameNum %= thisPerson->myAnim->numFrames;
-					thisPerson->frameTick =
-							thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
+					thisPerson->frameTick = thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
 				} else if (myAnim->frames[thisPerson->frameNum].noise) {
-					startNewFunctionNum(
-							-myAnim->frames[thisPerson->frameNum].noise, 0,
-							NULL, noStack);
+					startNewFunctionNum(-myAnim->frames[thisPerson->frameNum].noise, 0,
+					NULL, noStack);
 					thisPerson->frameNum++;
 					thisPerson->frameNum %= thisPerson->myAnim->numFrames;
-					thisPerson->frameTick =
-							thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
+					thisPerson->frameTick = thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
 				}
 			}
 			int fNumSign = myAnim->frames[thisPerson->frameNum].frameNum;
@@ -499,8 +487,7 @@ void drawPeople() {
 			}
 			if (m != 2) {
 				bool r = false;
-				r = scaleSprite(myAnim->theSprites->bank.sprites[fNum],
-						myAnim->theSprites->bank.myPalette, thisPerson, m);
+				r = scaleSprite(myAnim->theSprites->bank.sprites[fNum], myAnim->theSprites->bank.myPalette, thisPerson, m);
 				if (r) {
 					if (thisPerson->thisType->screenName[0]) {
 						if (personRegion.thisType != thisPerson->thisType)
@@ -514,24 +501,19 @@ void drawPeople() {
 		if (!--thisPerson->frameTick) {
 			thisPerson->frameNum++;
 			thisPerson->frameNum %= thisPerson->myAnim->numFrames;
-			thisPerson->frameTick =
-					thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
+			thisPerson->frameTick = thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
 			if (thisPerson->show && myAnim && myAnim->frames) {
 				if (myAnim->frames[thisPerson->frameNum].noise > 0) {
-					startSound(myAnim->frames[thisPerson->frameNum].noise,
-							false);
+					startSound(myAnim->frames[thisPerson->frameNum].noise, false);
 					thisPerson->frameNum++;
 					thisPerson->frameNum %= thisPerson->myAnim->numFrames;
-					thisPerson->frameTick =
-							thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
+					thisPerson->frameTick = thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
 				} else if (myAnim->frames[thisPerson->frameNum].noise) {
-					startNewFunctionNum(
-							-myAnim->frames[thisPerson->frameNum].noise, 0,
-							NULL, noStack);
+					startNewFunctionNum(-myAnim->frames[thisPerson->frameNum].noise, 0,
+					NULL, noStack);
 					thisPerson->frameNum++;
 					thisPerson->frameNum %= thisPerson->myAnim->numFrames;
-					thisPerson->frameTick =
-							thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
+					thisPerson->frameTick = thisPerson->myAnim->frames[thisPerson->frameNum].howMany;
 				}
 			}
 		}
@@ -548,9 +530,7 @@ void makeSilent(onScreenPerson &me) {
 }
 
 bool handleClosestPoint(int &setX, int &setY, int &setPoly) {
-	int gotX = 320, gotY = 200, gotPoly = -1, i, j, xTest1, yTest1, xTest2,
-			yTest2, closestX, closestY, oldJ, currentDistance = 0xFFFFF,
-			thisDistance;
+	int gotX = 320, gotY = 200, gotPoly = -1, i, j, xTest1, yTest1, xTest2, yTest2, closestX, closestY, oldJ, currentDistance = 0xFFFFF, thisDistance;
 
 //	FILE * dbug = fopen ("debug_closest.txt", "at");
 //	fprintf (dbug, "\nGetting closest point to %i, %i\n", setX, setY);
@@ -559,16 +539,11 @@ bool handleClosestPoint(int &setX, int &setY, int &setPoly) {
 		oldJ = currentFloor->polygon[i].numVertices - 1;
 		for (j = 0; j < currentFloor->polygon[i].numVertices; j++) {
 //			fprintf (dbug, "Polygon %i, line %i... ", i, j);
-			xTest1 =
-					currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].x;
-			yTest1 =
-					currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].y;
-			xTest2 =
-					currentFloor->vertex[currentFloor->polygon[i].vertexID[oldJ]].x;
-			yTest2 =
-					currentFloor->vertex[currentFloor->polygon[i].vertexID[oldJ]].y;
-			closestPointOnLine(closestX, closestY, xTest1, yTest1, xTest2,
-					yTest2, setX, setY);
+			xTest1 = currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].x;
+			yTest1 = currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].y;
+			xTest2 = currentFloor->vertex[currentFloor->polygon[i].vertexID[oldJ]].x;
+			yTest2 = currentFloor->vertex[currentFloor->polygon[i].vertexID[oldJ]].y;
+			closestPointOnLine(closestX, closestY, xTest1, yTest1, xTest2, yTest2, setX, setY);
 //			fprintf (dbug, "closest point is %i, %i... ", closestX, closestY);
 			xTest1 = setX - closestX;
 			yTest1 = setY - closestY;
@@ -610,8 +585,7 @@ bool doBorderStuff(onScreenPerson *moveMe) {
 
 		// Grab the index of the second matching corner...
 		int ID, ID2;
-		if (!getMatchingCorners(currentFloor->polygon[moveMe->inPoly],
-				currentFloor->polygon[newPoly], ID, ID2))
+		if (!getMatchingCorners(currentFloor->polygon[moveMe->inPoly], currentFloor->polygon[newPoly], ID, ID2))
 			return fatal("Not a valid floor plan!");
 
 		// Remember that we're walking to the new polygon...
@@ -647,8 +621,7 @@ bool doBorderStuff(onScreenPerson *moveMe) {
 			dy23 *= dy23;
 			dy24 *= dy24;
 
-			if (sqrt((double) dx13 + dy13) + sqrt((double) dx23 + dy23)
-					< sqrt((double) dx14 + dy14) + sqrt((double) dx24 + dy24)) {
+			if (sqrt((double)dx13 + dy13) + sqrt((double)dx23 + dy23) < sqrt((double)dx14 + dy14) + sqrt((double)dx24 + dy24)) {
 				moveMe->thisStepX = x3;
 				moveMe->thisStepY = y3;
 			} else {
@@ -679,9 +652,7 @@ bool walkMe(onScreenPerson *thisPerson, bool move = true) {
 		if (s < 0.2)
 			s = 0.2;
 
-		maxDiff =
-				(TF_abs(xDiff) >= TF_abs(yDiff)) ?
-						TF_abs(xDiff) : TF_abs(yDiff);
+		maxDiff = (TF_abs(xDiff) >= TF_abs(yDiff)) ? TF_abs(xDiff) : TF_abs(yDiff);
 
 		if (TF_abs(maxDiff) > s) {
 			if (thisPerson->spinning) {
@@ -690,8 +661,7 @@ bool walkMe(onScreenPerson *thisPerson, bool move = true) {
 			}
 			s = maxDiff / s;
 			if (move)
-				moveAndScale(*thisPerson, thisPerson->x + xDiff / s,
-						thisPerson->y + yDiff / (s * 2));
+				moveAndScale(*thisPerson, thisPerson->x + xDiff / s, thisPerson->y + yDiff / (s * 2));
 			return true;
 		}
 
@@ -732,8 +702,7 @@ bool makeWalkingPerson(int x, int y, int objNum, loadedFunction *func, int di) {
 	moveMe->walkToY = y;
 	moveMe->walkToPoly = inFloor(x, y);
 	if (moveMe->walkToPoly == -1) {
-		if (!handleClosestPoint(moveMe->walkToX, moveMe->walkToY,
-				moveMe->walkToPoly))
+		if (!handleClosestPoint(moveMe->walkToX, moveMe->walkToY, moveMe->walkToPoly))
 			return false;
 	}
 
@@ -767,8 +736,7 @@ bool stopPerson(int o) {
 	return false;
 }
 
-bool forceWalkingPerson(int x, int y, int objNum, loadedFunction *func,
-		int di) {
+bool forceWalkingPerson(int x, int y, int objNum, loadedFunction *func, int di) {
 	if (x == 0 && y == 0)
 		return false;
 	onScreenPerson *moveMe = findPerson(objNum);
@@ -840,8 +808,7 @@ void walkAllPeople() {
 			spinStep(thisPerson);
 			setFrames(*thisPerson, ANI_STAND);
 		}
-		if ((!thisPerson->walking) && (!thisPerson->spinning)
-				&& thisPerson->continueAfterWalking) {
+		if ((!thisPerson->walking) && (!thisPerson->spinning) && thisPerson->continueAfterWalking) {
 			restartFunction(thisPerson->continueAfterWalking);
 			thisPerson->continueAfterWalking = NULL;
 		}
@@ -890,12 +857,10 @@ bool addPerson(int x, int y, int objNum, persona *p) {
 		if (fNumSigned < 0) {
 			newPerson->height = 5;
 		} else {
-			newPerson->height =
-					p->animation[0]->theSprites->bank.sprites[0].yhot + 5;
+			newPerson->height = p->animation[0]->theSprites->bank.sprites[0].yhot + 5;
 		}
 	} else {
-		newPerson->height = p->animation[0]->theSprites->bank.sprites[fNum].yhot
-				+ 5;
+		newPerson->height = p->animation[0]->theSprites->bank.sprites[fNum].yhot + 5;
 	}
 
 	// NOW ADD IT IN THE RIGHT PLACE
@@ -907,7 +872,7 @@ bool addPerson(int x, int y, int objNum, persona *p) {
 	newPerson->next = (*changethat);
 	(*changethat) = newPerson;
 
-	return (bool) (newPerson->thisType != NULL);
+	return (bool)(newPerson->thisType != NULL);
 }
 
 int timeForAnim(personaAnimation *fram) {
@@ -987,8 +952,7 @@ void removeOneCharacter(int i) {
 	onScreenPerson *p = findPerson(i);
 
 	if (p) {
-		if (overRegion == &personRegion
-				&& overRegion->thisType == p->thisType) {
+		if (overRegion == &personRegion && overRegion->thisType == p->thisType) {
 			overRegion = NULL;
 		}
 
@@ -997,8 +961,7 @@ void removeOneCharacter(int i) {
 		p->continueAfterWalking = NULL;
 		onScreenPerson * * killPeople;
 
-		for (killPeople = &allPeople; *killPeople != p; killPeople =
-				&((*killPeople)->next)) {
+		for (killPeople = &allPeople; *killPeople != p; killPeople = &((*killPeople)->next)) {
 			;
 		}
 
diff --git a/engines/sludge/people.h b/engines/sludge/people.h
index f6d8784..442cb92 100644
--- a/engines/sludge/people.h
+++ b/engines/sludge/people.h
@@ -69,43 +69,34 @@ struct onScreenPerson {
 };
 
 // Initialisation and creation
-
 bool initPeople();
 bool addPerson(int x, int y, int objNum, persona *p);
 
 // Draw to screen and to backdrop
-
 void drawPeople();
 void freezePeople(int, int);
 
 // Removalisationisms
-
 void killAllPeople();
 void killMostPeople();
 void removeOneCharacter(int i);
 
 // Things which affect or use all characters
-
 onScreenPerson *findPerson(int v);
 void setScale(short int h, short int d);
 
 // Things which affect one character
-
 void makeTalker(onScreenPerson &me);
 void makeSilent(onScreenPerson &me);
 void setShown(bool h, int ob);
 void setDrawMode(int h, int ob);
 void setPersonTransparency(int ob, unsigned char x);
-void setPersonColourise(int ob, unsigned char r, unsigned char g,
-		unsigned char b, unsigned char colourmix);
+void setPersonColourise(int ob, unsigned char r, unsigned char g, unsigned char b, unsigned char colourmix);
 
 // Moving 'em
-
 void movePerson(int x, int y, int objNum);
-bool makeWalkingPerson(int x, int y, int objNum, struct loadedFunction *func,
-		int di);
-bool forceWalkingPerson(int x, int y, int objNum, struct loadedFunction *func,
-		int di);
+bool makeWalkingPerson(int x, int y, int objNum, struct loadedFunction *func, int di);
+bool forceWalkingPerson(int x, int y, int objNum, struct loadedFunction *func, int di);
 void jumpPerson(int x, int y, int objNum);
 void walkAllPeople();
 bool turnPersonToFace(int thisNum, int direc);
@@ -114,7 +105,6 @@ bool floatCharacter(int f, int objNum);
 bool setCharacterWalkSpeed(int f, int objNum);
 
 // Animating 'em
-
 void animatePerson(int obj, personaAnimation *);
 void animatePerson(int obj, persona *per);
 personaAnimation *createPersonaAnim(int num, struct variableStack *&stacky);
diff --git a/engines/sludge/region.cpp b/engines/sludge/region.cpp
index efc6908..9c565a3 100644
--- a/engines/sludge/region.cpp
+++ b/engines/sludge/region.cpp
@@ -47,7 +47,7 @@ void showBoxes() {
 }
 
 void removeScreenRegion(int objectNum) {
-	screenRegion * * huntRegion = &allScreenRegions;
+	screenRegion ** huntRegion = &allScreenRegions;
 	screenRegion *killMe;
 
 	while (*huntRegion) {
diff --git a/engines/sludge/savedata.cpp b/engines/sludge/savedata.cpp
index e387b92..bb13152 100644
--- a/engines/sludge/savedata.cpp
+++ b/engines/sludge/savedata.cpp
@@ -77,7 +77,7 @@ char *readStringEncoded(Common::File *fp) {
 	if (!checkNew(s))
 		return NULL;
 	for (a = 0; a < len; a++) {
-		s[a] = (char) (fp->readByte() ^ encode1);
+		s[a] = (char)(fp->readByte() ^ encode1);
 		encode1 += encode2;
 	}
 	s[len] = 0;
@@ -95,7 +95,7 @@ char *readTextPlain(Common::File *fp) {
 	startPos = fp->pos();
 
 	while (keepGoing) {
-		gotChar = (char) fp->readByte();
+		gotChar = (char)fp->readByte();
 		if ((gotChar == '\n') || (fp->eos())) {
 			keepGoing = false;
 		} else {
@@ -125,9 +125,7 @@ bool fileToStack(char *filename, stackHandler *sH) {
 
 	variable stringVar;
 	stringVar.varType = SVT_NULL;
-	const char *checker =
-			saveEncoding ?
-					"[Custom data (encoded)]\r\n" : "[Custom data (ASCII)]\n";
+	const char *checker = saveEncoding ? "[Custom data (encoded)]\r\n" : "[Custom data (ASCII)]\n";
 
 	Common::File fd;
 
@@ -153,14 +151,13 @@ bool fileToStack(char *filename, stackHandler *sH) {
 		return fatal("No such file", filename); //TODO: false value
 	}
 
-	encode1 = (unsigned char) saveEncoding & 255;
-	encode2 = (unsigned char) (saveEncoding >> 8);
+	encode1 = (unsigned char)saveEncoding & 255;
+	encode2 = (unsigned char)(saveEncoding >> 8);
 
 	while (*checker) {
 		if (fd.readByte() != *checker) {
 			fd.close();
-			return fatal(LOAD_ERROR "This isn't a SLUDGE custom data file:",
-					filename);
+			return fatal(LOAD_ERROR "This isn't a SLUDGE custom data file:", filename);
 		}
 		checker++;
 	}
@@ -170,8 +167,7 @@ bool fileToStack(char *filename, stackHandler *sH) {
 		if (strcmp(checker, "UN�LO�CKED")) {
 			fd.close();
 			return fatal(
-					LOAD_ERROR "The current file encoding setting does not match the encoding setting used when this file was created:",
-					filename);
+			LOAD_ERROR "The current file encoding setting does not match the encoding setting used when this file was created:", filename);
 		}
 		delete checker;
 		checker = NULL;
@@ -184,25 +180,25 @@ bool fileToStack(char *filename, stackHandler *sH) {
 			if (fd.eos())
 				break;
 			switch (i) {
-			case 0: {
-				char *g = readStringEncoded(&fd);
-				makeTextVar(stringVar, g);
-				delete g;
-			}
-				break;
+				case 0: {
+					char *g = readStringEncoded(&fd);
+					makeTextVar(stringVar, g);
+					delete g;
+				}
+					break;
 
-			case 1:
-				setVariable(stringVar, SVT_INT, fd.readUint32LE());
-				break;
+				case 1:
+					setVariable(stringVar, SVT_INT, fd.readUint32LE());
+					break;
 
-			case 2:
-				setVariable(stringVar, SVT_INT, fd.readByte());
-				break;
+				case 2:
+					setVariable(stringVar, SVT_INT, fd.readByte());
+					break;
 
-			default:
-				fatal(LOAD_ERROR "Corrupt custom data file:", filename);
-				fd.close();
-				return false;
+				default:
+					fatal(LOAD_ERROR "Corrupt custom data file:", filename);
+					fd.close();
+					return false;
 			}
 		} else {
 			char *line = readTextPlain(&fd);
diff --git a/engines/sludge/sludge.cpp b/engines/sludge/sludge.cpp
index b679a09..85775f0 100644
--- a/engines/sludge/sludge.cpp
+++ b/engines/sludge/sludge.cpp
@@ -20,7 +20,7 @@
  *
  */
 #include "common/scummsys.h"
- 
+
 #include "common/config-manager.h"
 #include "common/debug.h"
 #include "common/debug-channels.h"
@@ -32,10 +32,10 @@
 #include "main_loop.h"
 
 namespace Sludge {
- 
-SludgeEngine::SludgeEngine(OSystem *syst, const SludgeGameDescription *gameDesc)
- : Engine(syst), _gameDescription(gameDesc), _console(nullptr) {
- 
+
+SludgeEngine::SludgeEngine(OSystem *syst, const SludgeGameDescription *gameDesc) :
+		Engine(syst), _gameDescription(gameDesc), _console(nullptr) {
+
 	// register your random source
 	_rnd = new Common::RandomSource("sludge");
 
@@ -49,19 +49,19 @@ SludgeEngine::SludgeEngine(OSystem *syst, const SludgeGameDescription *gameDesc)
 	// check init
 	debug("SludgeEngine::SludgeEngine");
 }
- 
+
 SludgeEngine::~SludgeEngine() {
 
 	// Dispose resources
 	delete _rnd;
- 
+
 	// Remove debug levels
 	DebugMan.clearAllDebugChannels();
-	
+
 	// Dispose console
 	delete _console;
 }
- 
+
 Common::Error SludgeEngine::run() {
 	// init graphics
 	Graphics::PixelFormat format = Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0);
@@ -69,12 +69,12 @@ Common::Error SludgeEngine::run() {
 
 	// create console
 	_console = new SludgeConsole(this);
- 
+
 	// debug log
 	main_loop("Welcome.slg");
- 
+
 	return Common::kNoError;
 }
- 
+
 } // End of namespace Sludge
 
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index 9f80228..a018d74 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -1672,8 +1672,7 @@ bool handleInput() {
 			delete tempString;
 			tempString = NULL;
 			tempStack->next = NULL;
-			if (!startNewFunctionNum(currentEvents->spaceFunction, 1, NULL,
-					tempStack))
+			if (!startNewFunctionNum(currentEvents->spaceFunction, 1, NULL, tempStack))
 				return false;
 		}
 	}
diff --git a/engines/sludge/sludger.h b/engines/sludge/sludger.h
index ef319db..f5030ef 100644
--- a/engines/sludge/sludger.h
+++ b/engines/sludge/sludger.h
@@ -82,8 +82,7 @@ extern int iconW, iconH;
 
 bool initSludge(char *);
 void sludgeDisplay();
-int startNewFunctionNum(unsigned int, unsigned int, loadedFunction *,
-		variableStack*&, bool = true);
+int startNewFunctionNum(unsigned int, unsigned int, loadedFunction *, variableStack*&, bool = true);
 bool handleInput();
 void restartFunction(loadedFunction *fun);
 bool loadFunctionCode(loadedFunction *newFunc);
@@ -92,8 +91,7 @@ void saveHandlers(Common::WriteStream *stream);
 
 void finishFunction(loadedFunction *fun);
 void abortFunction(loadedFunction *fun);
-Common::File *openAndVerify(char *filename, char extra1, char extra2,
-		const char *er, int &fileVersion);
+Common::File *openAndVerify(char *filename, char extra1, char extra2, const char *er, int &fileVersion);
 
 void freezeSubs();
 void unfreezeSubs();
diff --git a/engines/sludge/sound_bass.cpp b/engines/sludge/sound_bass.cpp
index c2fa56d..b285b96 100644
--- a/engines/sludge/sound_bass.cpp
+++ b/engines/sludge/sound_bass.cpp
@@ -49,8 +49,7 @@ soundThing soundCache[MAX_SAMPLES];
 int defVol = 128;
 int defSoundVol = 255;
 
-char *loadEntireFileToMemory(Common::SeekableReadStream *inputFile,
-		uint32_t size) {
+char *loadEntireFileToMemory(Common::SeekableReadStream *inputFile, uint32_t size) {
 	char *allData = new char[size];
 	if (!allData)
 		return NULL;
@@ -147,11 +146,7 @@ bool playMOD(int f, int a, int fromTrack) {
 		if (!memImage)
 			return fatal(ERROR_MUSIC_MEMORY_LOW);
 
-		mod[a] =
-				BASS_MusicLoad(true, memImage, 0, length,
-						BASS_MUSIC_LOOP
-								| BASS_MUSIC_RAMP/*|BASS_MUSIC_PRESCAN needed too if we're going to set the position in bytes*/,
-						0);
+		mod[a] = BASS_MusicLoad(true, memImage, 0, length, BASS_MUSIC_LOOP | BASS_MUSIC_RAMP/*|BASS_MUSIC_PRESCAN needed too if we're going to set the position in bytes*/, 0);
 		delete memImage;
 
 		if (!mod[a]) {
@@ -162,10 +157,8 @@ bool playMOD(int f, int a, int fromTrack) {
 			if (!BASS_ChannelPlay(mod[a], true))
 				debugOut("playMOD: Error %d!\n", BASS_ErrorGetCode());
 
-			BASS_ChannelSetPosition(mod[a], MAKELONG(fromTrack, 0),
-					BASS_POS_MUSIC_ORDER);
-			BASS_ChannelFlags(mod[a], BASS_SAMPLE_LOOP | BASS_MUSIC_RAMP,
-					BASS_SAMPLE_LOOP | BASS_MUSIC_RAMP);
+			BASS_ChannelSetPosition(mod[a], MAKELONG(fromTrack, 0), BASS_POS_MUSIC_ORDER);
+			BASS_ChannelFlags(mod[a], BASS_SAMPLE_LOOP | BASS_MUSIC_RAMP, BASS_SAMPLE_LOOP | BASS_MUSIC_RAMP);
 		}
 		setResourceForFatal(-1);
 	}
@@ -175,8 +168,7 @@ bool playMOD(int f, int a, int fromTrack) {
 void setMusicVolume(int a, int v) {
 	int ret;
 	if (soundOK && mod[a]) {
-		ret = BASS_ChannelSetAttribute(mod[a], BASS_ATTRIB_VOL,
-				(float) v / 256);
+		ret = BASS_ChannelSetAttribute(mod[a], BASS_ATTRIB_VOL, (float)v / 256);
 		if (!ret) {
 			debugOut("setMusicVolume: Error %d\n", BASS_ErrorGetCode());
 		}
@@ -192,8 +184,7 @@ void setSoundVolume(int a, int v) {
 		int ch = findInSoundCache(a);
 		if (ch != -1) {
 			if (BASS_ChannelIsActive(soundCache[ch].mostRecentChannel)) {
-				BASS_ChannelSetAttribute(soundCache[ch].mostRecentChannel,
-						BASS_ATTRIB_VOL, (float) v / 256);
+				BASS_ChannelSetAttribute(soundCache[ch].mostRecentChannel, BASS_ATTRIB_VOL, (float)v / 256);
 			}
 		}
 	}
@@ -203,8 +194,7 @@ bool stillPlayingSound(int ch) {
 	if (soundOK)
 		if (ch != -1)
 			if (soundCache[ch].fileLoaded != -1)
-				if (BASS_ChannelIsActive(soundCache[ch].mostRecentChannel)
-						!= BASS_ACTIVE_STOPPED)
+				if (BASS_ChannelIsActive(soundCache[ch].mostRecentChannel) != BASS_ACTIVE_STOPPED)
 					return true;
 	return false;
 }
@@ -318,8 +308,7 @@ int cacheSound(int f) {
 
 	for (;;) {
 //		soundWarning ("  Trying to load sound into slot", a);
-		soundCache[a].sample = BASS_SampleLoad(true, memImage, 0, length, 65535,
-				0);
+		soundCache[a].sample = BASS_SampleLoad(true, memImage, 0, length, 65535, 0);
 
 		if (soundCache[a].sample) {
 			soundCache[a].fileLoaded = f;
@@ -345,15 +334,12 @@ bool startSound(int f, bool loopy) {
 		soundCache[a].looping = loopy;
 		soundCache[a].vol = defSoundVol;
 
-		soundCache[a].mostRecentChannel = BASS_SampleGetChannel(
-				soundCache[a].sample, false);
+		soundCache[a].mostRecentChannel = BASS_SampleGetChannel(soundCache[a].sample, false);
 		if (soundCache[a].mostRecentChannel) {
 			BASS_ChannelPlay(soundCache[a].mostRecentChannel, true);
-			BASS_ChannelSetAttribute(soundCache[a].mostRecentChannel,
-					BASS_ATTRIB_VOL, defSoundVol);
+			BASS_ChannelSetAttribute(soundCache[a].mostRecentChannel, BASS_ATTRIB_VOL, defSoundVol);
 			if (loopy) {
-				BASS_ChannelFlags(soundCache[a].mostRecentChannel,
-						BASS_SAMPLE_LOOP, BASS_SAMPLE_LOOP); // set LOOP flag
+				BASS_ChannelFlags(soundCache[a].mostRecentChannel, BASS_SAMPLE_LOOP, BASS_SAMPLE_LOOP); // set LOOP flag
 			}
 		}
 
diff --git a/engines/sludge/sprbanks.cpp b/engines/sludge/sprbanks.cpp
index 8598cb5..1ae7774 100644
--- a/engines/sludge/sprbanks.cpp
+++ b/engines/sludge/sprbanks.cpp
@@ -52,8 +52,7 @@ loadedSpriteBank *loadBankForAnim(int ID) {
 			debugOut("loadBankForAnim: New sprite bank created OK\n");
 			return returnMe;
 		} else {
-			debugOut(
-					"loadBankForAnim: I guess I couldn't load the sprites...\n");
+			debugOut("loadBankForAnim: I guess I couldn't load the sprites...\n");
 			return NULL;
 		}
 	} else
diff --git a/engines/sludge/sprites.h b/engines/sludge/sprites.h
index c09ae39..f3ec22d 100644
--- a/engines/sludge/sprites.h
+++ b/engines/sludge/sprites.h
@@ -67,19 +67,13 @@ bool loadSpriteBank(char *filename, spriteBank &loadhere);
 bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont);
 
 void fontSprite(int x1, int y1, sprite &single, const spritePalette &fontPal);
-void flipFontSprite(int x1, int y1, sprite &single,
-		const spritePalette &fontPal);
+void flipFontSprite(int x1, int y1, sprite &single, const spritePalette &fontPal);
 
-bool scaleSprite(sprite &single, const spritePalette &fontPal,
-		onScreenPerson *thisPerson, bool mirror);
-void pasteSpriteToBackDrop(int x1, int y1, sprite &single,
-		const spritePalette &fontPal);
+bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *thisPerson, bool mirror);
+void pasteSpriteToBackDrop(int x1, int y1, sprite &single, const spritePalette &fontPal);
 bool reserveSpritePal(spritePalette &sP, int n);
-void fixScaleSprite(int x1, int y1, sprite &single,
-		const spritePalette &fontPal, onScreenPerson *thisPerson,
-		const int camX, const int camY, bool);
-void burnSpriteToBackDrop(int x1, int y1, sprite &single,
-		const spritePalette &fontPal);
+void fixScaleSprite(int x1, int y1, sprite &single, const spritePalette &fontPal, onScreenPerson *thisPerson, const int camX, const int camY, bool);
+void burnSpriteToBackDrop(int x1, int y1, sprite &single, const spritePalette &fontPal);
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/statusba.cpp b/engines/sludge/statusba.cpp
index da9d655..52aeb5d 100644
--- a/engines/sludge/statusba.cpp
+++ b/engines/sludge/statusba.cpp
@@ -223,8 +223,8 @@ bool loadStatusBars(Common::SeekableReadStream *stream) {
 		if (! checkNew(newOne)) return false;
 		newOne->text = readString(stream);
 		newOne->next = NULL;
-		(* viewLine) = newOne;
-		viewLine = & (newOne->next);
+		(*viewLine) = newOne;
+		viewLine = &(newOne->next);
 	}
 	return true;
 }
diff --git a/engines/sludge/thumbnail.cpp b/engines/sludge/thumbnail.cpp
index 5e77936..63c7544 100644
--- a/engines/sludge/thumbnail.cpp
+++ b/engines/sludge/thumbnail.cpp
@@ -104,8 +104,8 @@ bool saveThumbnail(Common::WriteStream *stream) {
 		GLuint *tmp = new GLuint [thumbWidth * thumbHeight];
 		if (! checkNew(image)) return false;
 		glReadPixels(viewportOffsetX, viewportOffsetY, thumbWidth, thumbHeight, GL_RGBA, GL_UNSIGNED_BYTE, tmp);
-		for (int y = 0; y < thumbHeight; y ++) {
-			for (int x = 0; x < thumbWidth; x ++) {
+		for (int y = 0; y < thumbHeight; y++) {
+			for (int x = 0; x < thumbWidth; x++) {
 				const GLuint a = tmp[y * thumbWidth + x];
 				image[y * thumbWidth + x] = ((a & 0x00f80000) >> (16 + 3)) | ((a & 0x0000fc00) >> (8 + 2 - 5)) | ((a & 0x000000f8) << (11 - 3));
 			}
@@ -122,8 +122,8 @@ bool saveThumbnail(Common::WriteStream *stream) {
 #endif
 		setPixelCoords(false);
 
-		for (int y = 0; y < thumbHeight; y ++) {
-			for (int x = 0; x < thumbWidth; x ++) {
+		for (int y = 0; y < thumbHeight; y++) {
+			for (int x = 0; x < thumbWidth; x++) {
 				put2bytes((*(image + y * thumbWidth + x)), fp);
 			}
 		}
@@ -167,7 +167,7 @@ void showThumbnail(char *filename, int atX, int atY) {
 		int t1, t2;
 		unsigned short c;
 		GLubyte *target;
-		for (t2 = 0; t2 < fileHeight; t2 ++) {
+		for (t2 = 0; t2 < fileHeight; t2++) {
 			t1 = 0;
 			while (t1 < fileWidth) {
 				c = (unsigned short) fp->readUint16BE();
diff --git a/engines/sludge/transition.cpp b/engines/sludge/transition.cpp
index 73ac737..100cc9c 100644
--- a/engines/sludge/transition.cpp
+++ b/engines/sludge/transition.cpp
@@ -380,27 +380,27 @@ void transitionBlinds() {
 
 void fixBrightness() {
 	switch (fadeMode) {
-	case 0:
-		transitionFader();
-		break;
-	case 1:
-		resetRandW();
-		// Fall through!
-	case 2:
-		transitionDisolve();
-		break;
-	case 3:
-		transitionTV();
-		break;
-	case 4:
-		transitionBlinds();
-		break;
-	case 5:
-		transitionCrossFader();
-		break;
-	case 6:
-		transitionSnapshotBox();
-		break;
+		case 0:
+			transitionFader();
+			break;
+		case 1:
+			resetRandW();
+			// Fall through!
+		case 2:
+			transitionDisolve();
+			break;
+		case 3:
+			transitionTV();
+			break;
+		case 4:
+			transitionBlinds();
+			break;
+		case 5:
+			transitionCrossFader();
+			break;
+		case 6:
+			transitionSnapshotBox();
+			break;
 
 	}
 }
diff --git a/engines/sludge/variable.cpp b/engines/sludge/variable.cpp
index 8d6beb2..96473cc 100644
--- a/engines/sludge/variable.cpp
+++ b/engines/sludge/variable.cpp
@@ -49,36 +49,36 @@ extern char *outputDir;
 
 void unlinkVar(variable &thisVar) {
 	switch (thisVar.varType) {
-	case SVT_STRING:
-		delete[] thisVar.varData.theString;
-		thisVar.varData.theString = NULL;
-		break;
-
-	case SVT_STACK:
-		thisVar.varData.theStack->timesUsed--;
-		if (thisVar.varData.theStack->timesUsed <= 0) {
-			while (thisVar.varData.theStack->first)
-				trimStack(thisVar.varData.theStack->first);
-			delete thisVar.varData.theStack;
-			thisVar.varData.theStack = NULL;
-		}
-		break;
-
-	case SVT_FASTARRAY:
-		thisVar.varData.fastArray->timesUsed--;
-		if (thisVar.varData.theStack->timesUsed <= 0) {
-			delete thisVar.varData.fastArray->fastVariables;
-			delete[] thisVar.varData.fastArray;
-			thisVar.varData.fastArray = NULL;
-		}
-		break;
+		case SVT_STRING:
+			delete[] thisVar.varData.theString;
+			thisVar.varData.theString = NULL;
+			break;
+
+		case SVT_STACK:
+			thisVar.varData.theStack->timesUsed--;
+			if (thisVar.varData.theStack->timesUsed <= 0) {
+				while (thisVar.varData.theStack->first)
+					trimStack(thisVar.varData.theStack->first);
+				delete thisVar.varData.theStack;
+				thisVar.varData.theStack = NULL;
+			}
+			break;
+
+		case SVT_FASTARRAY:
+			thisVar.varData.fastArray->timesUsed--;
+			if (thisVar.varData.theStack->timesUsed <= 0) {
+				delete thisVar.varData.fastArray->fastVariables;
+				delete[] thisVar.varData.fastArray;
+				thisVar.varData.fastArray = NULL;
+			}
+			break;
 
-	case SVT_ANIM:
-		deleteAnim(thisVar.varData.animHandler);
-		break;
+		case SVT_ANIM:
+			deleteAnim(thisVar.varData.animHandler);
+			break;
 
-	default:
-		break;
+		default:
+			break;
 	}
 }
 
@@ -101,8 +101,7 @@ personaAnimation *getAnimationFromVar(variable &thisVar) {
 	if (thisVar.varType == SVT_INT && thisVar.varData.intValue == 0)
 		return makeNullAnim();
 
-	fatal("Expecting an animation variable; found variable of type",
-			typeName[thisVar.varType]);
+	fatal("Expecting an animation variable; found variable of type", typeName[thisVar.varType]);
 	return NULL;
 }
 
@@ -116,27 +115,26 @@ persona *getCostumeFromVar(variable &thisVar) {
 	persona *p = NULL;
 
 	switch (thisVar.varType) {
-	case SVT_ANIM:
-		p = new persona;
-		if (!checkNew(p))
-			return NULL;
-		p->numDirections = 1;
-		p->animation = new personaAnimation *[3];
-		if (!checkNew(p->animation))
-			return NULL;
+		case SVT_ANIM:
+			p = new persona;
+			if (!checkNew(p))
+				return NULL;
+			p->numDirections = 1;
+			p->animation = new personaAnimation *[3];
+			if (!checkNew(p->animation))
+				return NULL;
 
-		for (int iii = 0; iii < 3; iii++)
-			p->animation[iii] = copyAnim(thisVar.varData.animHandler);
+			for (int iii = 0; iii < 3; iii++)
+				p->animation[iii] = copyAnim(thisVar.varData.animHandler);
 
-		break;
+			break;
 
-	case SVT_COSTUME:
-		return thisVar.varData.costumeHandler;
-		break;
+		case SVT_COSTUME:
+			return thisVar.varData.costumeHandler;
+			break;
 
-	default:
-		fatal("Expecting an animation variable; found variable of type",
-				typeName[thisVar.varType]);
+		default:
+			fatal("Expecting an animation variable; found variable of type", typeName[thisVar.varType]);
 	}
 
 	return p;
@@ -297,29 +295,29 @@ int compareVars(const variable &var1, const variable &var2) {
 	int re = 0;
 	if (var1.varType == var2.varType) {
 		switch (var1.varType) {
-		case SVT_NULL:
-			re = 1;
-			break;
+			case SVT_NULL:
+				re = 1;
+				break;
 
-		case SVT_COSTUME:
-			re = (var1.varData.costumeHandler == var2.varData.costumeHandler);
-			break;
+			case SVT_COSTUME:
+				re = (var1.varData.costumeHandler == var2.varData.costumeHandler);
+				break;
 
-		case SVT_ANIM:
-			re = (var1.varData.animHandler == var2.varData.animHandler);
-			break;
+			case SVT_ANIM:
+				re = (var1.varData.animHandler == var2.varData.animHandler);
+				break;
 
-		case SVT_STRING:
+			case SVT_STRING:
 
-			re = (strcmp(var1.varData.theString, var2.varData.theString) == 0);
-			break;
+				re = (strcmp(var1.varData.theString, var2.varData.theString) == 0);
+				break;
 
-		case SVT_STACK:
-			re = (var1.varData.theStack == var2.varData.theStack);
-			break;
+			case SVT_STACK:
+				re = (var1.varData.theStack == var2.varData.theStack);
+				break;
 
-		default:
-			re = (var1.varData.intValue == var2.varData.intValue);
+			default:
+				re = (var1.varData.intValue == var2.varData.intValue);
 		}
 	}
 	return re;
@@ -338,93 +336,92 @@ void makeTextVar(variable &thisVar, const char *txt) {
 bool loadStringToVar(variable &thisVar, int value) {
 
 	makeTextVar(thisVar, getNumberedString(value));
-	return (bool) (thisVar.varData.theString != NULL);
+	return (bool)(thisVar.varData.theString != NULL);
 }
 
 char *getTextFromAnyVar(const variable &from) {
 	switch (from.varType) {
-	case SVT_STRING:
-		return copyString(from.varData.theString);
-
-	case SVT_FASTARRAY: {
-		char *builder = copyString("FAST:");
-		char *builder2;
-		char *grabText;
-
-		for (int i = 0; i < from.varData.fastArray->size; i++) {
-			builder2 = joinStrings(builder, " ");
-			if (!builder2)
-				return NULL;
-			delete builder;
-			grabText = getTextFromAnyVar(
-					from.varData.fastArray->fastVariables[i]);
-			builder = joinStrings(builder2, grabText);
-			if (!builder)
-				return NULL;
-			delete grabText;
-			grabText = NULL;
-			delete builder2;
-			builder2 = NULL;
+		case SVT_STRING:
+			return copyString(from.varData.theString);
+
+		case SVT_FASTARRAY: {
+			char *builder = copyString("FAST:");
+			char *builder2;
+			char *grabText;
+
+			for (int i = 0; i < from.varData.fastArray->size; i++) {
+				builder2 = joinStrings(builder, " ");
+				if (!builder2)
+					return NULL;
+				delete builder;
+				grabText = getTextFromAnyVar(from.varData.fastArray->fastVariables[i]);
+				builder = joinStrings(builder2, grabText);
+				if (!builder)
+					return NULL;
+				delete grabText;
+				grabText = NULL;
+				delete builder2;
+				builder2 = NULL;
+			}
+			return builder;
 		}
-		return builder;
-	}
 
-	case SVT_STACK: {
-		char *builder = copyString("ARRAY:");
-		char *builder2;
-		char *grabText;
-
-		variableStack *stacky = from.varData.theStack->first;
+		case SVT_STACK: {
+			char *builder = copyString("ARRAY:");
+			char *builder2;
+			char *grabText;
+
+			variableStack *stacky = from.varData.theStack->first;
+
+			while (stacky) {
+				builder2 = joinStrings(builder, " ");
+				if (!builder2)
+					return NULL;
+				delete builder;
+				grabText = getTextFromAnyVar(stacky->thisVar);
+				builder = joinStrings(builder2, grabText);
+				if (!builder)
+					return NULL;
+				delete grabText;
+				grabText = NULL;
+				delete builder2;
+				builder2 = NULL;
+				stacky = stacky->next;
+			}
+			return builder;
+		}
 
-		while (stacky) {
-			builder2 = joinStrings(builder, " ");
-			if (!builder2)
+		case SVT_INT: {
+			char *buff = new char[10];
+			if (!checkNew(buff))
 				return NULL;
-			delete builder;
-			grabText = getTextFromAnyVar(stacky->thisVar);
-			builder = joinStrings(builder2, grabText);
-			if (!builder)
-				return NULL;
-			delete grabText;
-			grabText = NULL;
-			delete builder2;
-			builder2 = NULL;
-			stacky = stacky->next;
+			sprintf(buff, "%i", from.varData.intValue);
+			return buff;
 		}
-		return builder;
-	}
-
-	case SVT_INT: {
-		char *buff = new char[10];
-		if (!checkNew(buff))
-			return NULL;
-		sprintf(buff, "%i", from.varData.intValue);
-		return buff;
-	}
 
-	case SVT_FILE: {
+		case SVT_FILE: {
 //			char * buff = new char[15];
 //			if (! checkNew (buff)) return NULL;
 //			sprintf (buff, "FILE %i", from.varData.intValue);
-		return joinStrings("", resourceNameFromNum(from.varData.intValue));
-	}
+			return joinStrings("", resourceNameFromNum(from.varData.intValue));
+		}
 
-		/*      case SVT_ANIM:
-		 {
-		 char * buff = new char[20];
-		 if (! checkNew (buff)) return NULL;
-		 sprintf (buff, "%p", from.varData.animHandler);
-		 return buff;
-		 }*/
-
-	case SVT_OBJTYPE: {
-		objectType *thisType = findObjectType(from.varData.intValue);
-		if (thisType)
-			return copyString(thisType->screenName);
-	}
+			/*      case SVT_ANIM:
+			 {
+			 char * buff = new char[20];
+			 if (! checkNew (buff)) return NULL;
+			 sprintf (buff, "%p", from.varData.animHandler);
+			 return buff;
+			 }*/
+
+		case SVT_OBJTYPE: {
+			objectType *thisType = findObjectType(from.varData.intValue);
+			if (thisType)
+				return copyString(thisType->screenName);
+		}
 
-	default:
-		break;
+		default:
+			break;
 	}
 
 	return copyString(typeName[from.varType]);
@@ -432,23 +429,23 @@ char *getTextFromAnyVar(const variable &from) {
 
 bool getBoolean(const variable &from) {
 	switch (from.varType) {
-	case SVT_NULL:
-		return false;
+		case SVT_NULL:
+			return false;
 
-	case SVT_INT:
-		return (bool) (from.varData.intValue != 0);
+		case SVT_INT:
+			return (bool)(from.varData.intValue != 0);
 
-	case SVT_STACK:
-		return (bool) (from.varData.theStack->first != NULL);
+		case SVT_STACK:
+			return (bool)(from.varData.theStack->first != NULL);
 
-	case SVT_STRING:
-		return (bool) (from.varData.theString[0] != 0);
+		case SVT_STRING:
+			return (bool)(from.varData.theString[0] != 0);
 
-	case SVT_FASTARRAY:
-		return (bool) (from.varData.fastArray->size != 0);
+		case SVT_FASTARRAY:
+			return (bool)(from.varData.fastArray->size != 0);
 
-	default:
-		break;
+		default:
+			break;
 	}
 	return true;
 }
@@ -456,41 +453,41 @@ bool getBoolean(const variable &from) {
 bool copyMain(const variable &from, variable &to) {
 	to.varType = from.varType;
 	switch (to.varType) {
-	case SVT_INT:
-	case SVT_FUNC:
-	case SVT_BUILT:
-	case SVT_FILE:
-	case SVT_OBJTYPE:
-		to.varData.intValue = from.varData.intValue;
-		return true;
-
-	case SVT_FASTARRAY:
-		to.varData.fastArray = from.varData.fastArray;
-		to.varData.fastArray->timesUsed++;
-		return true;
-
-	case SVT_STRING:
-		to.varData.theString = copyString(from.varData.theString);
-		return to.varData.theString ? true : false;
-
-	case SVT_STACK:
-		to.varData.theStack = from.varData.theStack;
-		to.varData.theStack->timesUsed++;
-		return true;
-
-	case SVT_COSTUME:
-		to.varData.costumeHandler = from.varData.costumeHandler;
-		return true;
-
-	case SVT_ANIM:
-		to.varData.animHandler = copyAnim(from.varData.animHandler);
-		return true;
-
-	case SVT_NULL:
-		return true;
-
-	default:
-		break;
+		case SVT_INT:
+		case SVT_FUNC:
+		case SVT_BUILT:
+		case SVT_FILE:
+		case SVT_OBJTYPE:
+			to.varData.intValue = from.varData.intValue;
+			return true;
+
+		case SVT_FASTARRAY:
+			to.varData.fastArray = from.varData.fastArray;
+			to.varData.fastArray->timesUsed++;
+			return true;
+
+		case SVT_STRING:
+			to.varData.theString = copyString(from.varData.theString);
+			return to.varData.theString ? true : false;
+
+		case SVT_STACK:
+			to.varData.theStack = from.varData.theStack;
+			to.varData.theStack->timesUsed++;
+			return true;
+
+		case SVT_COSTUME:
+			to.varData.costumeHandler = from.varData.costumeHandler;
+			return true;
+
+		case SVT_ANIM:
+			to.varData.animHandler = copyAnim(from.varData.animHandler);
+			return true;
+
+		case SVT_NULL:
+			return true;
+
+		default:
+			break;
 	}
 	fatal("Unknown value type");
 	return false;
@@ -509,8 +506,7 @@ variable *fastArrayGetByIndex(fastArrayHandler *vS, unsigned int theIndex) {
 
 bool makeFastArraySize(variable &to, int size) {
 	if (size < 0)
-		return fatal(
-				"Can't create a fast array with a negative number of elements!");
+		return fatal("Can't create a fast array with a negative number of elements!");
 	unlinkVar(to);
 	to.varType = SVT_FASTARRAY;
 	to.varData.fastArray = new fastArrayHandler;
@@ -561,8 +557,7 @@ bool addVarToStack(const variable &va, variableStack *&thisStack) {
 		return false;
 	newStack->next = thisStack;
 	thisStack = newStack;
-	debug(kSludgeDebugStackMachine, "Variable %s was added to stack",
-			getTextFromAnyVar(va));
+	debug(kSludgeDebugStackMachine, "Variable %s was added to stack", getTextFromAnyVar(va));
 	return true;
 }
 
@@ -578,13 +573,11 @@ bool addVarToStackQuick(variable &va, variableStack *&thisStack) {
 
 	newStack->next = thisStack;
 	thisStack = newStack;
-	debug(kSludgeDebugStackMachine, "Variable %s was added to stack quick",
-			getTextFromAnyVar(va));
+	debug(kSludgeDebugStackMachine, "Variable %s was added to stack quick", getTextFromAnyVar(va));
 	return true;
 }
 
-bool stackSetByIndex(variableStack *vS, unsigned int theIndex,
-		const variable &va) {
+bool stackSetByIndex(variableStack *vS, unsigned int theIndex, const variable &va) {
 	while (theIndex--) {
 		vS = vS->next;
 		if (!vS)
@@ -603,8 +596,7 @@ variable *stackGetByIndex(variableStack *vS, unsigned int theIndex) {
 	return &(vS->thisVar);
 }
 
-int deleteVarFromStack(const variable &va, variableStack *&thisStack,
-		bool allOfEm) {
+int deleteVarFromStack(const variable &va, variableStack *&thisStack, bool allOfEm) {
 	variableStack * * huntVar = &thisStack;
 	variableStack *killMe;
 	int reply = 0;
@@ -640,12 +632,8 @@ variableStack *stackFindLast(variableStack *hunt) {
 bool getValueType(int &toHere, variableType vT, const variable &v) {
 	//if (! v) return false;
 	if (v.varType != vT) {
-		char *e1 =
-				joinStrings(
-						"Can only perform specified operation on a value which is of type ",
-						typeName[vT]);
-		char *e2 = joinStrings("... value supplied was of type ",
-				typeName[v.varType]);
+		char *e1 = joinStrings("Can only perform specified operation on a value which is of type ", typeName[vT]);
+		char *e2 = joinStrings("... value supplied was of type ", typeName[v.varType]);
 		fatal(e1, e2);
 
 		return false;
@@ -658,8 +646,7 @@ void trimStack(variableStack *&stack) {
 	variableStack *killMe = stack;
 	stack = stack->next;
 
-	debug(kSludgeDebugStackMachine, "Variable %s was removed from stack",
-			getTextFromAnyVar(killMe->thisVar));
+	debug(kSludgeDebugStackMachine, "Variable %s was removed from stack", getTextFromAnyVar(killMe->thisVar));
 
 	// When calling this, we've ALWAYS checked that stack != NULL
 	unlinkVar(killMe->thisVar);
diff --git a/engines/sludge/vid.cpp b/engines/sludge/vid.cpp
index 00e2063..0aab819 100644
--- a/engines/sludge/vid.cpp
+++ b/engines/sludge/vid.cpp
@@ -74,8 +74,7 @@ bool getStream(DWORD type, timStream &intoHere) {
 	if (AVIFileGetStream(pAviFile, &intoHere.got, type, 0)) {
 		intoHere.got = NULL;
 		return true;
-	} else if (AVIStreamInfo(intoHere.got, &intoHere.info,
-			sizeof(AVISTREAMINFO))) {
+	} else if (AVIStreamInfo(intoHere.got, &intoHere.info, sizeof(AVISTREAMINFO))) {
 		return fatal("Can't get stream info");
 	} else if (AVIStreamReadFormat(intoHere.got, AVIStreamStart(intoHere.got),
 	NULL, &intoHere.chunkSize)) {
@@ -87,9 +86,7 @@ bool getStream(DWORD type, timStream &intoHere) {
 
 		if (!intoHere.chunk) {
 			return fatal("Out of memory");
-		} else if (AVIStreamReadFormat(intoHere.got,
-				AVIStreamStart(intoHere.got), intoHere.chunk,
-				&intoHere.chunkSize)) {
+		} else if (AVIStreamReadFormat(intoHere.got, AVIStreamStart(intoHere.got), intoHere.chunk, &intoHere.chunkSize)) {
 			return fatal("Couldn't read stream format");
 		}
 	}
@@ -231,14 +228,13 @@ return true;
 }
 
 bool nextVideoFrame() {
-LPBITMAPINFOHEADER lpbi = (LPBITMAPINFOHEADER) AVIStreamGetFrame(pgf,
-		videoFrameNum);
+LPBITMAPINFOHEADER lpbi = (LPBITMAPINFOHEADER)AVIStreamGetFrame(pgf, videoFrameNum);
 if (!lpbi) {
 	finishVideo();
 	return false;
 }
 
-BYTE *pData = (((BYTE *) lpbi) + lpbi->biSize);
+BYTE *pData = (((BYTE *)lpbi) + lpbi->biSize);
 
 int xOff = (winWidth - vidWidth) >> 1;
 int yOff = (winHeight + vidHeight) >> 1;
@@ -249,22 +245,20 @@ for (int y = 0; y < vidHeight; y++) {
 	unsigned short int *toHere = startingPoint;
 	for (int x = 0; x < vidWidth; x++) {
 		switch (vidBytesPerPixel) {
-		case 1:
-			(*toHere) = makeGrey(*pData);
-			break;
-
-		case 3:
-		case 4:
-			(*toHere) = makeColour(*(pData + 2), *(pData + 1), *pData);
-			break;
-
-		default: {
-			WORD Pixel16 = *((WORD *) pData);
-			(*toHere) = makeColour((((UINT)(Pixel16) >> 10) & 0x1F) << 3,
-					(((UINT)(Pixel16) >> 5) & 0x1F) << 3,
-					(((UINT)(Pixel16) >> 0) & 0x1F) << 3);
-		}
-			break;
+			case 1:
+				(*toHere) = makeGrey(*pData);
+				break;
+
+			case 3:
+			case 4:
+				(*toHere) = makeColour(*(pData + 2), *(pData + 1), *pData);
+				break;
+
+			default: {
+				WORD Pixel16 = *((WORD *)pData);
+				(*toHere) = makeColour((((UINT)(Pixel16) >> 10) & 0x1F) << 3, (((UINT)(Pixel16) >> 5) & 0x1F) << 3, (((UINT)(Pixel16) >> 0) & 0x1F) << 3);
+			}
+				break;
 		}
 		pData += vidBytesPerPixel;
 		toHere++;
diff --git a/engines/sludge/zbuffer.cpp b/engines/sludge/zbuffer.cpp
index d81fde6..865a62e 100644
--- a/engines/sludge/zbuffer.cpp
+++ b/engines/sludge/zbuffer.cpp
@@ -75,133 +75,140 @@ bool setZBuffer(int y) {
 	setResourceForFatal(y);
 
 	zBuffer.originalNum = y;
-	if (! openFileFromNum(y)) return false;
-	if (fgetc(bigDataFile) != 'S') return fatal("Not a Z-buffer file");
-	if (fgetc(bigDataFile) != 'z') return fatal("Not a Z-buffer file");
-	if (fgetc(bigDataFile) != 'b') return fatal("Not a Z-buffer file");
-
-	switch (fgetc(bigDataFile)) {
-		case 0:
-		zBuffer.width = 640;
-		zBuffer.height = 480;
-		break;
-
-		case 1:
-		zBuffer.width = bigDataFile->readUint16BE();
-		zBuffer.height = bigDataFile->readUint16BE();
-		break;
-
-		default:
-		return fatal("Extended Z-buffer format not supported in this version of the SLUDGE engine");
-	}
-	if (zBuffer.width != sceneWidth || zBuffer.height != sceneHeight) {
-		char tmp[256];
-		sprintf(tmp, "Z-w: %d Z-h:%d w: %d, h:%d", zBuffer.width, zBuffer.height, sceneWidth, sceneHeight);
-		return fatal("Z-buffer width and height don't match scene width and height", tmp);
-	}
+	if (!openFileFromNum(y))
+		return false;
+	if (bigDataFile->readByte() != 'S')
+		return fatal("Not a Z-buffer file");
+	if (bigDataFile->readByte() != 'z')
+		return fatal("Not a Z-buffer file");
+	if (bigDataFile->readByte() != 'b')
+		return fatal("Not a Z-buffer file");
+
+	switch (bigDataFile->readByte()) {
+			case 0:
+				zBuffer.width = 640;
+				zBuffer.height = 480;
+				break;
+
+			case 1:
+				zBuffer.width = bigDataFile->readUint16BE();
+				zBuffer.height = bigDataFile->readUint16BE();
+				break;
+
+			default:
+				return fatal("Extended Z-buffer format not supported in this version of the SLUDGE engine");
+		}
+		if (zBuffer.width != sceneWidth || zBuffer.height != sceneHeight) {
+			char tmp[256];
+			sprintf(tmp, "Z-w: %d Z-h:%d w: %d, h:%d", zBuffer.width, zBuffer.height, sceneWidth, sceneHeight);
+			return fatal("Z-buffer width and height don't match scene width and height", tmp);
+		}
 
-	zBuffer.numPanels = fgetc(bigDataFile);
-	for (y = 0; y < zBuffer.numPanels; y ++) {
-		yPalette[y] = bigDataFile->readUint16BE();
-	}
-	sortZPal(yPalette, sorted, zBuffer.numPanels);
-	for (y = 0; y < zBuffer.numPanels; y ++) {
-		zBuffer.panel[y] = yPalette[sorted[y]];
-		sortback[sorted[y]] = y;
-	}
+		zBuffer.numPanels = bigDataFile->readByte();
+		for (y = 0; y < zBuffer.numPanels; y++) {
+			yPalette[y] = bigDataFile->readUint16BE();
+		}
+		sortZPal(yPalette, sorted, zBuffer.numPanels);
+		for (y = 0; y < zBuffer.numPanels; y++) {
+			zBuffer.panel[y] = yPalette[sorted[y]];
+			sortback[sorted[y]] = y;
+		}
 
-	int picWidth = sceneWidth;
-	int picHeight = sceneHeight;
-	if (! NPOT_textures) {
-		picWidth = getNextPOT(picWidth);
-		picHeight = getNextPOT(picHeight);
-	}
-	zBuffer.tex = new GLubyte [picHeight * picWidth];
-	if (! checkNew(zBuffer.tex)) return false;
-
-	for (y = 0; y < sceneHeight; y ++) {
-		for (x = 0; x < sceneWidth; x ++) {
-			if (stillToGo == 0) {
-				n = fgetc(bigDataFile);
-				stillToGo = n >> 4;
-				if (stillToGo == 15) stillToGo = bigDataFile->readUint16BE() + 16l;
-				else stillToGo ++;
-				n &= 15;
+		int picWidth = sceneWidth;
+		int picHeight = sceneHeight;
+		if (!NPOT_textures) {
+			picWidth = getNextPOT(picWidth);
+			picHeight = getNextPOT(picHeight);
+		}
+		zBuffer.tex = new GLubyte[picHeight * picWidth];
+		if (!checkNew(zBuffer.tex))
+			return false;
+
+		for (y = 0; y < sceneHeight; y++) {
+			for (x = 0; x < sceneWidth; x++) {
+				if (stillToGo == 0) {
+					n = bigDataFile->readByte();
+					stillToGo = n >> 4;
+					if (stillToGo == 15)
+						stillToGo = bigDataFile->readUint16BE() + 16l;
+					else
+						stillToGo++;
+					n &= 15;
+				}
+				zBuffer.tex[y * picWidth + x] = sortback[n] * 16;
+				stillToGo--;
 			}
-			zBuffer.tex[y * picWidth + x] = sortback[n] * 16;
-			stillToGo --;
 		}
-	}
-	finishAccess();
+		finishAccess();
 #endif
-	setResourceForFatal(-1);
+		setResourceForFatal(-1);
 #if 0
-	if (! zBuffer.texName) glGenTextures(1, &zBuffer.texName);
-	glBindTexture(GL_TEXTURE_2D, zBuffer.texName);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-
-	texImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, picWidth, picHeight, 0, GL_ALPHA, GL_UNSIGNED_BYTE, zBuffer.tex, zBuffer.texName);
+		if (! zBuffer.texName) glGenTextures(1, &zBuffer.texName);
+		glBindTexture(GL_TEXTURE_2D, zBuffer.texName);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+
+		texImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, picWidth, picHeight, 0, GL_ALPHA, GL_UNSIGNED_BYTE, zBuffer.tex, zBuffer.texName);
 #endif
-	return true;
-}
+		return true;
+	}
 
-void drawZBuffer(int x, int y, bool upsidedown) {
-	int i;
+	void drawZBuffer(int x, int y, bool upsidedown) {
+		int i;
 #if 0
-	if (! zBuffer.tex) return;
+		if (! zBuffer.tex) return;
 
-	glEnable(GL_DEPTH_TEST);
-	glEnable(GL_BLEND);
-	glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
-	glDepthMask(GL_TRUE);
+		glEnable(GL_DEPTH_TEST);
+		glEnable(GL_BLEND);
+		glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
+		glDepthMask(GL_TRUE);
 
-	glUseProgram(shader.texture);
+		glUseProgram(shader.texture);
 
-	setPMVMatrix(shader.texture);
+		setPMVMatrix(shader.texture);
 
-	//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
-	glBindTexture(GL_TEXTURE_2D, zBuffer.texName);
+		//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
+		glBindTexture(GL_TEXTURE_2D, zBuffer.texName);
 
-	setPrimaryColor(1.0, 1.0, 1.0, 1.0);
+		setPrimaryColor(1.0, 1.0, 1.0, 1.0);
 
-	for (i = 1; i < zBuffer.numPanels; i++) {
-		GLfloat z = 1.0 - (double) i * (1.0 / 128.0);
+		for (i = 1; i < zBuffer.numPanels; i++) {
+			GLfloat z = 1.0 - (double) i * (1.0 / 128.0);
 
-		GLfloat vy1 = -y, vy2 = zBuffer.height - y;
-		if (upsidedown) {
-			vy1 += zBuffer.height;
-			vy2 -= zBuffer.height;
-		}
+			GLfloat vy1 = -y, vy2 = zBuffer.height - y;
+			if (upsidedown) {
+				vy1 += zBuffer.height;
+				vy2 -= zBuffer.height;
+			}
 
-		const GLfloat vertices[] = {
-			(GLfloat) - x, vy1, z,
-			(GLfloat)zBuffer.width - x, vy1, z,
-			(GLfloat) - x, vy2, z,
-			(GLfloat)zBuffer.width - x, vy2, z
-		};
-
-		const GLfloat texCoords[] = {
-			0.0f, 0.0f,
-			backdropTexW, 0.0f,
-			0.0f, backdropTexH,
-			backdropTexW, backdropTexH
-		};
-
-		glUniform1i(glGetUniformLocation(shader.texture, "zBuffer"), 1);
-		glUniform1f(glGetUniformLocation(shader.texture, "zBufferLayer"), i);
-
-		drawQuad(shader.texture, vertices, 1, texCoords);
-		glUniform1i(glGetUniformLocation(shader.texture, "zBuffer"), 0);
-	}
+			const GLfloat vertices[] = {
+				(GLfloat) - x, vy1, z,
+				(GLfloat)zBuffer.width - x, vy1, z,
+				(GLfloat) - x, vy2, z,
+				(GLfloat)zBuffer.width - x, vy2, z
+			};
+
+			const GLfloat texCoords[] = {
+				0.0f, 0.0f,
+				backdropTexW, 0.0f,
+				0.0f, backdropTexH,
+				backdropTexW, backdropTexH
+			};
+
+			glUniform1i(glGetUniformLocation(shader.texture, "zBuffer"), 1);
+			glUniform1f(glGetUniformLocation(shader.texture, "zBufferLayer"), i);
+
+			drawQuad(shader.texture, vertices, 1, texCoords);
+			glUniform1i(glGetUniformLocation(shader.texture, "zBuffer"), 0);
+		}
 
-	glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
-	glDepthMask(GL_FALSE);
-	glDisable(GL_BLEND);
-	glUseProgram(0);
+		glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+		glDepthMask(GL_FALSE);
+		glDisable(GL_BLEND);
+		glUseProgram(0);
 #endif
-}
+	}
 
-} // End of namespace Sludge
+	} // End of namespace Sludge


Commit: 39c122385672eadbea674ef0233a80104ae07c48
    https://github.com/scummvm/scummvm/commit/39c122385672eadbea674ef0233a80104ae07c48
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: add copyright information

Changed paths:
    engines/sludge/CommonCode/functionlist.h
    engines/sludge/CommonCode/specialsettings.h
    engines/sludge/CommonCode/tga.cpp
    engines/sludge/CommonCode/tga.h
    engines/sludge/CommonCode/utf8.cpp
    engines/sludge/CommonCode/utf8.h
    engines/sludge/CommonCode/version.h


diff --git a/engines/sludge/CommonCode/functionlist.h b/engines/sludge/CommonCode/functionlist.h
index 637ed5c..e59fe44 100644
--- a/engines/sludge/CommonCode/functionlist.h
+++ b/engines/sludge/CommonCode/functionlist.h
@@ -1,3 +1,24 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
 /*
  This is the list of the built in functions
 
@@ -5,7 +26,6 @@
  in the current version of the engine,
  but that value currently isn't used anywhere
  */
-
 FUNC(true, say)
 FUNC(true, skipSpeech)
 FUNC(true, statusText)
diff --git a/engines/sludge/CommonCode/specialsettings.h b/engines/sludge/CommonCode/specialsettings.h
index 1e41e4e..0aa4786 100644
--- a/engines/sludge/CommonCode/specialsettings.h
+++ b/engines/sludge/CommonCode/specialsettings.h
@@ -1,3 +1,24 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
 #define SPECIAL_REGISTERED      1
 #define SPECIAL_FULLSCREEN      2
 #define SPECIAL_MOUSE_1         4
diff --git a/engines/sludge/CommonCode/tga.cpp b/engines/sludge/CommonCode/tga.cpp
index d25ccd9..bcd543d 100644
--- a/engines/sludge/CommonCode/tga.cpp
+++ b/engines/sludge/CommonCode/tga.cpp
@@ -1,3 +1,24 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
 #include <stdio.h>
 
 #include "tga.h"
diff --git a/engines/sludge/CommonCode/tga.h b/engines/sludge/CommonCode/tga.h
index e7f6b55..b1146d0 100644
--- a/engines/sludge/CommonCode/tga.h
+++ b/engines/sludge/CommonCode/tga.h
@@ -1,3 +1,24 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
 #include <stdio.h>
 
 struct TGAHeader {
diff --git a/engines/sludge/CommonCode/utf8.cpp b/engines/sludge/CommonCode/utf8.cpp
index 24d9010..7fe6af1 100644
--- a/engines/sludge/CommonCode/utf8.cpp
+++ b/engines/sludge/CommonCode/utf8.cpp
@@ -1,3 +1,24 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
 /*
   Basic UTF-8 manipulation routines
   by Jeff Bezanson
diff --git a/engines/sludge/CommonCode/utf8.h b/engines/sludge/CommonCode/utf8.h
index 85989ee..71df6cb 100644
--- a/engines/sludge/CommonCode/utf8.h
+++ b/engines/sludge/CommonCode/utf8.h
@@ -1,3 +1,24 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
 #include <stdint.h>
 #include <stdarg.h>
 
diff --git a/engines/sludge/CommonCode/version.h b/engines/sludge/CommonCode/version.h
index 9307bff..f984b0e 100644
--- a/engines/sludge/CommonCode/version.h
+++ b/engines/sludge/CommonCode/version.h
@@ -1,3 +1,24 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
 #define MAJOR_VERSION 2
 #define MINOR_VERSION 2
 #define RELEASE_VERSION 1


Commit: dc380b4ba488e0a2f088955a93ac1b55b557a35a
    https://github.com/scummvm/scummvm/commit/dc380b4ba488e0a2f088955a93ac1b55b557a35a
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: align increment operator

Changed paths:
    engines/sludge/loadsave.cpp
    engines/sludge/moreio.cpp
    engines/sludge/movie.cpp
    engines/sludge/people.cpp
    engines/sludge/sprites.cpp


diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index 50ef4cc..ef50b24 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -107,7 +107,7 @@ void saveStack(variableStack *vs, Common::WriteStream *stream) {
 
 	stream->writeUint16BE(elements);
 	search = vs;
-	for (a = 0; a < elements; ++a) {
+	for (a = 0; a < elements; a++) {
 		saveVariable(&search->thisVar, stream);
 		search = search->next;
 	}
@@ -333,7 +333,7 @@ void saveFunction(loadedFunction *fun, Common::WriteStream *stream) {
 		fatal(ERROR_GAME_SAVE_FROZEN);
 	}
 	saveStack(fun->stack, stream);
-	for (a = 0; a < fun->numLocals; ++a) {
+	for (a = 0; a < fun->numLocals; a++) {
 		saveVariable(&(fun->localVars[a]), stream);
 	}
 }
@@ -368,7 +368,7 @@ loadedFunction *loadFunction(Common::SeekableReadStream *stream) {
 
 	buildFunc->stack = loadStack(stream, NULL);
 
-	for (a = 0; a < buildFunc->numLocals; ++a) {
+	for (a = 0; a < buildFunc->numLocals; a++) {
 		loadVariable(&(buildFunc->localVars[a]), stream);
 	}
 
@@ -442,7 +442,7 @@ bool saveGame(char *fname) {
 		thisFunction = thisFunction->next;
 	}
 
-	for (a = 0; a < numGlobals; ++a) {
+	for (a = 0; a < numGlobals; a++) {
 		saveVariable(&globalVars[a], fp);
 	}
 
@@ -543,7 +543,7 @@ bool loadGame(char *fname) {
 			charOrder = new char[257];
 			if (! checkNew(charOrder)) return false;
 
-			for (int a = 0; a < 256; ++a) {
+			for (int a = 0; a < 256; a++) {
 				x = fgetc(fp);
 				charOrder[x] = a;
 			}
@@ -591,7 +591,7 @@ bool loadGame(char *fname) {
 		buildList = &(rFunc->next);
 	}
 
-	for (a = 0; a < numGlobals; ++a) {
+	for (a = 0; a < numGlobals; a++) {
 		unlinkVar(globalVars[a]);
 		loadVariable(&globalVars[a], fp);
 	}
diff --git a/engines/sludge/moreio.cpp b/engines/sludge/moreio.cpp
index da86553..c7e90ff 100644
--- a/engines/sludge/moreio.cpp
+++ b/engines/sludge/moreio.cpp
@@ -43,7 +43,7 @@ bool allowAnyFilename = true;
 void writeString(char *s, Common::WriteStream *stream) {
 	int a, len = strlen(s);
 	stream->writeUint16BE(len);
-	for (a = 0; a < len; ++a) {
+	for (a = 0; a < len; a++) {
 		stream->writeByte(s[a] + 1);
 	}
 }
@@ -54,7 +54,7 @@ char *readString(Common::SeekableReadStream *stream) {
 	if (!checkNew(s)) {
 		return NULL;
 	}
-	for (a = 0; a < len; ++a) {
+	for (a = 0; a < len; a++) {
 		s[a] = (char)(stream->readByte() - 1);
 	}
 	s[len] = 0;
@@ -187,7 +187,7 @@ char *encodeFilename(char *nameIn) {
 		return newName;
 	} else {
 		int a;
-		for (a = 0; nameIn[a]; ++a) {
+		for (a = 0; nameIn[a]; a++) {
 #ifdef _WIN32
 			if (nameIn[a] == '/') nameIn[a] = '\\';
 #else
diff --git a/engines/sludge/movie.cpp b/engines/sludge/movie.cpp
index cd4ef1b..8aa2ece 100644
--- a/engines/sludge/movie.cpp
+++ b/engines/sludge/movie.cpp
@@ -826,7 +826,7 @@ int playMovie(int fileNumber) {
 						}
 					}
 				}
-				++frameCounter;
+				frameCounter++;
 
 			} else {
 				movieHasEnded:
diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index fb21037..bb23d6a 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -136,7 +136,7 @@ personaAnimation *copyAnim(personaAnimation *orig) {
 		if (!checkNew(newAnim->frames))
 			return NULL;
 
-		for (int a = 0; a < num; ++a) {
+		for (int a = 0; a < num; a++) {
 			newAnim->frames[a].frameNum = orig->frames[a].frameNum;
 			newAnim->frames[a].howMany = orig->frames[a].howMany;
 			newAnim->frames[a].noise = orig->frames[a].noise;
@@ -877,7 +877,7 @@ bool addPerson(int x, int y, int objNum, persona *p) {
 
 int timeForAnim(personaAnimation *fram) {
 	int total = 0;
-	for (int a = 0; a < fram->numFrames; ++a) {
+	for (int a = 0; a < fram->numFrames; a++) {
 		total += fram->frames[a].howMany;
 	}
 	return total;
@@ -976,7 +976,7 @@ bool saveAnim(personaAnimation *p, Common::WriteStream *stream) {
 	if (p->numFrames) {
 		stream->writeUint32LE(p->theSprites->ID);
 
-		for (int a = 0; a < p->numFrames; ++a) {
+		for (int a = 0; a < p->numFrames; a++) {
 			stream->writeUint32LE(p->frames[a].frameNum);
 			stream->writeUint32LE(p->frames[a].howMany);
 			stream->writeUint32LE(p->frames[a].noise);
@@ -995,7 +995,7 @@ bool loadAnim(personaAnimation *p, Common::SeekableReadStream *stream) {
 			return false;
 		p->theSprites = loadBankForAnim(a);
 
-		for (a = 0; a < p->numFrames; ++a) {
+		for (a = 0; a < p->numFrames; a++) {
 			p->frames[a].frameNum = stream->readUint32LE();
 			p->frames[a].howMany = stream->readUint32LE();
 			if (ssgVersion >= VERSION(2, 0)) {
@@ -1014,7 +1014,7 @@ bool loadAnim(personaAnimation *p, Common::SeekableReadStream *stream) {
  void debugCostume (char * message, persona * cossy) {
  FILE * db = fopen ("debuTURN.txt", "at");
  fprintf (db, "  %s costume with %i directions...\n", message, cossy->numDirections);
- for (int a = 0; a < cossy->numDirections * 3; ++a) {
+ for (int a = 0; a < cossy->numDirections * 3; a++) {
  fprintf (db, "      %i frames:", cossy->animation[a]->numFrames);
  for (int b = 0; b < cossy->animation[a]->numFrames; b ++) {
  fprintf (db, " %i", cossy->animation[a]->frames[b]);
@@ -1028,7 +1028,7 @@ bool loadAnim(personaAnimation *p, Common::SeekableReadStream *stream) {
 bool saveCostume(persona *cossy, Common::WriteStream *stream) {
 	int a;
 	stream->writeUint16BE(cossy->numDirections);
-	for (a = 0; a < cossy->numDirections * 3; ++a) {
+	for (a = 0; a < cossy->numDirections * 3; a++) {
 		if (!saveAnim(cossy->animation[a], stream))
 			return false;
 	}
@@ -1042,7 +1042,7 @@ bool loadCostume(persona *cossy, Common::SeekableReadStream *stream) {
 	cossy->animation = new personaAnimation *[cossy->numDirections * 3];
 	if (!checkNew(cossy->animation))
 		return false;
-	for (a = 0; a < cossy->numDirections * 3; ++a) {
+	for (a = 0; a < cossy->numDirections * 3; a++) {
 		cossy->animation[a] = new personaAnimation;
 		if (!checkNew(cossy->animation[a]))
 			return false;
@@ -1069,7 +1069,7 @@ bool savePeople(Common::WriteStream *stream) {
 	stream->writeUint16BE(countPeople);
 
 	me = allPeople;
-	for (a = 0; a < countPeople; ++a) {
+	for (a = 0; a < countPeople; a++) {
 
 		putFloat(me->x, stream);
 		putFloat(me->y, stream);
@@ -1132,7 +1132,7 @@ bool loadPeople(Common::SeekableReadStream *stream) {
 	int a;
 
 	allPeople = NULL;
-	for (a = 0; a < countPeople; ++a) {
+	for (a = 0; a < countPeople; a++) {
 		me = new onScreenPerson;
 		if (!checkNew(me))
 			return false;
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index 936bb67..0927644 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -225,7 +225,7 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 
 	// Make palette for version 0, 1, 2
 	if (!reserveSpritePal(loadhere.myPalette, howmany + startIndex)) return false;
-	for (int i = 0; i < howmany; ++i) {
+	for (int i = 0; i < howmany; i++) {
 		loadhere.myPalette.r[i + startIndex] = (byte)bigDataFile->readByte();
 		loadhere.myPalette.g[i + startIndex] = (byte)bigDataFile->readByte();
 		loadhere.myPalette.b[i + startIndex] = (byte)bigDataFile->readByte();
@@ -246,8 +246,8 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 			}
 		}
 		fromhere = 0;
-		for (int y = 0; y < loadhere.sprites[i].surface.h; ++y) {
-			for (int x = 0; x < loadhere.sprites[i].surface.w; ++x) {
+		for (int y = 0; y < loadhere.sprites[i].surface.h; y++) {
+			for (int x = 0; x < loadhere.sprites[i].surface.w; x++) {
 				byte *target = (byte *)loadhere.sprites[i].surface.getBasePtr(x, y);
 				unsigned char s = spriteData[i][fromhere++];
 				if (s) {


Commit: c44b4f3128931038215cce7c3d1fa23cfa67c75c
    https://github.com/scummvm/scummvm/commit/c44b4f3128931038215cce7c3d1fa23cfa67c75c
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove implementation of tga.h

Changed paths:
  R engines/sludge/CommonCode/tga.cpp
  R engines/sludge/CommonCode/tga.h


diff --git a/engines/sludge/CommonCode/tga.cpp b/engines/sludge/CommonCode/tga.cpp
deleted file mode 100644
index bcd543d..0000000
--- a/engines/sludge/CommonCode/tga.cpp
+++ /dev/null
@@ -1,299 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-#include <stdio.h>
-
-#include "tga.h"
-
-//FILE * debugFile = fopen ("TGAdebug.txt", "wt");
-
-unsigned short int makeColour (unsigned char r, unsigned char g, unsigned char b) {
-	unsigned short int reply = (unsigned short int) (r >> 3);
-	reply <<= 6;
-	reply += (unsigned short int) (g >> 2);
-	reply <<= 5;
-	reply += (unsigned short int) (b >> 3);
-	return reply & 65503;
-}
-
-int get2bytesReverse (FILE * fp) {
-	int a = fgetc (fp);
-	return a + fgetc (fp) * 256;
-}
-
-int countDown = 0;
-
-bool dither24bitImages = 0;
-
-char ditherArray[4][4] = {{4,12,6,14},{10,0,8,2},{7,15,5,13},{9,3,11,1}};
-
-void grabRGBA (FILE * fp, int bpc, unsigned char & r, unsigned char & g, unsigned char & b, unsigned char & a, palCol thePalette[])
-{
-	int grabbed1, grabbed2;
-	switch (bpc) {
-		case 8:
-			grabbed1 = fgetc (fp);
-			r = thePalette[grabbed1].r;
-			g = thePalette[grabbed1].g;
-			b = thePalette[grabbed1].b;
-			if (r == 255 && g == 0 && b == 255) {
-				r = g = b = a = 0;
-			} else a = 255;
-			break;
-			
-		case 16:
-			grabbed1 = fgetc (fp);
-			grabbed2 = fgetc (fp);
-			if (grabbed2*256+grabbed1 == 31775) {
-				r=g=b=a=0;
-				break;
-			}
-
-			r = ((grabbed2 & 127) << 1),
-			g = ((grabbed1 & 224) >> 2) + (grabbed2 << 6);
-			b = ((grabbed1 & 31) << 3);
-			if (r == 255 && g == 0 && b == 255) {
-				r = g = b = a = 0;
-			} else a = 255;
-			break;
-			
-		case 24:
-			b = fgetc (fp);
-			g = fgetc (fp);
-			r = fgetc (fp);
-			if (r == 255 && g == 0 && b == 255) {
-				r = g = b = a = 0;
-			} else a = 255;
-			break;
-			
-		case 32:
-			b = fgetc (fp);
-			g = fgetc (fp);
-			r = fgetc (fp);
-			a = fgetc (fp);
-			break;		
-	}
-}
-
-
-void grabRGB (FILE * fp, int bpc, unsigned char & r, unsigned char & g, unsigned char & b, palCol thePalette[])
-{
-	int a;
-	int grabbed1, grabbed2;
-	switch (bpc) {
-		case 8:
-		grabbed1 = fgetc (fp);
-		r = thePalette[grabbed1].r;
-		g = thePalette[grabbed1].g;
-		b = thePalette[grabbed1].b;
-		break;
-	
-		case 16:
-		grabbed1 = fgetc (fp);
-		grabbed2 = fgetc (fp);
-		r = ((grabbed2 & 127) << 1),
-		g = ((grabbed1 & 224) >> 2) + (grabbed2 << 6);
-		b = ((grabbed1 & 31) << 3);
-		break;
-				
-		case 24:
-		b = fgetc (fp);
-		g = fgetc (fp);
-		r = fgetc (fp);
-		break;
-		
-		case 32:
-		b = fgetc (fp);
-		g = fgetc (fp);
-		r = fgetc (fp);
-		a = fgetc (fp);
-			if (a < 100) {
-				r = 255;
-				g = 0;
-				b = 255;
-			}
-		break;		
-	}
-}
-
-void grabRGBACompressed (FILE * fp, int bpc, unsigned char & r2, unsigned char & g2, unsigned char & b2, unsigned char & a2, palCol thePalette[]) {
-	static unsigned char r, g, b, a;
-	static bool oneCol;
-	unsigned short col;
-	
-	// Do we have to start a new packet?
-	if (countDown == 0) {
-		
-		// Read the packet description thingy
-		col = fgetc (fp);
-		
-		// Is it raw data?
-		if (col >= 128) {
-			oneCol = true;
-			countDown = col - 127;
-			grabRGBA (fp, bpc, r, g, b, a, thePalette);
-			//			fprintf (debugFile, "  %d raw colours...\n", countDown);
-		} else {
-			oneCol = false;
-			countDown = col + 1;
-			//			fprintf (debugFile, "  %d pixels the same colour...\n", countDown);
-		}
-	}
-	
-	countDown --;
-	
-	if (! oneCol) {
-		grabRGBA (fp, bpc, r2, g2, b2, a2, thePalette);
-	} else {
-		r2 = r;
-		g2 = g;
-		b2 = b;
-		a2 = a;
-	}
-}
-
-
-void grabRGBCompressed (FILE * fp, int bpc, unsigned char & r2, unsigned char & g2, unsigned char & b2, palCol thePalette[]) {
-	static unsigned char r, g, b;
-	static bool oneCol;
-	unsigned short col;
-	
-	// Do we have to start a new packet?
-	if (countDown == 0) {
-		
-		// Read the packet description thingy
-		col = fgetc (fp);
-		
-		// Is it raw data?
-		if (col >= 128) {
-			oneCol = true;
-			countDown = col - 127;
-			grabRGB (fp, bpc, r, g, b, thePalette);
-			//			fprintf (debugFile, "  %d raw colours...\n", countDown);
-		} else {
-			oneCol = false;
-			countDown = col + 1;
-			//			fprintf (debugFile, "  %d pixels the same colour...\n", countDown);
-		}
-	}
-	
-	countDown --;
-	
-	if (! oneCol) {
-		grabRGB (fp, bpc, r2, g2, b2, thePalette);
-	} else {
-		r2 = r;
-		g2 = g;
-		b2 = b;
-	}
-}
-
-void addDither (unsigned char & col, const unsigned char add)
-{
-	int tot = col;
-	tot += add;
-	col = (tot > 255) ? 255 : tot;
-}
-
-unsigned short readAColour (FILE * fp, int bpc, palCol thePalette[], int x, int y) {
-	unsigned char r,g,b;
-	grabRGB (fp, bpc, r, g, b, thePalette);
-
-	if (dither24bitImages)
-	{
-		addDither (r, ditherArray[x&3][y&3]);
-		addDither (g, ditherArray[x&3][y&3] / 2);
-		addDither (b, ditherArray[x&3][y&3]);
-	}
-
-	return makeColour (r, g, b);
-}
-
-unsigned short readCompressedColour (FILE * fp, int bpc, palCol thePalette[], int x, int y) {
-	unsigned char r,g,b;
-	grabRGBCompressed (fp, bpc, r, g, b, thePalette);
-	
-	if (dither24bitImages)
-	{
-		addDither (r, ditherArray[x&3][y&3]);
-		addDither (g, ditherArray[x&3][y&3] / 2);
-		addDither (b, ditherArray[x&3][y&3]);
-	}
-	
-	return makeColour (r, g, b);
-}
-
-const char * readTGAHeader (TGAHeader & h, FILE * fp, palCol thePalette[]) {
-
-	h.IDBlockSize = fgetc (fp);
-	h.gotMap = fgetc (fp);
-	unsigned char imageType = fgetc (fp);
-	h.firstPalColour = get2bytesReverse (fp);
-	h.numPalColours = get2bytesReverse (fp);
-	h.bitsPerPalColour = fgetc (fp);
-	h.xOrigin = get2bytesReverse (fp);
-	h.yOrigin = get2bytesReverse (fp);
-	h.width = get2bytesReverse (fp);
-	h.height = get2bytesReverse (fp);
-	h.pixelDepth = fgetc (fp);
-	h.imageDescriptor = fgetc (fp);
-	countDown = 0;
-	// Who cares about the ID block?
-	fseek (fp, h.IDBlockSize, 1);
-
-	switch (imageType) {
-		case 1:
-		case 2:
-		h.compressed = false;
-		break;
-		
-		case 9:
-		case 10:
-		h.compressed = true;
-		break;
-		
-		default:
-		return "Unsupported internal image format... are you sure this is a valid TGA image file?";
-	}
-
-	if (h.pixelDepth != 8 && h.pixelDepth != 16 && h.pixelDepth != 24 && h.pixelDepth != 32) {
-		return "Colour depth is not 8, 16, 24 or 32 bits... are you sure this is a valid TGA image file?";
-	}
-
-	if (h.gotMap) {
-		int c;
-		for (c = 0; c < h.numPalColours; c ++) {
-			grabRGB (fp, h.bitsPerPalColour, thePalette[c].r, thePalette[c].g, thePalette[c].b, thePalette);
-		}
-	}
-
-	return NULL;
-}
-
-void setDither (int dither)
-{
-	dither24bitImages = dither;
-}
-
-bool getDither ()
-{
-	return dither24bitImages;
-}
diff --git a/engines/sludge/CommonCode/tga.h b/engines/sludge/CommonCode/tga.h
deleted file mode 100644
index b1146d0..0000000
--- a/engines/sludge/CommonCode/tga.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-#include <stdio.h>
-
-struct TGAHeader {
-	unsigned char IDBlockSize;
-	unsigned char gotMap;
-	bool compressed;
-	unsigned short int firstPalColour;
-	unsigned short int numPalColours;
-	unsigned char bitsPerPalColour;
-	unsigned short xOrigin;
-	unsigned short yOrigin;
-	unsigned short width;
-	unsigned short height;
-	unsigned char pixelDepth;
-	unsigned char imageDescriptor;
-};
-
-struct palCol {
-	unsigned char r, g, b;
-};
-
-void grabRGBCompressed(FILE *fp, int bpc, unsigned char &r2, unsigned char &g2, unsigned char &b2, palCol thePalette[]);
-void grabRGB(FILE *fp, int bpc, unsigned char &r, unsigned char &g, unsigned char &b, palCol thePalette[]);
-void grabRGBACompressed(FILE *fp, int bpc, unsigned char &r2, unsigned char &g2, unsigned char &b2, unsigned char &a2, palCol thePalette[]);
-void grabRGBA(FILE *fp, int bpc, unsigned char &r, unsigned char &g, unsigned char &b, unsigned char &a, palCol thePalette[]);
-
-unsigned short int makeColour(unsigned char r, unsigned char g, unsigned char b);
-unsigned short readAColour(FILE *fp, int bpc, palCol thePalette[], int x, int y);
-unsigned short readCompressedColour(FILE *fp, int bpc, palCol thePalette[], int x, int y);
-const char *readTGAHeader(TGAHeader &h, FILE *fp, palCol thePalette[]);
-void setDither(int dither);
-bool getDither();
-
-inline unsigned short redValue(unsigned short c) {
-	return (c >> 11) << 3;
-}
-inline unsigned short greenValue(unsigned short c) {
-	return ((c >> 5) & 63) << 2;
-}
-inline unsigned short blueValue(unsigned short c) {
-	return (c & 31) << 3;
-}
-inline int brightness(unsigned short c) {
-	return ((int) redValue(c)) + ((int) greenValue(c)) + ((int) blueValue(c) >> 1);
-}


Commit: a8ccd053157f18c5d125bb114cdb1e17ac17460a
    https://github.com/scummvm/scummvm/commit/a8ccd053157f18c5d125bb114cdb1e17ac17460a
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: header formatting

Changed paths:
    engines/sludge/backdrop.cpp
    engines/sludge/backdrop.h
    engines/sludge/bg_effects.cpp
    engines/sludge/builtin.cpp
    engines/sludge/cursors.cpp
    engines/sludge/debug.cpp
    engines/sludge/fileset.cpp
    engines/sludge/floor.cpp
    engines/sludge/fonttext.cpp
    engines/sludge/freeze.cpp
    engines/sludge/graphics.cpp
    engines/sludge/graphics.h
    engines/sludge/helpers.cpp
    engines/sludge/hsi.cpp
    engines/sludge/imgloader.cpp
    engines/sludge/language.cpp
    engines/sludge/language.h
    engines/sludge/line.cpp
    engines/sludge/loadsave.cpp
    engines/sludge/main_loop.cpp
    engines/sludge/memwatch.cpp
    engines/sludge/moreio.cpp
    engines/sludge/movie.cpp
    engines/sludge/newfatal.cpp
    engines/sludge/newfatal.h
    engines/sludge/objtypes.cpp
    engines/sludge/people.cpp
    engines/sludge/region.cpp
    engines/sludge/savedata.cpp
    engines/sludge/shaders.cpp
    engines/sludge/sludge.cpp
    engines/sludge/sludger.cpp
    engines/sludge/sludger.h
    engines/sludge/sound.h
    engines/sludge/sound_bass.cpp
    engines/sludge/sound_nosound.cpp
    engines/sludge/sound_openal.cpp
    engines/sludge/sprbanks.cpp
    engines/sludge/sprbanks.h
    engines/sludge/sprites.cpp
    engines/sludge/statusba.cpp
    engines/sludge/stringy.cpp
    engines/sludge/talk.cpp
    engines/sludge/talk.h
    engines/sludge/thumbnail.cpp
    engines/sludge/transition.cpp
    engines/sludge/variable.cpp
    engines/sludge/vid.cpp
    engines/sludge/zbuffer.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index 2418593..d80a8ae 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -20,32 +20,25 @@
  *
  */
 
-#include "allfiles.h"
-#include "debug.h"
-#include "newfatal.h"
-#include "colours.h"
-#include "fileset.h"
-#include "cursors.h"
-#include "backdrop.h"
-#include "language.h"
-#include "moreio.h"
-#include "variable.h"
-#include "zbuffer.h"
-#include "graphics.h"
-#include "line.h"
-#include "people.h"
-#include "talk.h"
-#include "sludger.h"
-#include "statusba.h"
-#include "variable.h"
-#include "CommonCode/version.h"
 #include "common/debug.h"
+#include "common/rect.h"
 #include "image/png.h"
 #include "graphics/surface.h"
 #include "graphics/palette.h"
-#include "sludge.h"
-#include "imgloader.h"
-#include "common/rect.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/newfatal.h"
+#include "sludge/colours.h"
+#include "sludge/fileset.h"
+#include "sludge/backdrop.h"
+#include "sludge/moreio.h"
+#include "sludge/zbuffer.h"
+#include "sludge/graphics.h"
+#include "sludge/line.h"
+#include "sludge/sludge.h"
+#include "sludge/sludger.h"
+#include "sludge/variable.h"
+#include "sludge/imgloader.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/backdrop.h b/engines/sludge/backdrop.h
index 01f21b0..a381389 100644
--- a/engines/sludge/backdrop.h
+++ b/engines/sludge/backdrop.h
@@ -23,8 +23,8 @@
 #ifndef SLUDGE_BACKDROP_H
 #define SLUDGE_BACKDROP_H
 
-#include "variable.h"
-#include "graphics.h"
+#include "sludge/graphics.h"
+#include "sludge/variable.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/bg_effects.cpp b/engines/sludge/bg_effects.cpp
index 3692026..100b906 100644
--- a/engines/sludge/bg_effects.cpp
+++ b/engines/sludge/bg_effects.cpp
@@ -20,17 +20,17 @@
  *
  */
 
-#include "allfiles.h"
-#include "backdrop.h"
-#include "colours.h"
-#include "debug.h"
-#include "graphics.h"
-#include "newfatal.h"
-#include "moreio.h"
-
 #include "common/debug.h"
 #include "common/file.h"
 
+#include "sludge/allfiles.h"
+#include "sludge/backdrop.h"
+#include "sludge/colours.h"
+#include "sludge/debug.h"
+#include "sludge/graphics.h"
+#include "sludge/moreio.h"
+#include "sludge/newfatal.h"
+
 namespace Sludge {
 
 #if 0
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 58926b2..9733689 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -24,37 +24,37 @@
 #include <SDL/SDL.h>
 #endif
 
-#include "debug.h"
-#include "allfiles.h"
-#include "sludger.h"
-#include "builtin.h"
-#include "stringy.h"
-#include "newfatal.h"
-#include "cursors.h"
-#include "statusba.h"
-#include "loadsave.h"
-#include "backdrop.h"
-#include "bg_effects.h"
-#include "sprites.h"
-#include "fonttext.h"
-#include "sprbanks.h"
-#include "people.h"
-#include "sound.h"
-#include "objtypes.h"
-#include "floor.h"
-#include "zbuffer.h"
-#include "talk.h"
-#include "region.h"
-#include "language.h"
-#include "moreio.h"
-#include "movie.h"
-#include "savedata.h"
-#include "freeze.h"
-#include "colours.h"
-#include "language.h"
-#include "thumbnail.h"
-#include "graphics.h"
-#include "CommonCode/utf8.h"
+#include "sludge/debug.h"
+#include "sludge/allfiles.h"
+#include "sludge/sludger.h"
+#include "sludge/builtin.h"
+#include "sludge/stringy.h"
+#include "sludge/newfatal.h"
+#include "sludge/cursors.h"
+#include "sludge/statusba.h"
+#include "sludge/loadsave.h"
+#include "sludge/backdrop.h"
+#include "sludge/bg_effects.h"
+#include "sludge/sprites.h"
+#include "sludge/fonttext.h"
+#include "sludge/sprbanks.h"
+#include "sludge/people.h"
+#include "sludge/sound.h"
+#include "sludge/objtypes.h"
+#include "sludge/floor.h"
+#include "sludge/zbuffer.h"
+#include "sludge/talk.h"
+#include "sludge/region.h"
+#include "sludge/language.h"
+#include "sludge/moreio.h"
+#include "sludge/movie.h"
+#include "sludge/savedata.h"
+#include "sludge/freeze.h"
+#include "sludge/colours.h"
+#include "sludge/language.h"
+#include "sludge/thumbnail.h"
+#include "sludge/graphics.h"
+#include "sludge/CommonCode/utf8.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/cursors.cpp b/engines/sludge/cursors.cpp
index 562f386..4720677 100644
--- a/engines/sludge/cursors.cpp
+++ b/engines/sludge/cursors.cpp
@@ -28,13 +28,13 @@
 #endif
 #endif
 
-#include "allfiles.h"
-#include "cursors.h"
-#include "colours.h"
-#include "sprites.h"
-#include "sprbanks.h"
-#include "people.h"
-#include "sludger.h"
+#include "sludge/allfiles.h"
+#include "sludge/cursors.h"
+#include "sludge/colours.h"
+#include "sludge/sprites.h"
+#include "sludge/sprbanks.h"
+#include "sludge/people.h"
+#include "sludge/sludger.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/debug.cpp b/engines/sludge/debug.cpp
index 3e256bd..e79571a 100644
--- a/engines/sludge/debug.cpp
+++ b/engines/sludge/debug.cpp
@@ -24,9 +24,9 @@
 #include <stdarg.h>
 #endif
 
-#include "allfiles.h"
-#include "debug.h"
-#include "language.h"
+#include "sludge/allfiles.h"
+#include "sludge/debug.h"
+#include "sludge/language.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/fileset.cpp b/engines/sludge/fileset.cpp
index cf85814..2c4216d 100644
--- a/engines/sludge/fileset.cpp
+++ b/engines/sludge/fileset.cpp
@@ -27,16 +27,16 @@
 #include <iconv.h>
 #endif
 
-#include "debug.h"
-#include "stringy.h"
-#include "allfiles.h"
-#include "moreio.h"
-#include "newfatal.h"
-#include "CommonCode/version.h"
-
 #include "common/file.h"
 #include "common/debug.h"
-#include "sludge.h"
+
+#include "sludge/debug.h"
+#include "sludge/stringy.h"
+#include "sludge/allfiles.h"
+#include "sludge/moreio.h"
+#include "sludge/newfatal.h"
+#include "sludge/sludge.h"
+#include "sludge/CommonCode/version.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/floor.cpp b/engines/sludge/floor.cpp
index 29038b3..a402ef9 100644
--- a/engines/sludge/floor.cpp
+++ b/engines/sludge/floor.cpp
@@ -19,12 +19,13 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-#include "newfatal.h"
-#include "fileset.h"
-#include "moreio.h"
-#include "floor.h"
-#include "line.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/newfatal.h"
+#include "sludge/fileset.h"
+#include "sludge/moreio.h"
+#include "sludge/floor.h"
+#include "sludge/line.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/fonttext.cpp b/engines/sludge/fonttext.cpp
index 4dfdd10..bf7de8b 100644
--- a/engines/sludge/fonttext.cpp
+++ b/engines/sludge/fonttext.cpp
@@ -19,22 +19,17 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "platform-dependent.h"
 
-#include <stdint.h>
-#include <string.h>
-
-#include "CommonCode/utf8.h"
-
-#include "debug.h"
-#include "allfiles.h"
-#include "stringy.h"
-
-#include "sprites.h"
-#include "colours.h"
-#include "fonttext.h"
-#include "newfatal.h"
-#include "moreio.h"
+#include "sludge/debug.h"
+#include "sludge/allfiles.h"
+#include "sludge/stringy.h"
+#include "sludge/sprites.h"
+#include "sludge/colours.h"
+#include "sludge/fonttext.h"
+#include "sludge/newfatal.h"
+#include "sludge/moreio.h"
+#include "sludge/platform-dependent.h"
+#include "sludge/CommonCode/utf8.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/freeze.cpp b/engines/sludge/freeze.cpp
index d5aa29d..676c06b 100644
--- a/engines/sludge/freeze.cpp
+++ b/engines/sludge/freeze.cpp
@@ -19,22 +19,22 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-#include "debug.h"
-#include "graphics.h"
-#include "newfatal.h"
-#include "sprites.h"
-#include "sprbanks.h"
-#include "people.h"
-#include "sludger.h"
-#include "objtypes.h"
-#include "region.h"
-#include "backdrop.h"
-#include "talk.h"
-#include "fonttext.h"
-#include "statusba.h"
-#include "freeze.h"
-#include "zbuffer.h"
+#include "sludge/allfiles.h"
+#include "sludge/debug.h"
+#include "sludge/graphics.h"
+#include "sludge/newfatal.h"
+#include "sludge/sprites.h"
+#include "sludge/sprbanks.h"
+#include "sludge/people.h"
+#include "sludge/sludger.h"
+#include "sludge/objtypes.h"
+#include "sludge/region.h"
+#include "sludge/backdrop.h"
+#include "sludge/talk.h"
+#include "sludge/fonttext.h"
+#include "sludge/statusba.h"
+#include "sludge/freeze.h"
+#include "sludge/zbuffer.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/graphics.cpp b/engines/sludge/graphics.cpp
index 7c7c7be..e48ad8c 100644
--- a/engines/sludge/graphics.cpp
+++ b/engines/sludge/graphics.cpp
@@ -23,25 +23,7 @@
 #include <stdarg.h>
 
 #include <SDL/SDL.h>
-#endif
-
-#include "allfiles.h"
-#include "debug.h"
-#include "platform-dependent.h"
-#include "CommonCode/specialsettings.h"
-#include "graphics.h"
-#include "language.h"
-#include "newfatal.h"
-#include "sprbanks.h"
-#include "zbuffer.h"
-#include "backdrop.h"
-#include "shaders.h"
-#include "movie.h"
-#include "stringy.h"
-
-#include "language.h" // for settings
 
-#if 0
 #if !defined(HAVE_GLES2)
 #ifdef _WIN32
 #include <GL\glu.h> // handy for gluErrorString
@@ -53,6 +35,20 @@
 #endif
 #endif
 
+#include "sludge/allfiles.h"
+#include "sludge/debug.h"
+#include "sludge/platform-dependent.h"
+#include "sludge/graphics.h"
+#include "sludge/language.h"
+#include "sludge/newfatal.h"
+#include "sludge/sprbanks.h"
+#include "sludge/zbuffer.h"
+#include "sludge/backdrop.h"
+#include "sludge/shaders.h"
+#include "sludge/movie.h"
+#include "sludge/stringy.h"
+#include "sludge/CommonCode/specialsettings.h"
+
 namespace Sludge {
 
 unsigned int winWidth, winHeight;
@@ -857,9 +853,8 @@ void setupOpenGLStuff() {
 	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
 	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
 	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
-#endif
 	setGraphicsWindow(gameSettings.userFullScreen, false);
-
+#endif
 #if !defined(HAVE_GLES2)
 #if 0
 	/* Check for graphics capabilities... */
diff --git a/engines/sludge/graphics.h b/engines/sludge/graphics.h
index ba23d72..5d2bb9a 100644
--- a/engines/sludge/graphics.h
+++ b/engines/sludge/graphics.h
@@ -39,9 +39,9 @@ struct texture {
 #if 0
 	GLubyte *data;
 	GLuint name;
+	double texW, texH;
 #endif
 	Graphics::Surface surface;
-	double texW, texH;
 };
 
 #if 0
diff --git a/engines/sludge/helpers.cpp b/engines/sludge/helpers.cpp
index 60a29af..9cc44ab 100644
--- a/engines/sludge/helpers.cpp
+++ b/engines/sludge/helpers.cpp
@@ -19,11 +19,12 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-#include "helpers.h"
 
 #include "common/file.h"
 
+#include "sludge/allfiles.h"
+#include "sludge/helpers.h"
+
 namespace Sludge {
 
 bool fileExists(const char *file) {
diff --git a/engines/sludge/hsi.cpp b/engines/sludge/hsi.cpp
index 5281ff7..2ce87d8 100644
--- a/engines/sludge/hsi.cpp
+++ b/engines/sludge/hsi.cpp
@@ -25,9 +25,9 @@
 
 #include "graphics/surface.h"
 
-#include "colours.h"
-#include "hsi.h"
-#include "sludge.h"
+#include "sludge/colours.h"
+#include "sludge/hsi.h"
+#include "sludge/sludge.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/imgloader.cpp b/engines/sludge/imgloader.cpp
index f76c7b6..8036b4c 100644
--- a/engines/sludge/imgloader.cpp
+++ b/engines/sludge/imgloader.cpp
@@ -25,11 +25,11 @@
 #include "image/png.h"
 #include "graphics/surface.h"
 
-#include "allfiles.h"
-#include "hsi.h"
-#include "imgloader.h"
-#include "colours.h"
-#include "sludge.h"
+#include "sludge/allfiles.h"
+#include "sludge/hsi.h"
+#include "sludge/imgloader.h"
+#include "sludge/colours.h"
+#include "sludge/sludge.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/language.cpp b/engines/sludge/language.cpp
index 8d795a0..d06dda3 100644
--- a/engines/sludge/language.cpp
+++ b/engines/sludge/language.cpp
@@ -19,15 +19,15 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-#include "stringy.h"
-#include "newfatal.h"
-#include "moreio.h"
-#include "language.h"
-#include "CommonCode/version.h"
-#include "platform-dependent.h"
-
-#include "sludge.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/stringy.h"
+#include "sludge/newfatal.h"
+#include "sludge/moreio.h"
+#include "sludge/language.h"
+#include "sludge/platform-dependent.h"
+#include "sludge/sludge.h"
+#include "sludge/CommonCode/version.h"
 
 #include "common/debug.h"
 
diff --git a/engines/sludge/language.h b/engines/sludge/language.h
index 93805c2..033633b 100644
--- a/engines/sludge/language.h
+++ b/engines/sludge/language.h
@@ -22,10 +22,10 @@
 #ifndef LANGUAGE_H
 #define LANGUAGE_H
 
-#include "allfiles.h"
-
 #include "common/file.h"
 
+#include "sludge/allfiles.h"
+
 namespace Sludge {
 
 struct settingsStruct {
diff --git a/engines/sludge/line.cpp b/engines/sludge/line.cpp
index 0067163..b041884 100644
--- a/engines/sludge/line.cpp
+++ b/engines/sludge/line.cpp
@@ -23,8 +23,8 @@
 #include <stdlib.h>
 #endif
 
-#include "graphics.h"
-#include "allfiles.h"
+#include "sludge/graphics.h"
+#include "sludge/allfiles.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index ef50b24..db6afb1 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -19,28 +19,29 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-#include "sprites.h"
-#include "fonttext.h"
-#include "newfatal.h"
-#include "variable.h"
-#include "CommonCode/version.h"
-#include "language.h"
-#include "moreio.h"
-#include "sludger.h"
-#include "people.h"
-#include "talk.h"
-#include "objtypes.h"
-#include "backdrop.h"
-#include "region.h"
-#include "floor.h"
-#include "zbuffer.h"
-#include "cursors.h"
-#include "statusba.h"
-#include "sound.h"
-#include "fileset.h"
-#include "debug.h"
-#include "loadsave.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/sprites.h"
+#include "sludge/fonttext.h"
+#include "sludge/newfatal.h"
+#include "sludge/variable.h"
+#include "sludge/language.h"
+#include "sludge/moreio.h"
+#include "sludge/sludger.h"
+#include "sludge/people.h"
+#include "sludge/talk.h"
+#include "sludge/objtypes.h"
+#include "sludge/backdrop.h"
+#include "sludge/region.h"
+#include "sludge/floor.h"
+#include "sludge/zbuffer.h"
+#include "sludge/cursors.h"
+#include "sludge/statusba.h"
+#include "sludge/sound.h"
+#include "sludge/fileset.h"
+#include "sludge/debug.h"
+#include "sludge/loadsave.h"
+#include "sludge/CommonCode/version.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index 14ffed0..143d84f 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -52,30 +52,32 @@
 #include <SDL/SDL_syswm.h>
 #endif
 
-#include "allfiles.h"
-#include "debug.h"
-#include "platform-dependent.h"
-#include "language.h"
-#include "stringy.h"
-#include "sludger.h"
-#include "backdrop.h"
-#include "language.h"
-#include "newfatal.h"
-#include "people.h"
-#include "floor.h"
-#include "objtypes.h"
-#include "talk.h"
-#include "statusba.h"
-#include "transition.h"
-#include "CommonCode/specialsettings.h"
-#include "timing.h"
-#include "sound.h"
-#include "sludger.h"
-#include "graphics.h"
-#include "helpers.h"
-#include "graphics/surface.h"
 #include "common/debug.h"
-#include "sludge.h"
+
+#include "graphics/surface.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/debug.h"
+#include "sludge/platform-dependent.h"
+#include "sludge/language.h"
+#include "sludge/stringy.h"
+#include "sludge/sludger.h"
+#include "sludge/backdrop.h"
+#include "sludge/language.h"
+#include "sludge/newfatal.h"
+#include "sludge/people.h"
+#include "sludge/floor.h"
+#include "sludge/objtypes.h"
+#include "sludge/talk.h"
+#include "sludge/statusba.h"
+#include "sludge/transition.h"
+#include "sludge/timing.h"
+#include "sludge/sound.h"
+#include "sludge/sludger.h"
+#include "sludge/graphics.h"
+#include "sludge/helpers.h"
+#include "sludge/sludge.h"
+#include "sludge/CommonCode/specialsettings.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/memwatch.cpp b/engines/sludge/memwatch.cpp
index f9148c5..1a35f53 100644
--- a/engines/sludge/memwatch.cpp
+++ b/engines/sludge/memwatch.cpp
@@ -19,10 +19,11 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
 
 #include "common/debug.h"
 
+#include "sludge/allfiles.h"
+
 namespace Sludge {
 
 void *allKnownMem[3000];
diff --git a/engines/sludge/moreio.cpp b/engines/sludge/moreio.cpp
index c7e90ff..7dca5a6 100644
--- a/engines/sludge/moreio.cpp
+++ b/engines/sludge/moreio.cpp
@@ -19,16 +19,16 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-#include "moreio.h"
-#include "newfatal.h"
-#include "stringy.h"
-
-#include "sludge.h"
 
 #include "common/debug.h"
 #include "common/file.h"
 
+#include "sludge/allfiles.h"
+#include "sludge/moreio.h"
+#include "sludge/newfatal.h"
+#include "sludge/stringy.h"
+#include "sludge/sludge.h"
+
 #if defined __unix__ && !(defined __APPLE__)
 #include <endian.h>
 #if __BYTE_ORDER == __BIG_ENDIAN
diff --git a/engines/sludge/movie.cpp b/engines/sludge/movie.cpp
index 8aa2ece..dc49cc4 100644
--- a/engines/sludge/movie.cpp
+++ b/engines/sludge/movie.cpp
@@ -21,31 +21,10 @@
  */
 #if 0
 #include <SDL/SDL.h>
-#endif
-
-#include <math.h>
-
-#include "CommonCode/specialsettings.h"
-
-#include "libwebm/mkvreader.hpp"
-#include "libwebm/mkvparser.hpp"
-
-#if 0
 #define VPX_CODEC_DISABLE_COMPAT 1
 #include "vpx/vpx_decoder.h"
 #include "vpx/vp8dx.h"
 #define interface (&vpx_codec_vp8_dx_algo)
-#endif
-
-#include "newfatal.h"
-#include "timing.h"
-#include "graphics.h"
-#include "movie.h"
-#include "shaders.h"
-
-#include "sound.h"
-
-#if 0
 #include "vorbis/codec.h"
 #define OV_EXCLUDE_STATIC_CALLBACKS
 #include "vorbis/vorbisfile.h"
@@ -56,6 +35,17 @@
 #include "AL/alure.h"
 #endif
 
+#include "sludge/CommonCode/specialsettings.h"
+#include "sludge/libwebm/mkvreader.hpp"
+#include "sludge/libwebm/mkvparser.hpp"
+
+#include "sludge/newfatal.h"
+#include "sludge/timing.h"
+#include "sludge/graphics.h"
+#include "sludge/movie.h"
+#include "sludge/shaders.h"
+#include "sludge/sound.h"
+
 namespace Sludge {
 
 extern int specialSettings;
diff --git a/engines/sludge/newfatal.cpp b/engines/sludge/newfatal.cpp
index a6887d4..c00476d 100644
--- a/engines/sludge/newfatal.cpp
+++ b/engines/sludge/newfatal.cpp
@@ -26,16 +26,16 @@
 #include <stdlib.h>
 #endif
 
-#include "allfiles.h"
-
 #include "common/debug.h"
-#include "platform-dependent.h"
-#include "CommonCode/version.h"
-#include "sound.h"
-#include "stringy.h"
-#include "errors.h"
-#include "graphics.h"
-#include "sludge.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/platform-dependent.h"
+#include "sludge/sound.h"
+#include "sludge/stringy.h"
+#include "sludge/errors.h"
+#include "sludge/graphics.h"
+#include "sludge/sludge.h"
+#include "sludge/CommonCode/version.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/newfatal.h b/engines/sludge/newfatal.h
index a97dca8..089b053 100644
--- a/engines/sludge/newfatal.h
+++ b/engines/sludge/newfatal.h
@@ -22,7 +22,7 @@
 #ifndef SLUDGE_NEWFATAL_H
 #define SLUDGE_NEWFATAL_H
 
-#include "errors.h"
+#include "sludge/errors.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/objtypes.cpp b/engines/sludge/objtypes.cpp
index a765f3f..ffd2c83 100644
--- a/engines/sludge/objtypes.cpp
+++ b/engines/sludge/objtypes.cpp
@@ -19,13 +19,14 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-#include "objtypes.h"
-#include "variable.h"
-#include "newfatal.h"
-#include "moreio.h"
-#include "fileset.h"
-#include "CommonCode/version.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/objtypes.h"
+#include "sludge/variable.h"
+#include "sludge/newfatal.h"
+#include "sludge/moreio.h"
+#include "sludge/fileset.h"
+#include "sludge/CommonCode/version.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index bb23d6a..ebbf762 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -19,26 +19,26 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-#include <math.h>
+
 #include <stdlib.h>
 
-#include "CommonCode/version.h"
-#include "sprites.h"
-#include "sprbanks.h"
-#include "sludger.h"
-#include "objtypes.h"
-#include "region.h"
-#include "people.h"
-#include "talk.h"
-#include "newfatal.h"
-#include "variable.h"
-#include "moreio.h"
-#include "loadsave.h"
-#include "floor.h"
-#include "zbuffer.h"
-#include "sound.h"
-#include "debug.h"
+#include "sludge/allfiles.h"
+#include "sludge/sprites.h"
+#include "sludge/sprbanks.h"
+#include "sludge/sludger.h"
+#include "sludge/objtypes.h"
+#include "sludge/region.h"
+#include "sludge/people.h"
+#include "sludge/talk.h"
+#include "sludge/newfatal.h"
+#include "sludge/variable.h"
+#include "sludge/moreio.h"
+#include "sludge/loadsave.h"
+#include "sludge/floor.h"
+#include "sludge/zbuffer.h"
+#include "sludge/sound.h"
+#include "sludge/debug.h"
+#include "sludge/CommonCode/version.h"
 
 #define ANGLEFIX (180.0 / 3.14157)
 #define ANI_STAND 0
diff --git a/engines/sludge/region.cpp b/engines/sludge/region.cpp
index 9c565a3..c6fa06e 100644
--- a/engines/sludge/region.cpp
+++ b/engines/sludge/region.cpp
@@ -19,13 +19,14 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-#include "objtypes.h"
-#include "region.h"
-#include "newfatal.h"
-#include "sludger.h"
-#include "moreio.h"
-#include "backdrop.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/backdrop.h"
+#include "sludge/moreio.h"
+#include "sludge/newfatal.h"
+#include "sludge/objtypes.h"
+#include "sludge/region.h"
+#include "sludge/sludger.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/savedata.cpp b/engines/sludge/savedata.cpp
index bb13152..f79e7fb 100644
--- a/engines/sludge/savedata.cpp
+++ b/engines/sludge/savedata.cpp
@@ -21,16 +21,15 @@
  */
 #include <stdint.h>
 #include <unistd.h>
-#include <string.h>
-
-#include "allfiles.h"
-#include "debug.h"
-#include "variable.h"
-#include "newfatal.h"
-#include "moreio.h"
 
 #include "common/file.h"
 
+#include "sludge/allfiles.h"
+#include "sludge/debug.h"
+#include "sludge/variable.h"
+#include "sludge/newfatal.h"
+#include "sludge/moreio.h"
+
 #define LOAD_ERROR "Can't load custom data...\n\n"
 
 namespace Sludge {
diff --git a/engines/sludge/shaders.cpp b/engines/sludge/shaders.cpp
index cd95079..69c3f99 100644
--- a/engines/sludge/shaders.cpp
+++ b/engines/sludge/shaders.cpp
@@ -19,11 +19,12 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-#include "debug.h"
-#include "stringy.h"
-#include "shaders.h"
-#include "graphics.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/debug.h"
+#include "sludge/stringy.h"
+#include "sludge/shaders.h"
+#include "sludge/graphics.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/sludge.cpp b/engines/sludge/sludge.cpp
index 85775f0..725478c 100644
--- a/engines/sludge/sludge.cpp
+++ b/engines/sludge/sludge.cpp
@@ -20,7 +20,6 @@
  *
  */
 #include "common/scummsys.h"
-
 #include "common/config-manager.h"
 #include "common/debug.h"
 #include "common/debug-channels.h"
@@ -29,7 +28,7 @@
 #include "engines/util.h"
 
 #include "sludge/sludge.h"
-#include "main_loop.h"
+#include "sludge/main_loop.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index a018d74..3ae7c35 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -33,38 +33,39 @@
 #include <iconv.h>
 #endif
 
-#include "allfiles.h"
-#include "platform-dependent.h"
-#include "CommonCode/version.h"
-#include "sludger.h"
-#include "backdrop.h"
-#include "cursors.h"
-#include "colours.h"
-#include "objtypes.h"
-#include "region.h"
-#include "sprites.h"
-#include "sprbanks.h"
-#include "people.h"
-#include "talk.h"
-#include "newfatal.h"
-#include "stringy.h"
-#include "moreio.h"
-#include "statusba.h"
-#include "builtin.h"
-#include "fonttext.h"
-#include "freeze.h"
-#include "floor.h"
-#include "zbuffer.h"
-#include "sound.h"
-#include "loadsave.h"
-#include "fileset.h"
-#include "transition.h"
-#include "language.h"
-#include "CommonCode/specialsettings.h"
-#include "graphics.h"
-#include "variable.h"
 #include "common/debug.h"
-#include "sludge.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/platform-dependent.h"
+#include "sludge/sludger.h"
+#include "sludge/backdrop.h"
+#include "sludge/cursors.h"
+#include "sludge/colours.h"
+#include "sludge/objtypes.h"
+#include "sludge/region.h"
+#include "sludge/sprites.h"
+#include "sludge/sprbanks.h"
+#include "sludge/people.h"
+#include "sludge/talk.h"
+#include "sludge/newfatal.h"
+#include "sludge/stringy.h"
+#include "sludge/moreio.h"
+#include "sludge/statusba.h"
+#include "sludge/builtin.h"
+#include "sludge/fonttext.h"
+#include "sludge/freeze.h"
+#include "sludge/floor.h"
+#include "sludge/zbuffer.h"
+#include "sludge/sound.h"
+#include "sludge/loadsave.h"
+#include "sludge/fileset.h"
+#include "sludge/transition.h"
+#include "sludge/language.h"
+#include "sludge/graphics.h"
+#include "sludge/variable.h"
+#include "sludge/sludge.h"
+#include "sludge/CommonCode/specialsettings.h"
+#include "sludge/CommonCode/version.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/sludger.h b/engines/sludge/sludger.h
index f5030ef..591bd13 100644
--- a/engines/sludge/sludger.h
+++ b/engines/sludge/sludger.h
@@ -24,13 +24,13 @@
 
 #include <stdint.h>
 
-#include "allfiles.h"
-#include "variable.h"
-#include "csludge.h"
-#include "language.h"
-
 #include "common/file.h"
 
+#include "sludge/allfiles.h"
+#include "sludge/variable.h"
+#include "sludge/csludge.h"
+#include "sludge/language.h"
+
 namespace Sludge {
 
 #ifndef _WIN32
diff --git a/engines/sludge/sound.h b/engines/sludge/sound.h
index 1c5af96..ee1321a 100644
--- a/engines/sludge/sound.h
+++ b/engines/sludge/sound.h
@@ -29,10 +29,10 @@
 #define HWND void *
 #endif
 
-#include "variable.h"
-
 #include "common/file.h"
 
+#include "sludge/variable.h"
+
 namespace Sludge {
 
 // Sound list stuff
diff --git a/engines/sludge/sound_bass.cpp b/engines/sludge/sound_bass.cpp
index b285b96..a7e2ec7 100644
--- a/engines/sludge/sound_bass.cpp
+++ b/engines/sludge/sound_bass.cpp
@@ -19,12 +19,12 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-#include "newfatal.h"
-#include "bass.h"
-#include "sound.h"
-#include "moreio.h"
-#include "fileset.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/newfatal.h"
+#include "sludge/sound.h"
+#include "sludge/moreio.h"
+#include "sludge/fileset.h"
 
 #define MAX_SAMPLES 8
 #define MAX_MODS 3
diff --git a/engines/sludge/sound_nosound.cpp b/engines/sludge/sound_nosound.cpp
index 2c347e6..9e34ff4 100644
--- a/engines/sludge/sound_nosound.cpp
+++ b/engines/sludge/sound_nosound.cpp
@@ -19,11 +19,12 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-#include "newfatal.h"
-#include "sound.h"
-#include "moreio.h"
-#include "fileset.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/newfatal.h"
+#include "sludge/sound.h"
+#include "sludge/moreio.h"
+#include "sludge/fileset.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/sound_openal.cpp b/engines/sludge/sound_openal.cpp
index e180bf8..ea64acc 100644
--- a/engines/sludge/sound_openal.cpp
+++ b/engines/sludge/sound_openal.cpp
@@ -26,15 +26,15 @@
 #include "AL/alure.h"
 #endif
 
-#include "allfiles.h"
-#include "debug.h"
-#include "newfatal.h"
-#include "sound.h"
-#include "moreio.h"
-#include "fileset.h"
-
 #include "common/file.h"
 
+#include "sludge/allfiles.h"
+#include "sludge/debug.h"
+#include "sludge/newfatal.h"
+#include "sludge/sound.h"
+#include "sludge/moreio.h"
+#include "sludge/fileset.h"
+
 #define MAX_SAMPLES 8
 #define MAX_MODS 3
 #define NUM_BUFS 3
diff --git a/engines/sludge/sprbanks.cpp b/engines/sludge/sprbanks.cpp
index 1ae7774..bc2d084 100644
--- a/engines/sludge/sprbanks.cpp
+++ b/engines/sludge/sprbanks.cpp
@@ -19,11 +19,12 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-#include "sprites.h"
-#include "sprbanks.h"
-#include "newfatal.h"
-#include "debug.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/sprites.h"
+#include "sludge/sprbanks.h"
+#include "sludge/newfatal.h"
+#include "sludge/debug.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/sprbanks.h b/engines/sludge/sprbanks.h
index 81d1bc7..ed60be5 100644
--- a/engines/sludge/sprbanks.h
+++ b/engines/sludge/sprbanks.h
@@ -22,7 +22,7 @@
 #ifndef SLUDGE_SPRBANKS_H
 #define SLUDGE_SPRBANKS_H
 
-#include "sprites.h"
+#include "sludge/sprites.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index 0927644..1dc6619 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -22,20 +22,21 @@
 
 #include "graphics/surface.h"
 #include "graphics/transparent_surface.h"
-#include "allfiles.h"
-#include "fileset.h"
-#include "people.h"
-#include "sprites.h"
-#include "moreio.h"
-#include "newfatal.h"
-#include "colours.h"
-#include "backdrop.h"
-#include "sludger.h"
-#include "zbuffer.h"
-#include "debug.h"
-#include "graphics.h"
-#include "imgloader.h"
-#include "shaders.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/fileset.h"
+#include "sludge/people.h"
+#include "sludge/sprites.h"
+#include "sludge/moreio.h"
+#include "sludge/newfatal.h"
+#include "sludge/colours.h"
+#include "sludge/backdrop.h"
+#include "sludge/sludger.h"
+#include "sludge/zbuffer.h"
+#include "sludge/debug.h"
+#include "sludge/graphics.h"
+#include "sludge/imgloader.h"
+#include "sludge/shaders.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/statusba.cpp b/engines/sludge/statusba.cpp
index 52aeb5d..4bf665b 100644
--- a/engines/sludge/statusba.cpp
+++ b/engines/sludge/statusba.cpp
@@ -19,18 +19,19 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-
-#include "backdrop.h"
-#include "colours.h"
-#include "sprites.h"
-#include "fonttext.h"
-#include "moreio.h"
-#include "stringy.h"
-#include "newfatal.h"
-#include "statusba.h"
+
 #include "common/file.h"
 
+#include "sludge/allfiles.h"
+#include "sludge/backdrop.h"
+#include "sludge/colours.h"
+#include "sludge/sprites.h"
+#include "sludge/fonttext.h"
+#include "sludge/moreio.h"
+#include "sludge/stringy.h"
+#include "sludge/newfatal.h"
+#include "sludge/statusba.h"
+
 namespace Sludge {
 
 spritePalette verbLinePalette;
diff --git a/engines/sludge/stringy.cpp b/engines/sludge/stringy.cpp
index 5446f57..484f014 100644
--- a/engines/sludge/stringy.cpp
+++ b/engines/sludge/stringy.cpp
@@ -19,8 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-#include "newfatal.h"
+#include "sludge/allfiles.h"
+#include "sludge/newfatal.h"
 
 #ifndef SLUDGE_STRINGY_H
 #define SLUDGE_STRINGY_H
diff --git a/engines/sludge/talk.cpp b/engines/sludge/talk.cpp
index 86e2174..59f71aa 100644
--- a/engines/sludge/talk.cpp
+++ b/engines/sludge/talk.cpp
@@ -19,20 +19,21 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-#include "backdrop.h"
-#include "sprites.h"
-#include "sludger.h"
-#include "objtypes.h"
-#include "region.h"
-#include "sprbanks.h"
-#include "people.h"
-#include "talk.h"
-#include "sound.h"
-#include "fonttext.h"
-#include "newfatal.h"
-#include "stringy.h"
-#include "moreio.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/backdrop.h"
+#include "sludge/sprites.h"
+#include "sludge/sludger.h"
+#include "sludge/objtypes.h"
+#include "sludge/region.h"
+#include "sludge/sprbanks.h"
+#include "sludge/people.h"
+#include "sludge/talk.h"
+#include "sludge/sound.h"
+#include "sludge/fonttext.h"
+#include "sludge/newfatal.h"
+#include "sludge/stringy.h"
+#include "sludge/moreio.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/talk.h b/engines/sludge/talk.h
index 39da742..4f344fb 100644
--- a/engines/sludge/talk.h
+++ b/engines/sludge/talk.h
@@ -22,7 +22,7 @@
 #ifndef SLUDGE_TALK_H
 #define SLUDGE_TALK_H
 
-#include "sprites.h"
+#include "sludge/sprites.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/thumbnail.cpp b/engines/sludge/thumbnail.cpp
index 63c7544..c163452 100644
--- a/engines/sludge/thumbnail.cpp
+++ b/engines/sludge/thumbnail.cpp
@@ -19,15 +19,16 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-#include "errors.h"
-#include "moreio.h"
-#include "CommonCode/version.h"
-#include "sludger.h"
-#include "colours.h"
-#include "backdrop.h"
-#include "graphics.h"
-#include "newfatal.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/errors.h"
+#include "sludge/moreio.h"
+#include "sludge/sludger.h"
+#include "sludge/colours.h"
+#include "sludge/backdrop.h"
+#include "sludge/graphics.h"
+#include "sludge/newfatal.h"
+#include "sludge/CommonCode/version.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/transition.cpp b/engines/sludge/transition.cpp
index 100cc9c..373475b 100644
--- a/engines/sludge/transition.cpp
+++ b/engines/sludge/transition.cpp
@@ -19,12 +19,14 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
+
 #include <stdint.h>
-#include "allfiles.h"
-#include "colours.h"
-#include "backdrop.h"
-#include "graphics.h"
-#include "newfatal.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/colours.h"
+#include "sludge/backdrop.h"
+#include "sludge/graphics.h"
+#include "sludge/newfatal.h"
 
 #if 0
 extern GLuint snapshotTextureName;
diff --git a/engines/sludge/variable.cpp b/engines/sludge/variable.cpp
index 96473cc..00df66c 100644
--- a/engines/sludge/variable.cpp
+++ b/engines/sludge/variable.cpp
@@ -19,21 +19,22 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "debug.h"
 
-#include "allfiles.h"
-#include "variable.h"
-#include "newfatal.h"
-#include "stringy.h"
-#include "objtypes.h"
-#include "people.h"
-#include "fileset.h"
+#include <dirent.h>
 
-#include "sludge.h"
 #include "common/debug.h"
 
-#include <dirent.h>
-#include "moreio.h"
+#include "sludge/debug.h"
+#include "sludge/allfiles.h"
+#include "sludge/variable.h"
+#include "sludge/moreio.h"
+#include "sludge/newfatal.h"
+#include "sludge/stringy.h"
+#include "sludge/objtypes.h"
+#include "sludge/people.h"
+#include "sludge/fileset.h"
+#include "sludge/sludge.h"
+
 #ifdef _WIN32
 #include "windows.h"
 
diff --git a/engines/sludge/vid.cpp b/engines/sludge/vid.cpp
index 0aab819..519b4ca 100644
--- a/engines/sludge/vid.cpp
+++ b/engines/sludge/vid.cpp
@@ -19,23 +19,21 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
 
 #ifndef _MSC_VER        // Microsoft compiler?
 #include <unistd.h>     // For unlink
 #else
 #include <io.h>
 #include <stdio.h>
-#endif
-
-#include "newfatal.h"
-#include "stringy.h"
-#if 0
 #include "vfw.h"
 #endif
-#include "sound.h"
-#include "colours.h"
-#include "fileset.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/newfatal.h"
+#include "sludge/stringy.h"
+#include "sludge/sound.h"
+#include "sludge/colours.h"
+#include "sludge/fileset.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/zbuffer.cpp b/engines/sludge/zbuffer.cpp
index 865a62e..a4641ca 100644
--- a/engines/sludge/zbuffer.cpp
+++ b/engines/sludge/zbuffer.cpp
@@ -19,12 +19,13 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include "allfiles.h"
-#include "zbuffer.h"
-#include "fileset.h"
-#include "moreio.h"
-#include "newfatal.h"
-#include "graphics.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/zbuffer.h"
+#include "sludge/fileset.h"
+#include "sludge/moreio.h"
+#include "sludge/newfatal.h"
+#include "sludge/graphics.h"
 
 namespace Sludge {
 


Commit: 7430ebe8830f58ae8fd1c123bfd7b08031a0f8b1
    https://github.com/scummvm/scummvm/commit/7430ebe8830f58ae8fd1c123bfd7b08031a0f8b1
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: use scummvm int type instead of uint16/32_t

Changed paths:
    engines/sludge/fonttext.cpp
    engines/sludge/linuxstuff.cpp
    engines/sludge/moreio.h
    engines/sludge/people.cpp
    engines/sludge/platform-dependent.h
    engines/sludge/savedata.cpp
    engines/sludge/sludger.h
    engines/sludge/sound_bass.cpp
    engines/sludge/sound_nosound.cpp
    engines/sludge/sound_openal.cpp
    engines/sludge/thumbnail.cpp
    engines/sludge/transition.cpp
    engines/sludge/variable.cpp
    engines/sludge/vid.cpp
    engines/sludge/winstuff.cpp
    engines/sludge/zbuffer.cpp


diff --git a/engines/sludge/fonttext.cpp b/engines/sludge/fonttext.cpp
index bf7de8b..f66cde5 100644
--- a/engines/sludge/fonttext.cpp
+++ b/engines/sludge/fonttext.cpp
@@ -38,10 +38,10 @@ int fontHeight = 0, numFontColours, loadedFontNum;
 char *fontOrderString = NULL;
 short fontSpace = -1;
 
-uint32_t *fontTable = NULL;
+uint32 *fontTable = NULL;
 unsigned int fontTableSize = 0;
 
-#define fontInTable(x) ((x<fontTableSize) ? fontTable[(uint32_t) x] : 0)
+#define fontInTable(x) ((x<fontTableSize) ? fontTable[(uint32) x] : 0)
 
 extern float cameraZoom;
 
@@ -56,7 +56,7 @@ bool isInFont(char *theText) {
 		return false;
 
 	int i = 0;
-	uint32_t c = u8_nextchar(theText, &i);
+	uint32 c = u8_nextchar(theText, &i);
 
 	return u8_strchr(fontOrderString, c, &i);
 }
@@ -67,7 +67,7 @@ int stringLength(char *theText) {
 
 int stringWidth(char *theText) {
 	int a = 0;
-	uint32_t c;
+	uint32 c;
 	int xOff = 0;
 
 	if (!fontTableSize)
@@ -84,7 +84,7 @@ int stringWidth(char *theText) {
 void pasteString(char *theText, int xOff, int y, spritePalette &thePal) {
 	sprite *mySprite;
 	int a = 0;
-	uint32_t c;
+	uint32 c;
 
 	if (!fontTableSize)
 		return;
@@ -101,7 +101,7 @@ void pasteString(char *theText, int xOff, int y, spritePalette &thePal) {
 void pasteStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal) {
 	sprite *mySprite;
 	int a = 0;
-	uint32_t c;
+	uint32 c;
 
 	if (!fontTableSize)
 		return;
@@ -118,7 +118,7 @@ void pasteStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal
 void burnStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal) {
 	sprite *mySprite;
 	int a = 0;
-	uint32_t c;
+	uint32 c;
 
 	if (!fontTableSize)
 		return;
@@ -167,7 +167,7 @@ void setFontColour(spritePalette &sP, byte r, byte g, byte b) {
 
 bool loadFont(int filenum, const char *charOrder, int h) {
 	int a = 0;
-	uint32_t c;
+	uint32 c;
 
 	delete[] fontOrderString;
 	fontOrderString = copyString(charOrder);
@@ -185,7 +185,7 @@ bool loadFont(int filenum, const char *charOrder, int h) {
 	fontTableSize++;
 
 	delete[] fontTable;
-	fontTable = new uint32_t[fontTableSize];
+	fontTable = new uint32[fontTableSize];
 	if (!checkNew(fontTable))
 		return false;
 
diff --git a/engines/sludge/linuxstuff.cpp b/engines/sludge/linuxstuff.cpp
index 454cf93..84f3bc0 100644
--- a/engines/sludge/linuxstuff.cpp
+++ b/engines/sludge/linuxstuff.cpp
@@ -185,7 +185,7 @@ void changeToUserDir() {
 	}
 }
 
-uint32_t launch(char *filename) {
+uint32 launch(char *filename) {
 	debugOut("Trying to launch: %s\n", filename);
 
 	if (!fileExists("/usr/bin/xdg-open")) {
diff --git a/engines/sludge/moreio.h b/engines/sludge/moreio.h
index 1e2f314..7ca59ec 100644
--- a/engines/sludge/moreio.h
+++ b/engines/sludge/moreio.h
@@ -22,8 +22,6 @@
 #ifndef SLUDGE_MOREIO_H
 #define SLUDGE_MOREIO_H
 
-#include <stdint.h>
-
 namespace Sludge {
 
 // Read
diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index ebbf762..98b913c 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -20,8 +20,6 @@
  *
  */
 
-#include <stdlib.h>
-
 #include "sludge/allfiles.h"
 #include "sludge/sprites.h"
 #include "sludge/sprbanks.h"
diff --git a/engines/sludge/platform-dependent.h b/engines/sludge/platform-dependent.h
index 5754ef5..0296bc1 100644
--- a/engines/sludge/platform-dependent.h
+++ b/engines/sludge/platform-dependent.h
@@ -24,7 +24,6 @@
 /* These are the functions which have different versions for
  * the different operating systems.
  */
-#include <stdint.h>
 
 namespace Sludge {
 
@@ -35,7 +34,7 @@ void msgBox(const char *head, const char *msg);
 int msgBoxQuestion(const char *head, const char *msg);
 
 void changeToUserDir();
-uint32_t launch(char *filename);
+uint32 launch(char *filename);
 
 bool defaultUserFullScreen();
 
diff --git a/engines/sludge/savedata.cpp b/engines/sludge/savedata.cpp
index f79e7fb..d1e3fa5 100644
--- a/engines/sludge/savedata.cpp
+++ b/engines/sludge/savedata.cpp
@@ -19,8 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include <stdint.h>
-#include <unistd.h>
 
 #include "common/file.h"
 
diff --git a/engines/sludge/sludger.h b/engines/sludge/sludger.h
index 591bd13..be49276 100644
--- a/engines/sludge/sludger.h
+++ b/engines/sludge/sludger.h
@@ -22,8 +22,6 @@
 #ifndef SLUDGER_H
 #define SLUDGER_H
 
-#include <stdint.h>
-
 #include "common/file.h"
 
 #include "sludge/allfiles.h"
@@ -35,8 +33,8 @@ namespace Sludge {
 
 #ifndef _WIN32
 typedef struct _FILETIME {
-	uint32_t dwLowDateTime;
-	uint32_t dwHighDateTime;
+	uint32 dwLowDateTime;
+	uint32 dwHighDateTime;
 } FILETIME;
 #endif
 
diff --git a/engines/sludge/sound_bass.cpp b/engines/sludge/sound_bass.cpp
index a7e2ec7..d85981e 100644
--- a/engines/sludge/sound_bass.cpp
+++ b/engines/sludge/sound_bass.cpp
@@ -49,7 +49,7 @@ soundThing soundCache[MAX_SAMPLES];
 int defVol = 128;
 int defSoundVol = 255;
 
-char *loadEntireFileToMemory(Common::SeekableReadStream *inputFile, uint32_t size) {
+char *loadEntireFileToMemory(Common::SeekableReadStream *inputFile, uint32 size) {
 	char *allData = new char[size];
 	if (!allData)
 		return NULL;
@@ -137,7 +137,7 @@ bool playMOD(int f, int a, int fromTrack) {
 		stopMOD(a);
 
 		setResourceForFatal(f);
-		uint32_t length = openFileFromNum(f);
+		uint32 length = openFileFromNum(f);
 		if (length == 0)
 			return NULL;
 
@@ -287,7 +287,7 @@ int cacheSound(int f) {
 	a = findEmptySoundSlot();
 	freeSound(a);
 
-	uint32_t length = openFileFromNum(f);
+	uint32 length = openFileFromNum(f);
 	if (!length)
 		return -1;
 
diff --git a/engines/sludge/sound_nosound.cpp b/engines/sludge/sound_nosound.cpp
index 9e34ff4..46b6963 100644
--- a/engines/sludge/sound_nosound.cpp
+++ b/engines/sludge/sound_nosound.cpp
@@ -34,7 +34,7 @@ int defVol = 128;
 int defSoundVol = 255;
 
 #if 0
-char *loadEntireFileToMemory(FILE *inputFile, uint32_t size) {
+char *loadEntireFileToMemory(FILE *inputFile, uint32 size) {
 	char *allData = new char[size];
 	if (! allData) return NULL;
 	fread(allData, size, 1, inputFile);
diff --git a/engines/sludge/sound_openal.cpp b/engines/sludge/sound_openal.cpp
index ea64acc..c728151 100644
--- a/engines/sludge/sound_openal.cpp
+++ b/engines/sludge/sound_openal.cpp
@@ -19,8 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include <stdint.h>
-#include <stdio.h>
 
 #if 0
 #include "AL/alure.h"
@@ -369,7 +367,7 @@ void playStream(int a, bool isMOD, bool loopy) {
 }
 
 char *loadEntireFileToMemory(Common::SeekableReadStream *inputFile,
-		uint32_t size) {
+		uint32 size) {
 	char *allData = new char[size];
 	if (!allData)
 		return NULL;
@@ -390,7 +388,7 @@ bool playMOD(int f, int a, int fromTrack) {
 	stopMOD(a);
 
 	setResourceForFatal(f);
-	uint32_t length = openFileFromNum(f);
+	uint32 length = openFileFromNum(f);
 	if (length == 0) {
 		finishAccess();
 		setResourceForFatal(-1);
@@ -532,7 +530,7 @@ int cacheSound(int f) {
 	a = findEmptySoundSlot();
 	freeSound(a);
 
-	uint32_t length = openFileFromNum(f);
+	uint32 length = openFileFromNum(f);
 	if (! length) return -1;
 
 	unsigned char *memImage;
diff --git a/engines/sludge/thumbnail.cpp b/engines/sludge/thumbnail.cpp
index c163452..df0076c 100644
--- a/engines/sludge/thumbnail.cpp
+++ b/engines/sludge/thumbnail.cpp
@@ -255,7 +255,7 @@ void showThumbnail(char *filename, int atX, int atY) {
 bool skipThumbnail(Common::SeekableReadStream *stream) {
 	thumbWidth = stream->readUint32LE();
 	thumbHeight = stream->readUint32LE();
-	uint32_t skippy = thumbWidth;
+	uint32 skippy = thumbWidth;
 	skippy *= thumbHeight << 1;
 	stream->seek(skippy, 1);
 	return (stream->readByte() == '!');
diff --git a/engines/sludge/transition.cpp b/engines/sludge/transition.cpp
index 373475b..05257d8 100644
--- a/engines/sludge/transition.cpp
+++ b/engines/sludge/transition.cpp
@@ -20,8 +20,6 @@
  *
  */
 
-#include <stdint.h>
-
 #include "sludge/allfiles.h"
 #include "sludge/colours.h"
 #include "sludge/backdrop.h"
@@ -147,7 +145,7 @@ void transitionSnapshotBox() {
 //----------------------------------------------------
 
 #define KK 17
-uint32_t randbuffer[KK][2];  // history buffer
+uint32 randbuffer[KK][2];  // history buffer
 int p1, p2;
 
 void resetRandW() {
@@ -199,8 +197,8 @@ void transitionDisolve() {
 		return;
 	}
 
-	uint32_t n;
-	uint32_t y;
+	uint32 n;
+	uint32 y;
 
 	GLubyte *toScreen = transitionTexture;
 	GLubyte *end = transitionTexture + (256 * 256 * 4);
@@ -267,8 +265,8 @@ void transitionTV() {
 #if 0
 	if (! transitionTextureName) reserveTransitionTexture();
 
-	uint32_t n;
-	uint32_t y;
+	uint32 n;
+	uint32 y;
 
 	GLubyte *toScreen = transitionTexture;
 	GLubyte *end = transitionTexture + (256 * 256 * 4);
diff --git a/engines/sludge/variable.cpp b/engines/sludge/variable.cpp
index 00df66c..949060c 100644
--- a/engines/sludge/variable.cpp
+++ b/engines/sludge/variable.cpp
@@ -20,8 +20,6 @@
  *
  */
 
-#include <dirent.h>
-
 #include "common/debug.h"
 
 #include "sludge/debug.h"
@@ -164,7 +162,7 @@ bool getSavedGamesStack(stackHandler *sH, char *ext) {
 
 	variable newName;
 	newName.varType = SVT_NULL;
-
+#if 0
 #ifdef _WIN32
 
 	WCHAR *w_pattern = ConvertToUTF16(pattern);
@@ -215,7 +213,7 @@ bool getSavedGamesStack(stackHandler *sH, char *ext) {
 	closedir(dir);
 
 #endif
-
+#endif
 	delete[] pattern;
 	pattern = NULL;
 	return true;
diff --git a/engines/sludge/vid.cpp b/engines/sludge/vid.cpp
index 519b4ca..d0c51d1 100644
--- a/engines/sludge/vid.cpp
+++ b/engines/sludge/vid.cpp
@@ -21,7 +21,6 @@
  */
 
 #ifndef _MSC_VER        // Microsoft compiler?
-#include <unistd.h>     // For unlink
 #else
 #include <io.h>
 #include <stdio.h>
diff --git a/engines/sludge/winstuff.cpp b/engines/sludge/winstuff.cpp
index a229225..dfe0a5a 100644
--- a/engines/sludge/winstuff.cpp
+++ b/engines/sludge/winstuff.cpp
@@ -215,9 +215,9 @@ namespace Sludge {
 		_wchdir(szAppData);
 	}
 
-	uint32_t launch(char *f) {
+	uint32 launch(char *f) {
 		WCHAR *w_f = ConvertToUTF16(f);
-		uint32_t r = (uint32_t) ShellExecute(hMainWindow, TEXT("open"), w_f, NULL, TEXT("C:\\"), SW_SHOWNORMAL);
+		uint32 r = (uint32) ShellExecute(hMainWindow, TEXT("open"), w_f, NULL, TEXT("C:\\"), SW_SHOWNORMAL);
 		delete w_f;
 		return r;
 	}
diff --git a/engines/sludge/zbuffer.cpp b/engines/sludge/zbuffer.cpp
index a4641ca..4f42c98 100644
--- a/engines/sludge/zbuffer.cpp
+++ b/engines/sludge/zbuffer.cpp
@@ -68,7 +68,7 @@ void sortZPal(int *oldpal, int *newpal, int size) {
 bool setZBuffer(int y) {
 #if 0
 	int x, n;
-	uint32_t stillToGo = 0;
+	uint32 stillToGo = 0;
 	int yPalette[16], sorted[16], sortback[16];
 
 	killZBuffer();


Commit: bee42dc52fb7fa2d73f95cf088fc26ced732a17c
    https://github.com/scummvm/scummvm/commit/bee42dc52fb7fa2d73f95cf088fc26ced732a17c
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove platform dependent defines

Changed paths:
  R engines/sludge/linuxstuff.cpp
  R engines/sludge/linuxstuff.h
  R engines/sludge/winstuff.cpp
  R engines/sludge/winstuff.h
    engines/sludge/builtin.cpp
    engines/sludge/cursors.cpp
    engines/sludge/debug.cpp
    engines/sludge/fileset.cpp
    engines/sludge/floor.h
    engines/sludge/graphics.cpp
    engines/sludge/graphics.h
    engines/sludge/language.cpp
    engines/sludge/libwebm/mkvreader.cpp
    engines/sludge/libwebm/mkvreader.hpp
    engines/sludge/line.cpp
    engines/sludge/main_loop.cpp
    engines/sludge/module.mk
    engines/sludge/moreio.cpp
    engines/sludge/newfatal.cpp
    engines/sludge/people.h
    engines/sludge/shaders.h
    engines/sludge/sludger.cpp
    engines/sludge/sludger.h
    engines/sludge/sound.h
    engines/sludge/talk.cpp
    engines/sludge/timing.cpp
    engines/sludge/variable.cpp
    engines/sludge/zbuffer.h


diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 9733689..873b523 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -20,10 +20,6 @@
  *
  */
 
-#if 0
-#include <SDL/SDL.h>
-#endif
-
 #include "sludge/debug.h"
 #include "sludge/allfiles.h"
 #include "sludge/sludger.h"
@@ -995,11 +991,7 @@ builtIn(launch) {
 		launchMe = copyString(newTextA);
 	} else {
 		char *gameDir;
-#ifdef _WIN32
-		gameDir = joinStrings(gamePath, "\\");
-#else
 		gameDir = joinStrings(gamePath, "/");
-#endif
 		launchMe = joinStrings(gameDir, newText);
 		delete newText;
 		if (!launchMe)
diff --git a/engines/sludge/cursors.cpp b/engines/sludge/cursors.cpp
index 4720677..abe09c8 100644
--- a/engines/sludge/cursors.cpp
+++ b/engines/sludge/cursors.cpp
@@ -20,14 +20,6 @@
  *
  */
 
-#if 0
-#if !defined(HAVE_GLES2)
-#include "GLee.h"
-#else
-#include <GLES2/gl2.h>
-#endif
-#endif
-
 #include "sludge/allfiles.h"
 #include "sludge/cursors.h"
 #include "sludge/colours.h"
diff --git a/engines/sludge/debug.cpp b/engines/sludge/debug.cpp
index e79571a..cbeb996 100644
--- a/engines/sludge/debug.cpp
+++ b/engines/sludge/debug.cpp
@@ -20,10 +20,6 @@
  *
  */
 
-#if 0
-#include <stdarg.h>
-#endif
-
 #include "sludge/allfiles.h"
 #include "sludge/debug.h"
 #include "sludge/language.h"
diff --git a/engines/sludge/fileset.cpp b/engines/sludge/fileset.cpp
index 2c4216d..0a68f7a 100644
--- a/engines/sludge/fileset.cpp
+++ b/engines/sludge/fileset.cpp
@@ -19,13 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#if 0
-#include <errno.h>
-#include <stdint.h>
-#include <string.h>
-// For unicode conversion
-#include <iconv.h>
-#endif
 
 #include "common/file.h"
 #include "common/debug.h"
@@ -44,7 +37,7 @@ bool sliceBusy = true;
 
 Common::File *bigDataFile = NULL;
 
-uint32_t startOfDataIndex, startOfTextIndex, startOfSubIndex, startOfObjectIndex;
+uint32 startOfDataIndex, startOfTextIndex, startOfSubIndex, startOfObjectIndex;
 
 bool openSubSlice(int num) {
 //	FILE * dbug = fopen ("debuggy.txt", "at");
diff --git a/engines/sludge/floor.h b/engines/sludge/floor.h
index 193b6d1..1b212fa 100644
--- a/engines/sludge/floor.h
+++ b/engines/sludge/floor.h
@@ -22,10 +22,6 @@
 #ifndef SLUDGE_FLOOR_H
 #define SLUDGE_FLOOR_H
 
-#ifdef _WIN32
-#include "windef.h"
-#endif
-
 namespace Sludge {
 
 struct floorPolygon {
@@ -33,12 +29,10 @@ struct floorPolygon {
 	int *vertexID;
 };
 
-#ifndef _WIN32
 struct POINT {
 	int x;
 	int y;
 };
-#endif
 
 struct flor {
 	int originalNum;
diff --git a/engines/sludge/graphics.cpp b/engines/sludge/graphics.cpp
index e48ad8c..29cc47f 100644
--- a/engines/sludge/graphics.cpp
+++ b/engines/sludge/graphics.cpp
@@ -19,21 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#if 0
-#include <stdarg.h>
-
-#include <SDL/SDL.h>
-
-#if !defined(HAVE_GLES2)
-#ifdef _WIN32
-#include <GL\glu.h> // handy for gluErrorString
-#elif defined __APPLE__
-#include <OpenGL/glu.h>
-#else
-#include <GL/glu.h>
-#endif
-#endif
-#endif
 
 #include "sludge/allfiles.h"
 #include "sludge/debug.h"
@@ -364,62 +349,6 @@ void saveTexture(GLuint tex, GLubyte *data) {
 	glViewport(old_vp[0], old_vp[1], old_vp[2], old_vp[3]);
 	glBindFramebuffer(GL_FRAMEBUFFER, old_fbo);
 }
-#elif defined _WIN32
-// Replacement for glGetTexImage, because some ATI drivers are buggy.
-void saveTexture(GLuint tex, GLubyte *data) {
-	setPixelCoords(true);
-
-	glBindTexture(GL_TEXTURE_2D, tex);
-
-	GLint tw, th;
-	getTextureDimensions(tex, &tw, &th);
-
-	//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
-
-	int xoffset = 0;
-	while (xoffset < tw) {
-		int w = (tw - xoffset < viewportWidth) ? tw - xoffset : viewportWidth;
-
-		int yoffset = 0;
-		while (yoffset < th) {
-			int h = (th - yoffset < viewportHeight) ? th - yoffset : viewportHeight;
-
-			glClear(GL_COLOR_BUFFER_BIT);   // Clear The Screen
-
-			const GLfloat vertices[] = {
-				(GLfloat) - xoffset, (GLfloat) - yoffset, 0.f,
-				(GLfloat)tw - xoffset, (GLfloat) - yoffset, 0.f,
-				(GLfloat) - xoffset, (GLfloat) - yoffset + th, 0.f,
-				(GLfloat)tw - xoffset, (GLfloat) - yoffset + th, 0.f
-			};
-
-			const GLfloat texCoords[] = {
-				0.0f, 0.0f,
-				1.0f, 0.0f,
-				0.0f, 1.0f,
-				1.0f, 1.0f
-			};
-
-			glUseProgram(shader.texture);
-			setPMVMatrix(shader.texture);
-
-			drawQuad(shader.texture, vertices, 1, texCoords);
-			glUseProgram(0);
-
-			for (int i = 0; i < h; i++) {
-				glReadPixels(viewportOffsetX, viewportOffsetY + i, w, 1, GL_RGBA, GL_UNSIGNED_BYTE, data + xoffset * 4 + (yoffset + i) * 4 * tw);
-			}
-
-			yoffset += viewportHeight;
-		}
-
-		xoffset += viewportWidth;
-	}
-	//glReadPixels(viewportOffsetX, viewportOffsetY, tw, th, GL_RGBA, GL_UNSIGNED_BYTE, data);
-
-	setPixelCoords(false);
-
-}
 #else
 #if 0
 void saveTexture(GLuint tex, GLubyte *data) {
diff --git a/engines/sludge/graphics.h b/engines/sludge/graphics.h
index 5d2bb9a..b6d82ab 100644
--- a/engines/sludge/graphics.h
+++ b/engines/sludge/graphics.h
@@ -22,15 +22,6 @@
 #ifndef SLUDGE_GRAPHICS_H
 #define SLUDGE_GRAPHICS_H
 
-#if 0
-#if !defined(HAVE_GLES2)
-#include "GLee.h"
-#else
-#include <GLES2/gl2.h>
-#include "eglport/eglport.h"
-#endif
-#endif
-
 #include "graphics/surface.h"
 
 namespace Sludge {
diff --git a/engines/sludge/language.cpp b/engines/sludge/language.cpp
index d06dda3..1aff394 100644
--- a/engines/sludge/language.cpp
+++ b/engines/sludge/language.cpp
@@ -70,11 +70,7 @@ char *getPrefsFilename(char *filename) {
 
 	char *f = filename;
 	for (i = 0; i < n; i++) {
-#ifdef _WIN32
-		if (filename[i] == '\\')
-#else
 		if (filename[i] == '/')
-#endif
 			f = filename + i + 1;
 	}
 
diff --git a/engines/sludge/libwebm/mkvreader.cpp b/engines/sludge/libwebm/mkvreader.cpp
index 5ead487..4cae468 100644
--- a/engines/sludge/libwebm/mkvreader.cpp
+++ b/engines/sludge/libwebm/mkvreader.cpp
@@ -15,6 +15,7 @@
 #include <cassert>
 #include <stdio.h>
 
+#if 0
 MkvReader::MkvReader() :
     m_file(0)
 {
@@ -116,3 +117,4 @@ int MkvReader::Read(long long offset, long len, unsigned char* buffer)
 
     return 0;  //success
 }
+#endif
diff --git a/engines/sludge/libwebm/mkvreader.hpp b/engines/sludge/libwebm/mkvreader.hpp
index 6be9e16..b46ef78 100644
--- a/engines/sludge/libwebm/mkvreader.hpp
+++ b/engines/sludge/libwebm/mkvreader.hpp
@@ -16,6 +16,7 @@
 
 class MkvReader : public mkvparser::IMkvReader
 {
+#if 0
     MkvReader(const MkvReader&);
     MkvReader& operator=(const MkvReader&);
 public:
@@ -32,6 +33,7 @@ private:
     long long m_length;
 	unsigned int m_start;
     int m_file;
+#endif
 };
 
 #endif //MKVREADER_HPP
diff --git a/engines/sludge/line.cpp b/engines/sludge/line.cpp
index b041884..2262d92 100644
--- a/engines/sludge/line.cpp
+++ b/engines/sludge/line.cpp
@@ -19,9 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#if 0
-#include <stdlib.h>
-#endif
 
 #include "sludge/graphics.h"
 #include "sludge/allfiles.h"
diff --git a/engines/sludge/linuxstuff.cpp b/engines/sludge/linuxstuff.cpp
deleted file mode 100644
index 84f3bc0..0000000
--- a/engines/sludge/linuxstuff.cpp
+++ /dev/null
@@ -1,230 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-#if defined __unix__ && !(defined __APPLE__)
-#include <iostream>
-#include <fstream>
-#include <unistd.h>
-#include <stdlib.h>
-#include <sys/stat.h>
-#include <sys/wait.h>
-#include <getopt.h>
-
-#include "linuxstuff.h"
-#include "platform-dependent.h"
-#include "allfiles.h"
-#include "language.h" // for settings
-#include "debug.h"
-#include "helpers.h"
-
-namespace Sludge {
-
-extern settingsStruct gameSettings;
-cmdlineSettingsStruct cmdlineSettings;
-
-extern char **languageName;
-
-/*
- * Functions declared in linuxstuff.h:
- */
-
-void printCmdlineUsage() {
-	fprintf(stdout, "OpenSLUDGE engine, usage: sludge-engine [<options>] <gamefile name>\n\n");
-	fprintf(stdout, "Options:\n");
-	fprintf(stdout, "-f,		--fullscreen		Set display mode to fullscreen\n");
-	fprintf(stdout, "-w,		--window		Set display mode to windowed\n");
-	fprintf(stdout, "-L,		--list-languages	Print available languages and their indices\n");
-	fprintf(stdout, "-l<index>,	--language=<index>	Set language to <index> (look up with -L)\n");
-	fprintf(stdout, "-a<number>,	--antialias=<number>	Turn antialiasing on (1) or off (0)\n");
-	fprintf(stdout, "					or choose linear interpolation (-1)\n");
-	fprintf(stdout, "-d<number>,	--debug=<number>	Turn debug mode on (1) or off (0)\n");
-	fprintf(stdout, "-h,		--help			Print this help message\n\n");
-	fprintf(stdout, "Options are saved, so you don't need to specify them every time.\n");
-	fprintf(stdout, "If you entered a wrong language number, use -l0 to reset the language to the default setting.\n");
-	fprintf(stdout, "You can always toggle between fullscreen and windowed mode with \"Alt+Enter\"\n");
-	fprintf(stdout, "or antialiasing on and off with \"Alt+A\".\n");
-}
-
-void printLanguageTable() {
-	if (gameSettings.numLanguages) {
-		fprintf(stdout, "Index		Language\n");
-		for (unsigned int i = 0; i <= gameSettings.numLanguages; i++) {
-			if (languageName[i]) {
-				fprintf(stdout, "%d		%s\n", i, languageName[i]);
-			} else {
-				fprintf(stdout, "%d		Language %d\n", i, i);
-			}
-		}
-	} else {
-		fprintf(stdout, "No translations available.\n");
-	}
-}
-
-bool parseCmdlineParameters(int argc, char *argv[]) {
-	int retval = true;
-	cmdlineSettings.fullscreenSet = false;
-	cmdlineSettings.languageSet = false;
-	cmdlineSettings.aaSet = false;
-	cmdlineSettings.debugModeSet = false;
-	cmdlineSettings.listLanguages = false;
-	while (1) {
-		static struct option long_options[] = {
-			{"fullscreen",      no_argument,       0, 'f' },
-			{"window",      no_argument,       0, 'w' },
-			{"list-languages",  no_argument,       0, 'L' },
-			{"language",        required_argument, 0, 'l' },
-			{"antialias",       required_argument, 0, 'a' },
-			{"debug",       required_argument, 0, 'd' },
-			{"help",        no_argument,       0, 'h' },
-			{0, 0, 0, 0} /* This is a filler for -1 */
-		};
-		int option_index = 0;
-		int c = getopt_long(argc, argv, "fwLl:a:d:h", long_options, &option_index);
-		if (c == -1) break;
-		switch (c) {
-		case 'f':
-			cmdlineSettings.fullscreenSet = true;
-			cmdlineSettings.userFullScreen = true;
-			break;
-		case 'w':
-			cmdlineSettings.fullscreenSet = true;
-			cmdlineSettings.userFullScreen = false;
-			break;
-		case 'L':
-			cmdlineSettings.listLanguages = true;
-			break;
-		case 'l':
-			cmdlineSettings.languageSet = true;
-			cmdlineSettings.languageID = atoi(optarg);
-			break;
-		case 'a':
-			cmdlineSettings.aaSet = true;
-			cmdlineSettings.antiAlias = atoi(optarg);
-			break;
-		case 'd':
-			cmdlineSettings.debugModeSet = true;
-			cmdlineSettings.debugMode = atoi(optarg);
-			break;
-		case 'h':
-		default:
-			retval = false;
-			break;
-		}
-	}
-	return retval;
-}
-
-/*
- * Functions declared in platform-dependent.h:
- */
-
-char *grabFileName() {
-	return NULL;
-}
-
-int showSetupWindow() {
-	if (cmdlineSettings.listLanguages) {
-		printLanguageTable();
-		return 0;
-	}
-	if (cmdlineSettings.languageSet) {
-		if (cmdlineSettings.languageID <= gameSettings.numLanguages) {
-			gameSettings.languageID = cmdlineSettings.languageID;
-		} else {
-			fprintf(stdout, "Language index %d doesn't exist. Please specify an index between 0 and %d.\n\n",
-			        cmdlineSettings.languageID, gameSettings.numLanguages);
-			printLanguageTable();
-			return 0;
-		}
-	}
-	if (cmdlineSettings.fullscreenSet) {
-		gameSettings.userFullScreen = cmdlineSettings.userFullScreen;
-	}
-	if (cmdlineSettings.aaSet) {
-		gameSettings.antiAlias = cmdlineSettings.antiAlias;
-	}
-	if (cmdlineSettings.debugModeSet) {
-		gameSettings.debugMode = cmdlineSettings.debugMode;
-	}
-	return 1;
-}
-
-void msgBox(const char *head, const char *msg) {
-	fprintf(stderr, "%s\n%s\n", head, msg);
-}
-
-int msgBoxQuestion(const char *head, const char *msg) {
-	return 1;
-}
-
-void changeToUserDir() {
-	if (chdir(getenv("HOME"))) {
-		debugOut("Error: Failed changing to directory %s\n", getenv("HOME"));
-	}
-	mkdir(".sludge-engine", 0000777);
-	if (chdir(".sludge-engine")) {
-		debugOut("Error: Failed changing to directory %s\n", ".sludge-engine");
-	}
-}
-
-uint32 launch(char *filename) {
-	debugOut("Trying to launch: %s\n", filename);
-
-	if (!fileExists("/usr/bin/xdg-open")) {
-		debugOut("Launching failed due to missing /usr/bin/xdg-open.\n");
-		return 0;
-	}
-
-	if (!(filename[0] == 'h' &&
-	        filename[1] == 't' &&
-	        filename[2] == 't' &&
-	        filename[3] == 'p' &&
-	        (filename[4] == ':' || (filename[4] == 's' && filename[5] == ':'))) &&
-	        !fileExists(filename)) {
-		return 0;
-	}
-
-	int status;
-
-	pid_t pid = fork();
-	if (pid < 0) {
-		return 0;
-	} else if (pid == 0) {
-		execl("/usr/bin/xdg-open", "xdg-open", filename, (char *)0);
-		exit(EXIT_FAILURE);
-	} else {
-		waitpid(pid, &status, 0);
-	}
-
-	if (status == EXIT_SUCCESS) {
-		return 69;
-	} else {
-		return 0;
-	}
-}
-
-bool defaultUserFullScreen() {
-	return false;
-}
-
-} // End of namespace Sludge
-
-#endif
diff --git a/engines/sludge/linuxstuff.h b/engines/sludge/linuxstuff.h
deleted file mode 100644
index b97c7bf..0000000
--- a/engines/sludge/linuxstuff.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-#ifndef SLUDGE_LINUXSTUFF_H
-#define SLUDGE_LINUXSTUFF_H
-
-namespace Sludge {
-
-struct cmdlineSettingsStruct {
-	bool languageSet;
-	unsigned int languageID;
-	bool fullscreenSet;
-	bool userFullScreen;
-	bool aaSet;
-	int antiAlias;
-	bool debugModeSet;
-	bool debugMode;
-	bool listLanguages;
-};
-
-void printCmdlineUsage();
-bool parseCmdlineParameters(int argc, char *argv[]);
-
-} // End of namespace Sludge
-
-#endif
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index 143d84f..ebeedf9 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -19,38 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#if defined __unix__ && !(defined __APPLE__)
-#include "linuxstuff.h"
-#endif
-
-#if 0
-#ifdef _WIN32
-#include "winstuff.h"
-#endif
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <math.h>
-#include <unistd.h>
-
-#include <iostream>
-
-#include <stdexcept>
-
-#include <time.h>
-#include <sys/time.h>
-
-#if !defined(HAVE_GLES2)
-#include "GLee.h"
-#else
-#include <GLES2/gl2.h>
-#include "eglport/eglport.h"
-#endif
-
-#include <SDL/SDL.h>
-#include <SDL/SDL_syswm.h>
-#endif
 
 #include "common/debug.h"
 
@@ -81,12 +49,6 @@
 
 namespace Sludge {
 
-#ifdef _WIN32
-#define PATHSLASH '\\'
-#else
-#define PATHSLASH '/'
-#endif
-
 extern bool runningFullscreen;
 
 #ifndef MAX_PATH
@@ -148,10 +110,6 @@ void saveHSI(Common::WriteStream *writer);
 
 extern bool reallyWantToQuit;
 
-#ifdef _WIN32
-#undef main
-#endif
-
 int weAreDoneSoQuit;
 
 void checkInput() {
@@ -426,13 +384,6 @@ int main_loop(char *filename)
 	setupOpenGLStuff();
 #endif
 
-#ifdef _WIN32
-	SDL_SysWMinfo wmInfo;
-	SDL_VERSION(&wmInfo.version);
-	SDL_GetWMInfo(&wmInfo);
-	hMainWindow = wmInfo.window;
-#endif
-
 	registerWindowForFatal();
 
 	if (!killResizeBackdrop(winWidth, winHeight))
diff --git a/engines/sludge/module.mk b/engines/sludge/module.mk
index 726cd6b..b091361 100644
--- a/engines/sludge/module.mk
+++ b/engines/sludge/module.mk
@@ -42,10 +42,9 @@ MODULE_OBJS := \
 	variable.o \
 	zbuffer.o \
 	CommonCode/utf8.o \
-#	linuxstuff.o \
-	shaders.o \
-	libwebm/mkvparser.o \
-	libwebm/mkvreader.o \
+#	shaders.o \
+#	libwebm/mkvparser.o \
+#	libwebm/mkvreader.o \
  
 MODULE_DIRS += \
 	engines/sludge
diff --git a/engines/sludge/moreio.cpp b/engines/sludge/moreio.cpp
index 7dca5a6..f76b919 100644
--- a/engines/sludge/moreio.cpp
+++ b/engines/sludge/moreio.cpp
@@ -188,12 +188,8 @@ char *encodeFilename(char *nameIn) {
 	} else {
 		int a;
 		for (a = 0; nameIn[a]; a++) {
-#ifdef _WIN32
-			if (nameIn[a] == '/') nameIn[a] = '\\';
-#else
 			if (nameIn[a] == '\\')
 				nameIn[a] = '/';
-#endif
 		}
 
 		return copyString(nameIn);
diff --git a/engines/sludge/newfatal.cpp b/engines/sludge/newfatal.cpp
index c00476d..bc97d6a 100644
--- a/engines/sludge/newfatal.cpp
+++ b/engines/sludge/newfatal.cpp
@@ -114,6 +114,7 @@ int inFatal(const char *str) {
 	atexit(displayFatal);
 	exit(1);
 #endif
+	return true;
 }
 
 int checkNew(const void *mem) {
diff --git a/engines/sludge/people.h b/engines/sludge/people.h
index 442cb92..45ba55a 100644
--- a/engines/sludge/people.h
+++ b/engines/sludge/people.h
@@ -22,6 +22,8 @@
 #ifndef SLUDGE_PEOPLE_H
 #define SLUDGE_PEOPLE_H
 
+#include "sludge/variable.h"
+
 namespace Sludge {
 
 struct animFrame {
diff --git a/engines/sludge/shaders.h b/engines/sludge/shaders.h
index 13b6e37..fe31e19 100644
--- a/engines/sludge/shaders.h
+++ b/engines/sludge/shaders.h
@@ -22,14 +22,6 @@
 #ifndef SLUDGE_SHADERS_H
 #define SLUDGE_SHADERS_H
 
-#if 0
-#if !defined(HAVE_GLES2)
-#include "GLee.h"
-#else
-#include <GLES2/gl2.h>
-#endif
-#endif
-
 namespace Sludge {
 
 char *shaderFileRead(const char *fn);
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index 3ae7c35..0b99d79 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -19,19 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#if 0
-#if defined __unix__ && !(defined __APPLE__)
-#include <png.h>
-#else
-#include <libpng/png.h>
-#endif
-
-#include <SDL/SDL.h>
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <iconv.h>
-#endif
 
 #include "common/debug.h"
 
@@ -457,12 +444,6 @@ bool initSludge(char *filename) {
 			png_set_expand(png_ptr);
 			if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr);
 			if (bit_depth == 16) png_set_strip_16(png_ptr);
-#ifdef WIN32
-			// Windows wants a BGR bitmap
-			if (color_type == PNG_COLOR_TYPE_RGB ||
-					color_type == PNG_COLOR_TYPE_RGB_ALPHA)
-			png_set_bgr(png_ptr);
-#endif
 
 			png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER);
 
@@ -500,16 +481,9 @@ bool initSludge(char *filename) {
 						n = 1;
 					}
 					while (n --) {
-#ifdef WIN32
-						// Windows wants a BGR bitmap
-						*p++ = (Uint8) blueValue(c);
-						*p++ = (Uint8) greenValue(c);
-						*p++ = (Uint8) redValue(c);
-#else
 						*p++ = (Uint8) redValue(c);
 						*p++ = (Uint8) greenValue(c);
 						*p++ = (Uint8) blueValue(c);
-#endif
 						*p++ = (Uint8) /*(c == transCol) ? 0 :*/255;
 
 						t1++;
@@ -541,11 +515,7 @@ bool initSludge(char *filename) {
 #if 0
 	changeToUserDir();
 
-#ifdef _WIN32
-	mkdir(gameName);
-#else
 	mkdir(gameName, 0000777);
-#endif
 
 	if (chdir(gameName)) return fatal("This game's preference folder is inaccessible!\nI can't access the following directory (maybe there's a file with the same name, or maybe it's read-protected):", gameName);
 #endif
@@ -577,11 +547,7 @@ bool initSludge(char *filename) {
 	if (dataFol[0]) {
 		char *dataFolder = encodeFilename(dataFol);
 #if 0
-#ifdef _WIN32
-		mkdir(dataFolder);
-#else
 		mkdir(dataFolder, 0000777);
-#endif
 
 		if (chdir(dataFolder)) return fatal("This game's data folder is inaccessible!\nI can't access the following directory (maybe there's a file with the same name, or maybe it's read-protected):", dataFolder);
 #endif
diff --git a/engines/sludge/sludger.h b/engines/sludge/sludger.h
index be49276..840af9e 100644
--- a/engines/sludge/sludger.h
+++ b/engines/sludge/sludger.h
@@ -31,12 +31,10 @@
 
 namespace Sludge {
 
-#ifndef _WIN32
 typedef struct _FILETIME {
 	uint32 dwLowDateTime;
 	uint32 dwHighDateTime;
 } FILETIME;
-#endif
 
 struct variable;
 struct variableStack;
diff --git a/engines/sludge/sound.h b/engines/sludge/sound.h
index ee1321a..2e31943 100644
--- a/engines/sludge/sound.h
+++ b/engines/sludge/sound.h
@@ -23,11 +23,7 @@
 #ifndef SLUDGE_SOUND_H
 #define SLUDGE_SOUND_H
 
-#ifdef _WIN32
-#include <windows.h>
-#else
 #define HWND void *
-#endif
 
 #include "common/file.h"
 
diff --git a/engines/sludge/talk.cpp b/engines/sludge/talk.cpp
index 59f71aa..162875c 100644
--- a/engines/sludge/talk.cpp
+++ b/engines/sludge/talk.cpp
@@ -281,9 +281,8 @@ bool loadSpeech(speechStruct *sS, Common::SeekableReadStream *stream) {
 		(* viewLine) = newOne;
 		viewLine = &(newOne->next);
 	}
-
-	return true;
 #endif
+	return true;
 }
 
 } // End of namespace Sludge
diff --git a/engines/sludge/timing.cpp b/engines/sludge/timing.cpp
index 6bf6863..152d9ae 100644
--- a/engines/sludge/timing.cpp
+++ b/engines/sludge/timing.cpp
@@ -19,9 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#if 0
-#include <SDL/SDL.h>
-#endif
 
 namespace Sludge {
 
diff --git a/engines/sludge/variable.cpp b/engines/sludge/variable.cpp
index 949060c..73e90f0 100644
--- a/engines/sludge/variable.cpp
+++ b/engines/sludge/variable.cpp
@@ -33,11 +33,6 @@
 #include "sludge/fileset.h"
 #include "sludge/sludge.h"
 
-#ifdef _WIN32
-#include "windows.h"
-
-#endif
-
 namespace Sludge {
 
 const char *typeName[] = { "undefined", "number", "user function", "string",
@@ -149,12 +144,6 @@ int stackSize(const stackHandler *me) {
 	return r;
 }
 
-#ifdef _WIN32
-#include <windows.h>
-WCHAR *ConvertToUTF16(const char *input);
-char *ConvertFromUTF16(const WCHAR *input);
-#endif
-
 bool getSavedGamesStack(stackHandler *sH, char *ext) {
 	char *pattern = joinStrings("*", ext);
 	if (!pattern)
@@ -163,33 +152,6 @@ bool getSavedGamesStack(stackHandler *sH, char *ext) {
 	variable newName;
 	newName.varType = SVT_NULL;
 #if 0
-#ifdef _WIN32
-
-	WCHAR *w_pattern = ConvertToUTF16(pattern);
-
-	WIN32_FIND_DATA theData;
-	HANDLE handle = FindFirstFile(w_pattern, & theData);
-
-	delete w_pattern;
-
-	if (handle != INVALID_HANDLE_VALUE) {
-		bool keepGoing;
-		do {
-			theData.cFileName[lstrlen(theData.cFileName) - strlen(ext)] = TEXT('\0');
-			char *fileName = ConvertFromUTF16(theData.cFileName);
-			char *decoded = decodeFilename(fileName);
-			makeTextVar(newName, decoded);
-			delete fileName;
-			delete decoded;
-			if (! addVarToStack(newName, sH -> first)) return false;
-			if (sH -> last == NULL) sH -> last = sH -> first;
-			keepGoing = FindNextFile(handle, & theData);
-		}while (keepGoing);
-		FindClose(handle);
-	}
-
-#else
-
 	DIR *dir = opendir(".");
 	if (!dir)
 		return false;
@@ -211,8 +173,6 @@ bool getSavedGamesStack(stackHandler *sH, char *ext) {
 	}
 
 	closedir(dir);
-
-#endif
 #endif
 	delete[] pattern;
 	pattern = NULL;
diff --git a/engines/sludge/winstuff.cpp b/engines/sludge/winstuff.cpp
deleted file mode 100644
index dfe0a5a..0000000
--- a/engines/sludge/winstuff.cpp
+++ /dev/null
@@ -1,231 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-#ifdef _WIN32
-#include <windows.h>
-#include <shellapi.h>
-
-#include "allfiles.h"
-#include "debug.h"
-
-#include "winstuff.h"
-#include "platform-dependent.h"
-#include "language.h"
-#include "newfatal.h"
-#include "sprites.h"
-#include "sprbanks.h"
-#include "fonttext.h"
-#include "backdrop.h"
-#include "sludger.h"
-#include "cursors.h"
-#include "objtypes.h"
-#include "region.h"
-#include "people.h"
-#include "talk.h"
-#include "direct.h"
-#include "sound.h"
-#include "colours.h"
-#include "moreio.h"
-#include "stringy.h"
-
-#include <shellapi.h>
-#include <shlobj.h> // For SHGetFolderPath
-
-#include "..\..\images\resource.h"
-
-namespace Sludge {
-
-	HINSTANCE hInst;                // Handle of the main instance
-	extern HWND hMainWindow;
-
-	extern variableStack *noStack;
-
-// The platform-specific functions - Windows edition.
-
-	WCHAR *ConvertToUTF16(const char *input) {
-		int s = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, input, -1, NULL, 0);
-		WCHAR *ret = new WCHAR [s];
-		checkNew(ret);
-		/*int a = */MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, input, -1, ret, s);
-		return ret;
-	}
-
-	char *ConvertFromUTF16(const WCHAR *input) {
-		int s = WideCharToMultiByte(CP_UTF8, 0, input, -1, NULL, 0, NULL, NULL);
-		char *ret = new char [s];
-		checkNew(ret);
-		/*int a = */WideCharToMultiByte(CP_UTF8, 0, input, -1, ret, s, NULL, NULL);
-		return ret;
-	}
-
-	char *grabFileName() {
-		OPENFILENAME ofn;
-		WCHAR path[MAX_PATH];
-		WCHAR file[MAX_PATH] = TEXT("");
-
-		hInst = GetModuleHandle(NULL);
-
-		memset(& ofn, 0, sizeof(ofn));
-		ofn.lStructSize = sizeof(ofn);
-		ofn.hwndOwner = NULL;
-		ofn.hInstance = hInst;
-		ofn.nMaxFile = MAX_PATH;
-		ofn.lpstrInitialDir = path;
-		ofn.Flags = OFN_HIDEREADONLY | OFN_EXPLORER;
-		ofn.lpstrFilter = TEXT("SLUDGE games (*.SLG)\0*.slg\0\0");
-		ofn.lpstrFile = file;
-
-		if (GetOpenFileName(& ofn)) {
-			return ConvertFromUTF16(file);
-		} else {
-			return NULL;
-		}
-	}
-
-	extern char **languageName;
-	extern int *languageTable;
-
-	HBITMAP hLogo = NULL;
-	extern unsigned char *gameLogo;
-
-	BOOL CALLBACK setupDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
-		switch (message) {
-			case WM_INITDIALOG:
-			if (gameLogo) {
-				hLogo = CreateBitmap(310, 88, 1, 32, gameLogo);
-				SendDlgItemMessage(hDlg, 1003, STM_SETIMAGE, (WPARAM)IMAGE_BITMAP, (LPARAM)hLogo);
-			}
-
-			if (gameSettings.userFullScreen)
-			CheckDlgButton(hDlg, 1000, BST_CHECKED);
-			else
-			CheckDlgButton(hDlg, 1000, BST_UNCHECKED);
-
-			SendDlgItemMessage(hDlg, 1002, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)TEXT("Default (best looking)")));
-			SendDlgItemMessage(hDlg, 1002, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)TEXT("Linear (faster but blurry)")));
-			SendDlgItemMessage(hDlg, 1002, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)TEXT("Off (blocky graphics)")));
-
-			if (gameSettings.antiAlias < 0)
-			SendDlgItemMessage(hDlg, 1002, CB_SETCURSEL, 1, 0);
-			else if (gameSettings.antiAlias)
-			SendDlgItemMessage(hDlg, 1002, CB_SETCURSEL, 0, 0);
-			else
-			SendDlgItemMessage(hDlg, 1002, CB_SETCURSEL, 2, 0);
-
-			if (gameSettings.numLanguages) {
-				WCHAR text[20];
-				for (unsigned int i = 0; i <= gameSettings.numLanguages; i++) {
-					if (languageName[i]) {
-						WCHAR *w_lang = ConvertToUTF16(languageName[i]);
-						SendDlgItemMessage(hDlg, 1001, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)w_lang));
-						delete w_lang;
-					} else {
-						swprintf(text, TEXT("Language %d"), i);
-						SendDlgItemMessage(hDlg, 1001, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)text));
-					}
-				}
-				SendDlgItemMessage(hDlg, 1001, CB_SETCURSEL, getLanguageForFileB(), 0);
-			} else {
-				const WCHAR *text = TEXT("No translations available");
-				SendDlgItemMessage(hDlg, 1001, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)text));
-				SendDlgItemMessage(hDlg, 1001, CB_SETCURSEL, 0, 0);
-				EnableWindow(GetDlgItem(hDlg, 1001), false);
-			}
-			return true;
-
-			case WM_COMMAND:
-			if (hLogo) DeleteObject(hLogo);
-			switch (LOWORD(wParam)) {
-				case IDOK:
-
-				gameSettings.userFullScreen = (IsDlgButtonChecked(hDlg, 1000) == BST_CHECKED);
-				gameSettings.antiAlias = SendDlgItemMessage(hDlg, 1002, CB_GETCURSEL, 0, 0);
-				if (gameSettings.antiAlias == 0) gameSettings.antiAlias = 1;
-				else if (gameSettings.antiAlias == 1) gameSettings.antiAlias = -1;
-				else if (gameSettings.antiAlias == 2) gameSettings.antiAlias = 0;
-
-				if (gameSettings.numLanguages) {
-					gameSettings.languageID = SendDlgItemMessage(hDlg, 1001, CB_GETCURSEL, 0, 0);
-					if (gameSettings.languageID < 0) gameSettings.languageID = 0;
-					gameSettings.languageID = languageTable[gameSettings.languageID];
-				}
-				EndDialog(hDlg, true);
-				return TRUE;
-
-				case IDCANCEL:
-				EndDialog(hDlg, false);
-				return TRUE;
-			}
-			break;
-		}
-		return false;
-	}
-
-	int showSetupWindow() {
-
-		hInst = GetModuleHandle(NULL);
-
-		if (! hInst) debugOut("ERROR: No hInst!\n");
-
-		if (DialogBox(hInst, TEXT("SETUPWINDOW"), NULL, setupDlgProc)) return true;
-		return false;
-
-	}
-
-	void msgBox(const char *head, const char *msg) {
-		WCHAR *w_head = ConvertToUTF16(head);
-		WCHAR *w_msg = ConvertToUTF16(msg);
-		MessageBox(NULL, w_msg, w_head, MB_OK | MB_ICONSTOP | MB_SYSTEMMODAL | MB_SETFOREGROUND);
-		delete w_head;
-		delete w_msg;
-	}
-
-	int msgBoxQuestion(const char *head, const char *msg) {
-		WCHAR *w_head = ConvertToUTF16(head);
-		WCHAR *w_msg = ConvertToUTF16(msg);
-		int val = MessageBox(NULL, w_msg, w_head, MB_YESNO | MB_SETFOREGROUND | MB_APPLMODAL | MB_ICONQUESTION) == IDNO;
-		delete w_head;
-		delete w_msg;
-		if (val)
-		return false;
-		return true;
-	}
-
-	void changeToUserDir() {
-		TCHAR szAppData[MAX_PATH];
-		/*hr = */SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, szAppData);
-		_wchdir(szAppData);
-	}
-
-	uint32 launch(char *f) {
-		WCHAR *w_f = ConvertToUTF16(f);
-		uint32 r = (uint32) ShellExecute(hMainWindow, TEXT("open"), w_f, NULL, TEXT("C:\\"), SW_SHOWNORMAL);
-		delete w_f;
-		return r;
-	}
-
-	bool defaultUserFullScreen() {
-		return true;
-	}
-
-} // End of namespace Sludge
-
-#endif
diff --git a/engines/sludge/winstuff.h b/engines/sludge/winstuff.h
deleted file mode 100644
index 4a0cbbe..0000000
--- a/engines/sludge/winstuff.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-#ifndef SLUDGE_WINSTUFF_H
-#define SLUDGE_WINSTUFF_H
-
-#ifdef _WIN32
-#include <windows.h>
-#endif
-
-namespace Sludge {
-
-#ifndef _WIN32
-#ifndef HINSTANCE
-#define HINSTANCE int
-#endif
-#endif
-
-void setWindowName(const char *tx);
-bool InitApplication(HINSTANCE hInstance);
-bool InitInstance(HINSTANCE hInstance, const char *);
-
-} // End of namespace Sludge
-
-#endif
diff --git a/engines/sludge/zbuffer.h b/engines/sludge/zbuffer.h
index 46510ec..bb0b2ed 100644
--- a/engines/sludge/zbuffer.h
+++ b/engines/sludge/zbuffer.h
@@ -22,14 +22,6 @@
 #ifndef SLUDGE_ZBUFFER_H
 #define SLUDGE_ZBUFFER_H
 
-#if 0
-#if !defined(HAVE_GLES2)
-#include "GLee.h"
-#else
-#include <GLES2/gl2.h>
-#endif
-#endif
-
 namespace Sludge {
 
 struct zBufferData {


Commit: 4773aff468f3485991b3115722f0aec1226763ad
    https://github.com/scummvm/scummvm/commit/4773aff468f3485991b3115722f0aec1226763ad
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: correct int type

Changed paths:
    engines/sludge/hsi.cpp


diff --git a/engines/sludge/hsi.cpp b/engines/sludge/hsi.cpp
index 2ce87d8..22da4b4 100644
--- a/engines/sludge/hsi.cpp
+++ b/engines/sludge/hsi.cpp
@@ -60,7 +60,7 @@ bool HSIDecoder::loadStream(Common::SeekableReadStream &stream) {
 	for (uint16 y = 0; y < height; y++) {
 		uint16 x = 0;
 		while (x < width) {
-			unsigned short c = (unsigned short)stream.readUint16BE();
+			uint16 c = stream.readUint16BE();
 			if (c & 32) {
 				n = stream.readByte() + 1;
 				c -= 32;


Commit: 90ea9d01779d02b25c7fa3f4370047ddcc974c42
    https://github.com/scummvm/scummvm/commit/90ea9d01779d02b25c7fa3f4370047ddcc974c42
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: spelling correction in define

Changed paths:
    engines/sludge/debug.h


diff --git a/engines/sludge/debug.h b/engines/sludge/debug.h
index aecff42..9382b77 100644
--- a/engines/sludge/debug.h
+++ b/engines/sludge/debug.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef SLUDGE_DEDBUG_H
-#define SLUDGE_DEGBUG_H
+#ifndef SLUDGE_DEBUG_H
+#define SLUDGE_DEBUG_H
 
 namespace Sludge {
 


Commit: 83ab05630c149d8fb61a306797dec2f4c9d75784
    https://github.com/scummvm/scummvm/commit/83ab05630c149d8fb61a306797dec2f4c9d75784
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: replace int type by scummvm types in utf8

Changed paths:
    engines/sludge/CommonCode/utf8.cpp
    engines/sludge/CommonCode/utf8.h


diff --git a/engines/sludge/CommonCode/utf8.cpp b/engines/sludge/CommonCode/utf8.cpp
index 7fe6af1..291bef4 100644
--- a/engines/sludge/CommonCode/utf8.cpp
+++ b/engines/sludge/CommonCode/utf8.cpp
@@ -32,19 +32,12 @@
   with these routines reserved for higher performance on data known to be
   valid.
 */
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdarg.h>
-#ifdef WIN32
-#include <malloc.h>
-#else
-#include <alloca.h>
-#endif
-
-#include "utf8.h"
-
-static const uint32_t offsetsFromUTF8[6] = {
+
+#include "common/debug.h"
+
+#include "sludge/CommonCode/utf8.h"
+
+static const uint32 offsetsFromUTF8[6] = {
     0x00000000UL, 0x00003080UL, 0x000E2080UL,
     0x03C82080UL, 0xFA082080UL, 0x82082080UL
 };
@@ -76,9 +69,9 @@ int u8_seqlen(char *s)
    for all the characters.
    if sz = srcsz+1 (i.e. 4*srcsz+4 bytes), there will always be enough space.
 */
-int u8_toucs(uint32_t *dest, int sz, char *src, int srcsz)
+int u8_toucs(uint32 *dest, int sz, char *src, int srcsz)
 {
-    uint32_t ch;
+    uint32 ch;
     char *src_end = src + srcsz;
     int nb;
     int i=0;
@@ -121,9 +114,9 @@ int u8_toucs(uint32_t *dest, int sz, char *src, int srcsz)
    the NUL as well.
    the destination string will never be bigger than the source string.
 */
-int u8_toutf8(char *dest, int sz, uint32_t *src, int srcsz)
+int u8_toutf8(char *dest, int sz, uint32 *src, int srcsz)
 {
-    uint32_t ch;
+    uint32 ch;
     int i = 0;
     char *dest_end = dest + sz;
 
@@ -162,7 +155,7 @@ int u8_toutf8(char *dest, int sz, uint32_t *src, int srcsz)
     return i;
 }
 
-int u8_wc_toutf8(char *dest, uint32_t ch)
+int u8_wc_toutf8(char *dest, uint32 ch)
 {
     if (ch < 0x80) {
         dest[0] = (char)ch;
@@ -228,9 +221,9 @@ int u8_strlen(char *s)
 }
 
 /* reads the next utf-8 sequence out of a string, updating an index */
-uint32_t u8_nextchar(const char *s, int *i)
+uint32 u8_nextchar(const char *s, int *i)
 {
-    uint32_t ch = 0;
+    uint32 ch = 0;
     int sz = 0;
 
     do {
@@ -269,13 +262,13 @@ int hex_digit(char c)
 
 /* assumes that src points to the character after a backslash
    returns number of input characters processed */
-int u8_read_escape_sequence(char *str, uint32_t *dest)
+int u8_read_escape_sequence(char *str, uint32 *dest)
 {
-    uint32_t ch;
+    uint32 ch;
     char digs[9]="\0\0\0\0\0\0\0\0";
     int dno=0, i=1;
 
-    ch = (uint32_t)str[0];    /* take literal character */
+    ch = (uint32)str[0];    /* take literal character */
     if (str[0] == 'n')
         ch = L'\n';
     else if (str[0] == 't')
@@ -329,7 +322,7 @@ int u8_read_escape_sequence(char *str, uint32_t *dest)
 int u8_unescape(char *buf, int sz, char *src)
 {
     int c=0, amt;
-    uint32_t ch;
+    uint32 ch;
     char temp[4];
 
     while (*src && c < sz) {
@@ -338,7 +331,7 @@ int u8_unescape(char *buf, int sz, char *src)
             amt = u8_read_escape_sequence(src, &ch);
         }
         else {
-            ch = (uint32_t)*src;
+            ch = (uint32)*src;
             amt = 1;
         }
         src += amt;
@@ -353,7 +346,7 @@ int u8_unescape(char *buf, int sz, char *src)
     return c;
 }
 
-int u8_escape_wchar(char *buf, int sz, uint32_t ch)
+int u8_escape_wchar(char *buf, int sz, uint32 ch)
 {
     if (ch == L'\n')
         return snprintf(buf, sz, "\\n");
@@ -374,7 +367,7 @@ int u8_escape_wchar(char *buf, int sz, uint32_t ch)
     else if (ch < 32 || ch == 0x7f)
         return snprintf(buf, sz, "\\x%hhX", (unsigned char)ch);
     else if (ch > 0xFFFF)
-        return snprintf(buf, sz, "\\U%.8X", (uint32_t)ch);
+        return snprintf(buf, sz, "\\U%.8X", (uint32)ch);
     else if (ch >= 0x80 && ch <= 0xFFFF)
         return snprintf(buf, sz, "\\u%.4hX", (unsigned short)ch);
 
@@ -401,10 +394,10 @@ int u8_escape(char *buf, int sz, char *src, int escape_quotes)
     return c;
 }
 
-char *u8_strchr(char *s, uint32_t ch, int *charn)
+char *u8_strchr(char *s, uint32 ch, int *charn)
 {
     int i = 0, lasti=0;
-    uint32_t c;
+    uint32 c;
 
     *charn = 0;
     while (s[i]) {
@@ -418,10 +411,10 @@ char *u8_strchr(char *s, uint32_t ch, int *charn)
     return NULL;
 }
 
-char *u8_memchr(char *s, uint32_t ch, size_t sz, int *charn)
+char *u8_memchr(char *s, uint32 ch, size_t sz, int *charn)
 {
     int i = 0, lasti=0;
-    uint32_t c;
+    uint32 c;
     int csz;
 
     *charn = 0;
@@ -466,7 +459,7 @@ int u8_vprintf(char *fmt, va_list ap)
 {
     int cnt, sz=0;
     char *buf;
-    uint32_t *wcs;
+    uint32 *wcs;
 
     sz = 512;
     buf = (char*)alloca(sz);
@@ -477,9 +470,9 @@ int u8_vprintf(char *fmt, va_list ap)
         sz = cnt + 1;
         goto try_print;
     }
-    wcs = (uint32_t*)alloca((cnt+1) * sizeof(uint32_t));
+    wcs = (uint32*)alloca((cnt+1) * sizeof(uint32));
     cnt = u8_toucs(wcs, cnt+1, buf, cnt);
-    printf("%ls", (wchar_t*)wcs);
+    debug("%ls", (wchar_t*)wcs);
     return cnt;
 }
 
diff --git a/engines/sludge/CommonCode/utf8.h b/engines/sludge/CommonCode/utf8.h
index 71df6cb..c9af92e 100644
--- a/engines/sludge/CommonCode/utf8.h
+++ b/engines/sludge/CommonCode/utf8.h
@@ -19,20 +19,20 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#include <stdint.h>
-#include <stdarg.h>
+
+#include "common/system.h"
 
 /* is c the start of a utf8 sequence? */
 #define isutf(c) (((c)&0xC0)!=0x80)
 
 /* convert UTF-8 data to wide character */
-int u8_toucs(uint32_t *dest, int sz, char *src, int srcsz);
+int u8_toucs(uint32 *dest, int sz, char *src, int srcsz);
 
 /* the opposite conversion */
-int u8_toutf8(char *dest, int sz, uint32_t *src, int srcsz);
+int u8_toutf8(char *dest, int sz, uint32 *src, int srcsz);
 
 /* single character to UTF-8 */
-int u8_wc_toutf8(char *dest, uint32_t ch);
+int u8_wc_toutf8(char *dest, uint32 ch);
 
 /* character number to byte offset */
 int u8_offset(char *str, int charnum);
@@ -41,7 +41,7 @@ int u8_offset(char *str, int charnum);
 int u8_charnum(char *s, int offset);
 
 /* return next character, updating an index variable */
-uint32_t u8_nextchar(const char *s, int *i);
+uint32 u8_nextchar(const char *s, int *i);
 
 /* move to next character */
 void u8_inc(char *s, int *i);
@@ -55,11 +55,11 @@ int u8_seqlen(char *s);
 /* assuming src points to the character after a backslash, read an
    escape sequence, storing the result in dest and returning the number of
    input characters processed */
-int u8_read_escape_sequence(char *src, uint32_t *dest);
+int u8_read_escape_sequence(char *src, uint32 *dest);
 
 /* given a wide character, convert it to an ASCII escape sequence stored in
    buf, where buf is "sz" bytes. returns the number of characters output. */
-int u8_escape_wchar(char *buf, int sz, uint32_t ch);
+int u8_escape_wchar(char *buf, int sz, uint32 ch);
 
 /* convert a string "src" containing escape sequences to UTF-8 */
 int u8_unescape(char *buf, int sz, char *src);
@@ -75,11 +75,11 @@ int hex_digit(char c);
 
 /* return a pointer to the first occurrence of ch in s, or NULL if not
    found. character index of found character returned in *charn. */
-char *u8_strchr(char *s, uint32_t ch, int *charn);
+char *u8_strchr(char *s, uint32 ch, int *charn);
 
 /* same as the above, but searches a buffer of a given size instead of
    a NUL-terminated string. */
-char *u8_memchr(char *s, uint32_t ch, size_t sz, int *charn);
+char *u8_memchr(char *s, uint32 ch, size_t sz, int *charn);
 
 /* count the number of characters in a UTF-8 string */
 int u8_strlen(char *s);


Commit: 3975fd7215fa0b97249231f965837729be21e554
    https://github.com/scummvm/scummvm/commit/3975fd7215fa0b97249231f965837729be21e554
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove showSetupWindow

Changed paths:
    engines/sludge/platform-dependent.h
    engines/sludge/sludger.cpp


diff --git a/engines/sludge/platform-dependent.h b/engines/sludge/platform-dependent.h
index 0296bc1..bf36f5f 100644
--- a/engines/sludge/platform-dependent.h
+++ b/engines/sludge/platform-dependent.h
@@ -28,7 +28,6 @@
 namespace Sludge {
 
 char *grabFileName();
-int showSetupWindow();
 
 void msgBox(const char *head, const char *msg);
 int msgBoxQuestion(const char *head, const char *msg);
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index 0b99d79..ea71626 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -527,17 +527,13 @@ bool initSludge(char *filename) {
 	// There's no startup window on Linux and respecting this
 	// option from the ini file would disable commandline options.
 #if defined __unix__ && !(defined __APPLE__)
-#if 0
-	if (!showSetupWindow()) return 0;
-#endif
 	saveIniFile(filename);
 #else
 	if (!gameSettings.noStartWindow) {
-		if (!showSetupWindow()) return 0;
 		saveIniFile(filename);
 	}
 #endif
-
+	
 	// Now set file indices properly to the chosen language.
 	languageNum = getLanguageForFileB();
 	if (languageNum < 0)


Commit: 2ca68459620b84135c61daba231f1db66158c9b8
    https://github.com/scummvm/scummvm/commit/2ca68459620b84135c61daba231f1db66158c9b8
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: use AD_ENTRY1s instead of AD_ENTRY1

Changed paths:
  A engines/sludge/detection_tables.h
    engines/sludge/detection.cpp


diff --git a/engines/sludge/detection.cpp b/engines/sludge/detection.cpp
index e45ada2..423246e 100644
--- a/engines/sludge/detection.cpp
+++ b/engines/sludge/detection.cpp
@@ -49,64 +49,7 @@ static const PlainGameDescriptor sludgeGames[] = {
 	{ 0, 0 }
 };
  
-namespace Sludge {
-static const SludgeGameDescription gameDescriptions[] = {
-	{
-		{
-			"welcome",
-			"",
-			AD_ENTRY1("Welcome.slg", "50445503761cf6684fe3270d0860a4c3"),
-			Common::EN_ANY,
-			Common::kPlatformUnknown,
-			ADGF_NO_FLAGS,
-			GUIO0()
-		},
-		0
-	},
-
-	{
-		{
-			"welcome2",
-			"",
-			AD_ENTRY1("Welcome.slg", "cb1f307c05b8ae4107bcc7f86a3d2f99"),
-			Common::EN_ANY,
-			Common::kPlatformUnknown,
-			ADGF_NO_FLAGS,
-			GUIO0()
-		},
-		0
-	},
-
-	{
-		{
-			"welcomePng",
-			"",
-			AD_ENTRY1("Welcome.slg", "ff0d7ef0ce73b5503ef6b965928af6d6"),
-			Common::EN_ANY,
-			Common::kPlatformUnknown,
-			ADGF_NO_FLAGS,
-			GUIO0()
-		},
-		0
-	},
-
-	{
-		{
-			"verbcoin",
-			"",
-			AD_ENTRY1("Welcome.slg", "e39ec315dcbf3a1137481f0a5fe1617d"),
-			Common::EN_ANY,
-			Common::kPlatformUnknown,
-			ADGF_NO_FLAGS,
-			GUIO0()
-		},
-		0
-	},
-
-	{ AD_TABLE_END_MARKER, 0 }
-};
-
-} // End of namespace Sludge
+#include "sludge/detection_tables.h"
 
 class SludgeMetaEngine : public AdvancedMetaEngine {
 public:
diff --git a/engines/sludge/detection_tables.h b/engines/sludge/detection_tables.h
new file mode 100644
index 0000000..1176832
--- /dev/null
+++ b/engines/sludge/detection_tables.h
@@ -0,0 +1,55 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+namespace Sludge {
+
+static const SludgeGameDescription gameDescriptions[] = {
+	{
+		{
+			"welcome",
+			"",
+			AD_ENTRY1s("Welcome.slg", "50445503761cf6684fe3270d0860a4c3", 51736),
+			Common::EN_ANY,
+			Common::kPlatformUnknown,
+			ADGF_NO_FLAGS,
+			GUIO0()
+		},
+		0
+	},
+
+	{
+		{
+			"verbcoin",
+			"",
+			AD_ENTRY1s("Verb Coin.slg", "e39ec315dcbf3a1137481f0a5fe1617d", 980270),
+			Common::EN_ANY,
+			Common::kPlatformUnknown,
+			ADGF_NO_FLAGS,
+			GUIO0()
+		},
+		0
+	},
+
+	{ AD_TABLE_END_MARKER, 0 }
+};
+
+} // End of namespace Wage


Commit: d5379c212c4ee972083d825a6e586b1341f9e6f9
    https://github.com/scummvm/scummvm/commit/d5379c212c4ee972083d825a6e586b1341f9e6f9
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: add game file name getter in detection

Changed paths:
    engines/sludge/detection.cpp
    engines/sludge/language.cpp
    engines/sludge/language.h
    engines/sludge/main_loop.cpp
    engines/sludge/main_loop.h
    engines/sludge/sludge.cpp
    engines/sludge/sludge.h
    engines/sludge/sludger.cpp
    engines/sludge/sludger.h


diff --git a/engines/sludge/detection.cpp b/engines/sludge/detection.cpp
index 423246e..69e202c 100644
--- a/engines/sludge/detection.cpp
+++ b/engines/sludge/detection.cpp
@@ -37,6 +37,9 @@ int SludgeEngine::getGameType() const { return _gameDescription->gameType; }
 const char *SludgeEngine::getGameId() const { return _gameDescription->desc.gameId;}
 uint32 SludgeEngine::getFeatures() const { return _gameDescription->desc.flags; }
 Common::Language SludgeEngine::getLanguage() const { return _gameDescription->desc.language; }
+const char *SludgeEngine::getGameFile() const {
+	return _gameDescription->desc.filesDescriptions[0].fileName;
+}
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/language.cpp b/engines/sludge/language.cpp
index 1aff394..b0b3a8e 100644
--- a/engines/sludge/language.cpp
+++ b/engines/sludge/language.cpp
@@ -81,7 +81,7 @@ char *getPrefsFilename(char *filename) {
 	return joined;
 }
 
-void readIniFile(char *filename) {
+void readIniFile(const char *filename) {
 
 	char *langName = getPrefsFilename(copyString(filename));
 
@@ -161,7 +161,7 @@ void readIniFile(char *filename) {
 	fd.close();
 }
 
-void saveIniFile(char *filename) {
+void saveIniFile(const char *filename) {
 #if 0
 	char *langName = getPrefsFilename(copyString(filename));
 	FILE *fp = fopen(langName, "wt");
diff --git a/engines/sludge/language.h b/engines/sludge/language.h
index 033633b..85d50bb 100644
--- a/engines/sludge/language.h
+++ b/engines/sludge/language.h
@@ -41,8 +41,8 @@ struct settingsStruct {
 
 extern settingsStruct gameSettings;
 
-void readIniFile(char *filename);
-void saveIniFile(char *filename);
+void readIniFile(const char *filename);
+void saveIniFile(const char *filename);
 int getLanguageForFileB();
 
 void makeLanguageTable(Common::File *table);
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index ebeedf9..7498ab2 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -295,7 +295,7 @@ void checkInput() {
 #endif
 }
 
-int main_loop(char *filename)
+int main_loop(const char *filename)
 #if 0
 		try
 #endif
@@ -304,62 +304,9 @@ int main_loop(char *filename)
 	winWidth = 640;
 	winHeight = 480;
 
-	char *sludgeFile;
-
-#if 0
-	time_t t;
-	srand((unsigned) time(&t));
-
-	// bundleFolder is used to look for the game file
-	// and later to find the shader programs
-#ifdef __APPLE__
-	// bundleFolder is set in applicationDidFinishLaunching.
-#elif defined __unix__
-	bundleFolder = copyString(DATADIR); // DATADIR is defined in the Makefile.
-#else
-	bundleFolder = copyString(argv[0]);
-	int lastSlash = -1;
-	for (int i = 0; bundleFolder[i]; i ++) {
-		if (bundleFolder[i] == PATHSLASH) lastSlash = i;
-	}
-	bundleFolder[lastSlash + 1] = NULL;
-#endif
-
-#endif
-
-	sludgeFile = filename;
-	if (!sludgeFile) {
-		sludgeFile = joinStrings(bundleFolder, "gamedata.slg");
-		if (!(fileExists(sludgeFile))) {
-			delete sludgeFile;
-			sludgeFile = joinStrings(bundleFolder, "gamedata");
-			if (!(fileExists(sludgeFile))) {
-#if 0
-				sludgeFile = grabFileName();
-#endif
-			}
-		}
-	}
-
-#if 0
-#if defined __unix__ && !(defined __APPLE__)
-	if (!fileExists(sludgeFile)) {
-		fprintf(stderr, "Game file not found.\n");
-		printCmdlineUsage();
+	if (!initSludge(filename)) {
 		return 0;
 	}
-#endif
-#endif
-
-	// The player pressed cancel in the file selection dialogue,
-	// so we should quit now.
-	if (!sludgeFile)
-		return 0;
-
-	// OK, so we DO want to start up, then...
-	setGameFilePath(sludgeFile);
-	if (!initSludge(sludgeFile))
-		return 0;
 
 #if 0
 	/* Initialize the SDL library */
diff --git a/engines/sludge/main_loop.h b/engines/sludge/main_loop.h
index 7ea5881..b287c81 100644
--- a/engines/sludge/main_loop.h
+++ b/engines/sludge/main_loop.h
@@ -24,7 +24,7 @@
 
 namespace Sludge {
 
-int main_loop(char *filename);
+int main_loop(const char *filename);
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/sludge.cpp b/engines/sludge/sludge.cpp
index 725478c..6ea4b7b 100644
--- a/engines/sludge/sludge.cpp
+++ b/engines/sludge/sludge.cpp
@@ -70,7 +70,7 @@ Common::Error SludgeEngine::run() {
 	_console = new SludgeConsole(this);
 
 	// debug log
-	main_loop("Welcome.slg");
+	main_loop(getGameFile());
 
 	return Common::kNoError;
 }
diff --git a/engines/sludge/sludge.h b/engines/sludge/sludge.h
index a4e96c7..5754482 100644
--- a/engines/sludge/sludge.h
+++ b/engines/sludge/sludge.h
@@ -58,6 +58,8 @@ public:
 	uint32 getFeatures() const;
 	Common::Language getLanguage() const;
 
+	const char *getGameFile() const;
+
 	const SludgeGameDescription *_gameDescription;
 
 private:
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index ea71626..70f8180 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -135,7 +135,7 @@ void saveHandlers(Common::WriteStream *stream) {
 	stream->writeUint16BE(currentEvents->spaceFunction);
 }
 
-Common::File *openAndVerify(char *filename, char extra1, char extra2,
+Common::File *openAndVerify(const char *filename, char extra1, char extra2,
 		const char *er, int &fileVersion) {
 	Common::File *fp = new Common::File();
 	if (!fp->open(filename)) {
@@ -186,7 +186,7 @@ Common::File *openAndVerify(char *filename, char extra1, char extra2,
 	return fp;
 }
 
-bool initSludge(char *filename) {
+bool initSludge(const char *filename) {
 	int a = 0;
 	mouseCursorAnim = makeNullAnim();
 
diff --git a/engines/sludge/sludger.h b/engines/sludge/sludger.h
index 840af9e..6234e59 100644
--- a/engines/sludge/sludger.h
+++ b/engines/sludge/sludger.h
@@ -76,7 +76,7 @@ struct inputType {
 extern unsigned char *gameIcon;
 extern int iconW, iconH;
 
-bool initSludge(char *);
+bool initSludge(const char *);
 void sludgeDisplay();
 int startNewFunctionNum(unsigned int, unsigned int, loadedFunction *, variableStack*&, bool = true);
 bool handleInput();
@@ -87,7 +87,7 @@ void saveHandlers(Common::WriteStream *stream);
 
 void finishFunction(loadedFunction *fun);
 void abortFunction(loadedFunction *fun);
-Common::File *openAndVerify(char *filename, char extra1, char extra2, const char *er, int &fileVersion);
+Common::File *openAndVerify(const char *filename, char extra1, char extra2, const char *er, int &fileVersion);
 
 void freezeSubs();
 void unfreezeSubs();


Commit: 77d5c7235d5ad0aa36abc3625e0716582ee52318
    https://github.com/scummvm/scummvm/commit/77d5c7235d5ad0aa36abc3625e0716582ee52318
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: replace sludge colours by pixelformat

Changed paths:
  R engines/sludge/colours.h
    engines/sludge/backdrop.cpp
    engines/sludge/bg_effects.cpp
    engines/sludge/builtin.cpp
    engines/sludge/cursors.cpp
    engines/sludge/fonttext.cpp
    engines/sludge/hsi.cpp
    engines/sludge/imgloader.cpp
    engines/sludge/sludge.cpp
    engines/sludge/sludge.h
    engines/sludge/sludger.cpp
    engines/sludge/sprites.cpp
    engines/sludge/statusba.cpp
    engines/sludge/thumbnail.cpp
    engines/sludge/transition.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index d80a8ae..42b1c99 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -28,7 +28,6 @@
 
 #include "sludge/allfiles.h"
 #include "sludge/newfatal.h"
-#include "sludge/colours.h"
 #include "sludge/fileset.h"
 #include "sludge/backdrop.h"
 #include "sludge/moreio.h"
@@ -70,7 +69,7 @@ int cameraPX = 0, cameraPY = 0;
 
 unsigned int sceneWidth, sceneHeight;
 int lightMapNumber;
-unsigned int currentBlankColour = makeColour(0, 0, 0);
+unsigned int currentBlankColour = g_sludge->getOrigPixelFormat().RGBToColor(0, 0, 0);
 
 extern int cameraX, cameraY;
 extern float cameraZoom;
diff --git a/engines/sludge/bg_effects.cpp b/engines/sludge/bg_effects.cpp
index 100b906..529556e 100644
--- a/engines/sludge/bg_effects.cpp
+++ b/engines/sludge/bg_effects.cpp
@@ -25,7 +25,6 @@
 
 #include "sludge/allfiles.h"
 #include "sludge/backdrop.h"
-#include "sludge/colours.h"
 #include "sludge/debug.h"
 #include "sludge/graphics.h"
 #include "sludge/moreio.h"
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 873b523..b15ed01 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -46,10 +46,10 @@
 #include "sludge/movie.h"
 #include "sludge/savedata.h"
 #include "sludge/freeze.h"
-#include "sludge/colours.h"
 #include "sludge/language.h"
 #include "sludge/thumbnail.h"
 #include "sludge/graphics.h"
+#include "sludge/sludge.h"
 #include "sludge/CommonCode/utf8.h"
 
 namespace Sludge {
@@ -849,7 +849,7 @@ builtIn(setBlankColour) {
 	if (!getRGBParams(red, green, blue, fun))
 		return BR_ERROR;
 
-	currentBlankColour = makeColour(red & 255, green & 255, blue & 255);
+	currentBlankColour = g_sludge->getOrigPixelFormat().RGBToColor(red & 255, green & 255, blue & 255);
 	setVariable(fun->reg, SVT_INT, 1);
 	return BR_CONTINUE;
 }
diff --git a/engines/sludge/colours.h b/engines/sludge/colours.h
deleted file mode 100644
index a613f67..0000000
--- a/engines/sludge/colours.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef SLUDGE_COLOURS_H
-#define SLUDGE_COLOURS_H
-
-namespace Sludge {
-
-// Simple colour conversion routines to deal with 16-bit graphics
-//unsigned short int makeColour (byte r, byte g, byte b);
-
-inline unsigned short redValue(unsigned short c) {
-	return (c >> 11) << 3;
-}
-inline unsigned short greenValue(unsigned short c) {
-	return ((c >> 5) & 63) << 2;
-}
-inline unsigned short blueValue(unsigned short c) {
-	return (c & 31) << 3;
-}
-
-inline unsigned short makeGrey(unsigned short int r) {
-	return ((r >> 3) << 11) | ((r >> 2) << 5) | (r >> 3);
-}
-
-inline unsigned short makeColour(unsigned short int r, unsigned short int g,
-		unsigned short int b) {
-	return ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3);
-}
-
-} // End of namespace Sludge
-
-#endif
diff --git a/engines/sludge/cursors.cpp b/engines/sludge/cursors.cpp
index abe09c8..519b636 100644
--- a/engines/sludge/cursors.cpp
+++ b/engines/sludge/cursors.cpp
@@ -22,7 +22,6 @@
 
 #include "sludge/allfiles.h"
 #include "sludge/cursors.h"
-#include "sludge/colours.h"
 #include "sludge/sprites.h"
 #include "sludge/sprbanks.h"
 #include "sludge/people.h"
diff --git a/engines/sludge/fonttext.cpp b/engines/sludge/fonttext.cpp
index f66cde5..c3c877c 100644
--- a/engines/sludge/fonttext.cpp
+++ b/engines/sludge/fonttext.cpp
@@ -24,7 +24,6 @@
 #include "sludge/allfiles.h"
 #include "sludge/stringy.h"
 #include "sludge/sprites.h"
-#include "sludge/colours.h"
 #include "sludge/fonttext.h"
 #include "sludge/newfatal.h"
 #include "sludge/moreio.h"
diff --git a/engines/sludge/hsi.cpp b/engines/sludge/hsi.cpp
index 22da4b4..3ccdc14 100644
--- a/engines/sludge/hsi.cpp
+++ b/engines/sludge/hsi.cpp
@@ -25,7 +25,6 @@
 
 #include "graphics/surface.h"
 
-#include "sludge/colours.h"
 #include "sludge/hsi.h"
 #include "sludge/sludge.h"
 
@@ -56,7 +55,7 @@ bool HSIDecoder::loadStream(Common::SeekableReadStream &stream) {
 	debug(kSludgeDebugGraphics, "picHeight : %i", height);
 
 	_surface = new Graphics::Surface();
-	_surface->create(width, height, Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0));
+	_surface->create(width, height, g_sludge->getScreenPixelFormat());
 	for (uint16 y = 0; y < height; y++) {
 		uint16 x = 0;
 		while (x < width) {
@@ -76,9 +75,7 @@ bool HSIDecoder::loadStream(Common::SeekableReadStream &stream) {
 					target[3] = (byte)0;
 				} else {
 					target[0] = (byte)255;
-					target[1] = (byte)blueValue(c);
-					target[2] = (byte)greenValue(c);
-					target[3] = (byte)redValue(c);
+					g_sludge->getOrigPixelFormat().colorToRGB(c, target[3], target[2], target[1]);
 				}
 				x++;
 			}
diff --git a/engines/sludge/imgloader.cpp b/engines/sludge/imgloader.cpp
index 8036b4c..eef18ee 100644
--- a/engines/sludge/imgloader.cpp
+++ b/engines/sludge/imgloader.cpp
@@ -28,7 +28,6 @@
 #include "sludge/allfiles.h"
 #include "sludge/hsi.h"
 #include "sludge/imgloader.h"
-#include "sludge/colours.h"
 #include "sludge/sludge.h"
 
 namespace Sludge {
@@ -50,7 +49,7 @@ bool ImgLoader::loadPNGImage(Common::SeekableReadStream *stream, Graphics::Surfa
 	if (!png.loadStream(*stream))
 		return false;
 	const Graphics::Surface *sourceSurface = png.getSurface();
-	Graphics::Surface *pngSurface = sourceSurface->convertTo(Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0), png.getPalette());
+	Graphics::Surface *pngSurface = sourceSurface->convertTo(g_sludge->getScreenPixelFormat(), png.getPalette());
 	dest->copyFrom(*pngSurface);
 	pngSurface->free();
 	delete pngSurface;
diff --git a/engines/sludge/sludge.cpp b/engines/sludge/sludge.cpp
index 6ea4b7b..90bdd45 100644
--- a/engines/sludge/sludge.cpp
+++ b/engines/sludge/sludge.cpp
@@ -32,6 +32,15 @@
 
 namespace Sludge {
 
+SludgeEngine *g_sludge;
+
+Graphics::PixelFormat SludgeEngine::getScreenPixelFormat() const { return _pixelFormat; }
+Graphics::PixelFormat SludgeEngine::getOrigPixelFormat() const {
+	return Graphics::PixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0);
+	//return _origFormat;
+	// TODO: get segmentation fault when returning _origFormat
+}
+
 SludgeEngine::SludgeEngine(OSystem *syst, const SludgeGameDescription *gameDesc) :
 		Engine(syst), _gameDescription(gameDesc), _console(nullptr) {
 
@@ -62,9 +71,13 @@ SludgeEngine::~SludgeEngine() {
 }
 
 Common::Error SludgeEngine::run() {
+	// set global variable
+	g_sludge = this;
+
 	// init graphics
-	Graphics::PixelFormat format = Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0);
-	initGraphics(640, 480, false, &format);
+	_origFormat = Graphics::PixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0);
+	_pixelFormat = Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0);
+	initGraphics(640, 480, false, &_pixelFormat);
 
 	// create console
 	_console = new SludgeConsole(this);
diff --git a/engines/sludge/sludge.h b/engines/sludge/sludge.h
index 5754482..5fe09c3 100644
--- a/engines/sludge/sludge.h
+++ b/engines/sludge/sludge.h
@@ -25,12 +25,15 @@
 
 #include "common/random.h"
 #include "engines/engine.h"
+#include "graphics/pixelformat.h"
 #include "gui/debugger.h"
 
 #include "sludge/console.h"
 
 namespace Sludge {
 
+extern SludgeEngine *g_sludge;
+
 class SludgeConsole;
 
 struct SludgeGameDescription;
@@ -57,6 +60,8 @@ public:
 	const char *getGameId() const;
 	uint32 getFeatures() const;
 	Common::Language getLanguage() const;
+	Graphics::PixelFormat getScreenPixelFormat() const;
+	Graphics::PixelFormat getOrigPixelFormat() const;
 
 	const char *getGameFile() const;
 
@@ -65,6 +70,8 @@ public:
 private:
 	SludgeConsole *_console;
 	Common::RandomSource *_rnd;
+	Graphics::PixelFormat _pixelFormat;
+	Graphics::PixelFormat _origFormat;
 };
 
 } // End of namespace Sludge
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index 70f8180..e9c7243 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -27,7 +27,6 @@
 #include "sludge/sludger.h"
 #include "sludge/backdrop.h"
 #include "sludge/cursors.h"
-#include "sludge/colours.h"
 #include "sludge/objtypes.h"
 #include "sludge/region.h"
 #include "sludge/sprites.h"
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index 1dc6619..3ea82c8 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -29,7 +29,6 @@
 #include "sludge/sprites.h"
 #include "sludge/moreio.h"
 #include "sludge/newfatal.h"
-#include "sludge/colours.h"
 #include "sludge/backdrop.h"
 #include "sludge/sludger.h"
 #include "sludge/zbuffer.h"
@@ -37,6 +36,7 @@
 #include "sludge/graphics.h"
 #include "sludge/imgloader.h"
 #include "sludge/shaders.h"
+#include "sludge/sludge.h"
 
 namespace Sludge {
 
@@ -181,9 +181,9 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 		}
 
 		// init data
-		loadhere.sprites[i].surface.create(picwidth, picheight, Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0));
+		loadhere.sprites[i].surface.create(picwidth, picheight, g_sludge->getScreenPixelFormat());
 		if (isFont) {
-			loadhere.sprites[i].burnSurface.create(picwidth, picheight, Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0));
+			loadhere.sprites[i].burnSurface.create(picwidth, picheight, g_sludge->getScreenPixelFormat());
 		}
 		data = (byte *)new byte[picwidth * (picheight + 1)];
 		if (!checkNew(data)) return false;
@@ -230,7 +230,11 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 		loadhere.myPalette.r[i + startIndex] = (byte)bigDataFile->readByte();
 		loadhere.myPalette.g[i + startIndex] = (byte)bigDataFile->readByte();
 		loadhere.myPalette.b[i + startIndex] = (byte)bigDataFile->readByte();
-		loadhere.myPalette.pal[i + startIndex] = makeColour(loadhere.myPalette.r[i + startIndex], loadhere.myPalette.g[i + startIndex], loadhere.myPalette.b[i + startIndex]);
+		loadhere.myPalette.pal[i + startIndex] =
+				(uint16)g_sludge->getOrigPixelFormat().RGBToColor(
+						loadhere.myPalette.r[i + startIndex],
+						loadhere.myPalette.g[i + startIndex],
+						loadhere.myPalette.b[i + startIndex]);
 	}
 	loadhere.myPalette.originalRed = loadhere.myPalette.originalGreen = loadhere.myPalette.originalBlue = 255;
 
diff --git a/engines/sludge/statusba.cpp b/engines/sludge/statusba.cpp
index 4bf665b..0ebe4e7 100644
--- a/engines/sludge/statusba.cpp
+++ b/engines/sludge/statusba.cpp
@@ -24,7 +24,6 @@
 
 #include "sludge/allfiles.h"
 #include "sludge/backdrop.h"
-#include "sludge/colours.h"
 #include "sludge/sprites.h"
 #include "sludge/fonttext.h"
 #include "sludge/moreio.h"
diff --git a/engines/sludge/thumbnail.cpp b/engines/sludge/thumbnail.cpp
index df0076c..8e238f7 100644
--- a/engines/sludge/thumbnail.cpp
+++ b/engines/sludge/thumbnail.cpp
@@ -24,7 +24,6 @@
 #include "sludge/errors.h"
 #include "sludge/moreio.h"
 #include "sludge/sludger.h"
-#include "sludge/colours.h"
 #include "sludge/backdrop.h"
 #include "sludge/graphics.h"
 #include "sludge/newfatal.h"
diff --git a/engines/sludge/transition.cpp b/engines/sludge/transition.cpp
index 05257d8..207eca6 100644
--- a/engines/sludge/transition.cpp
+++ b/engines/sludge/transition.cpp
@@ -21,7 +21,6 @@
  */
 
 #include "sludge/allfiles.h"
-#include "sludge/colours.h"
 #include "sludge/backdrop.h"
 #include "sludge/graphics.h"
 #include "sludge/newfatal.h"


Commit: 839e7fb4d2d51c6abd38d1cc56a2d2cbd346d710
    https://github.com/scummvm/scummvm/commit/839e7fb4d2d51c6abd38d1cc56a2d2cbd346d710
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: fix unmatched delete[] leaks

Changed paths:
    engines/sludge/builtin.cpp
    engines/sludge/floor.cpp
    engines/sludge/language.cpp
    engines/sludge/newfatal.cpp
    engines/sludge/sludger.cpp
    engines/sludge/statusba.cpp
    engines/sludge/talk.cpp
    engines/sludge/variable.cpp


diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index b15ed01..131a903 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -180,7 +180,7 @@ static builtReturn sayCore(int numParams, loadedFunction *fun, bool sayIt) {
 			fun->timeLeft = p;
 			//debugOut ("BUILTIN: sayCore: %s (%i)\n", newText, p);
 			fun->isSpeech = true;
-			delete newText;
+			delete[] newText;
 			newText = NULL;
 			return BR_KEEP_AND_PAUSE;
 	}
@@ -887,7 +887,7 @@ builtIn(setFont) {
 	if (!loadFont(fileNumber, newText, newHeight))
 		return BR_ERROR;
 	//              newDebug ("  Done!");
-	delete newText;
+	delete[] newText;
 
 	return BR_CONTINUE;
 }
@@ -1862,7 +1862,7 @@ builtIn(statusText) {
 		return BR_ERROR;
 	trimStack(fun->stack);
 	setStatusBar(newText);
-	delete newText;
+	delete[] newText;
 	return BR_CONTINUE;
 }
 
diff --git a/engines/sludge/floor.cpp b/engines/sludge/floor.cpp
index a402ef9..e556463 100644
--- a/engines/sludge/floor.cpp
+++ b/engines/sludge/floor.cpp
@@ -231,10 +231,10 @@ bool setFloor(int fileNum) {
 	} while (madeChange);
 
 	for (i = 0; i < currentFloor->numPolygons; i++) {
-		delete distanceMatrix[i];
+		delete[] distanceMatrix[i];
 	}
 
-	delete distanceMatrix;
+	delete []distanceMatrix;
 	distanceMatrix = NULL;
 
 	setResourceForFatal(-1);
diff --git a/engines/sludge/language.cpp b/engines/sludge/language.cpp
index b0b3a8e..cb055f9 100644
--- a/engines/sludge/language.cpp
+++ b/engines/sludge/language.cpp
@@ -76,7 +76,7 @@ char *getPrefsFilename(char *filename) {
 
 	char *joined = joinStrings(f, ".ini");
 
-	delete filename;
+	delete[] filename;
 	filename = NULL;
 	return joined;
 }
diff --git a/engines/sludge/newfatal.cpp b/engines/sludge/newfatal.cpp
index bc97d6a..a44290a 100644
--- a/engines/sludge/newfatal.cpp
+++ b/engines/sludge/newfatal.cpp
@@ -81,7 +81,7 @@ void warning(const char *l) {
 }
 
 void registerWindowForFatal() {
-	delete fatalInfo;
+	delete[] fatalInfo;
 	fatalInfo =
 			joinStrings("There's an error with this SLUDGE game! If you're designing this game, please turn on verbose error messages in the project manager and recompile. If not, please contact the author saying where and how this problem occured.", "");
 }
@@ -126,7 +126,7 @@ int checkNew(const void *mem) {
 }
 
 void setFatalInfo(const char *userFunc, const char *BIF) {
-	delete fatalInfo;
+	delete[] fatalInfo;
 	fatalInfo = new char[strlen(userFunc) + strlen(BIF) + 38];
 	if (fatalInfo)
 		sprintf(fatalInfo, "Currently in this sub: %s\nCalling: %s", userFunc, BIF);
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index e9c7243..4743649 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -266,7 +266,7 @@ bool initSludge(const char *filename) {
 
 	if (strcmp(checker, "okSoFar"))
 		return fatal(ERROR_BAD_HEADER, filename);
-	delete checker;
+	delete[] checker;
 	checker = NULL;
 
 	unsigned char customIconLogo = fp->readByte();
@@ -509,7 +509,7 @@ bool initSludge(const char *filename) {
 
 	char *gameName = encodeFilename(gameNameOrig);
 
-	delete gameNameOrig;
+	delete[] gameNameOrig;
 
 #if 0
 	changeToUserDir();
@@ -767,10 +767,10 @@ void finishFunction(loadedFunction *fun) {
 	pauseFunction(fun);
 	if (fun->stack)
 		fatal(ERROR_NON_EMPTY_STACK);
-	delete fun->compiledLines;
+	delete[] fun->compiledLines;
 	for (a = 0; a < fun->numLocals; a++)
 		unlinkVar(fun->localVars[a]);
-	delete fun->localVars;
+	delete[] fun->localVars;
 	unlinkVar(fun->reg);
 	delete fun;
 	fun = NULL;
@@ -785,7 +785,7 @@ void abortFunction(loadedFunction *fun) {
 	delete fun->compiledLines;
 	for (a = 0; a < fun->numLocals; a++)
 		unlinkVar(fun->localVars[a]);
-	delete fun->localVars;
+	delete[] fun->localVars;
 	unlinkVar(fun->reg);
 	if (fun->calledBy)
 		abortFunction(fun->calledBy);
diff --git a/engines/sludge/statusba.cpp b/engines/sludge/statusba.cpp
index 0ebe4e7..9af0f3f 100644
--- a/engines/sludge/statusba.cpp
+++ b/engines/sludge/statusba.cpp
@@ -78,7 +78,7 @@ void addStatusBar() {
 
 void setStatusBar(char *txt) {
 	if (nowStatus->firstStatusBar) {
-		delete nowStatus->firstStatusBar->text;
+		delete[] nowStatus->firstStatusBar->text;
 		nowStatus->firstStatusBar->text = copyString(txt);
 	}
 }
diff --git a/engines/sludge/talk.cpp b/engines/sludge/talk.cpp
index 162875c..7663d39 100644
--- a/engines/sludge/talk.cpp
+++ b/engines/sludge/talk.cpp
@@ -70,7 +70,7 @@ void killAllSpeech() {
 	while (speech->allSpeech) {
 		killMe = speech->allSpeech;
 		speech->allSpeech = speech->allSpeech->next;
-		delete killMe->textLine;
+		delete[] killMe->textLine;
 		delete killMe;
 	}
 }
diff --git a/engines/sludge/variable.cpp b/engines/sludge/variable.cpp
index 73e90f0..e811c65 100644
--- a/engines/sludge/variable.cpp
+++ b/engines/sludge/variable.cpp
@@ -336,14 +336,14 @@ char *getTextFromAnyVar(const variable &from) {
 				builder2 = joinStrings(builder, " ");
 				if (!builder2)
 					return NULL;
-				delete builder;
+				delete[] builder;
 				grabText = getTextFromAnyVar(stacky->thisVar);
 				builder = joinStrings(builder2, grabText);
 				if (!builder)
 					return NULL;
-				delete grabText;
+				delete[] grabText;
 				grabText = NULL;
-				delete builder2;
+				delete[] builder2;
 				builder2 = NULL;
 				stacky = stacky->next;
 			}


Commit: 78cba75570115cf598a0c6c27a660f1ae0e985d6
    https://github.com/scummvm/scummvm/commit/78cba75570115cf598a0c6c27a660f1ae0e985d6
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: change pixel formats to pointers and fix seg fault

Changed paths:
    engines/sludge/backdrop.cpp
    engines/sludge/builtin.cpp
    engines/sludge/hsi.cpp
    engines/sludge/imgloader.cpp
    engines/sludge/loadsave.cpp
    engines/sludge/sludge.cpp
    engines/sludge/sludge.h
    engines/sludge/sprites.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index 42b1c99..850a23d 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -69,7 +69,9 @@ int cameraPX = 0, cameraPY = 0;
 
 unsigned int sceneWidth, sceneHeight;
 int lightMapNumber;
-unsigned int currentBlankColour = g_sludge->getOrigPixelFormat().RGBToColor(0, 0, 0);
+#if 0
+unsigned int currentBlankColour = g_sludge->getOrigPixelFormat()->RGBToColor(0, 0, 0);
+#endif
 
 extern int cameraX, cameraY;
 extern float cameraZoom;
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 131a903..3ac316d 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -91,7 +91,9 @@ extern unsigned char brightnessLevel;
 extern unsigned char fadeMode;
 extern unsigned short saveEncoding;
 extern frozenStuffStruct *frozenStuff;
+#if 0
 extern unsigned int currentBlankColour;
+#endif
 extern unsigned int languageID;
 extern unsigned char currentBurnR, currentBurnG, currentBurnB;
 
@@ -848,8 +850,9 @@ builtIn(setBlankColour) {
 
 	if (!getRGBParams(red, green, blue, fun))
 		return BR_ERROR;
-
-	currentBlankColour = g_sludge->getOrigPixelFormat().RGBToColor(red & 255, green & 255, blue & 255);
+#if 0
+	currentBlankColour = g_sludge->getOrigPixelFormat()->RGBToColor(red & 255, green & 255, blue & 255);
+#endif
 	setVariable(fun->reg, SVT_INT, 1);
 	return BR_CONTINUE;
 }
diff --git a/engines/sludge/hsi.cpp b/engines/sludge/hsi.cpp
index 3ccdc14..6bb333f 100644
--- a/engines/sludge/hsi.cpp
+++ b/engines/sludge/hsi.cpp
@@ -55,7 +55,7 @@ bool HSIDecoder::loadStream(Common::SeekableReadStream &stream) {
 	debug(kSludgeDebugGraphics, "picHeight : %i", height);
 
 	_surface = new Graphics::Surface();
-	_surface->create(width, height, g_sludge->getScreenPixelFormat());
+	_surface->create(width, height, *g_sludge->getScreenPixelFormat());
 	for (uint16 y = 0; y < height; y++) {
 		uint16 x = 0;
 		while (x < width) {
@@ -75,7 +75,7 @@ bool HSIDecoder::loadStream(Common::SeekableReadStream &stream) {
 					target[3] = (byte)0;
 				} else {
 					target[0] = (byte)255;
-					g_sludge->getOrigPixelFormat().colorToRGB(c, target[3], target[2], target[1]);
+					g_sludge->getOrigPixelFormat()->colorToRGB(c, target[3], target[2], target[1]);
 				}
 				x++;
 			}
diff --git a/engines/sludge/imgloader.cpp b/engines/sludge/imgloader.cpp
index eef18ee..bfac7fa 100644
--- a/engines/sludge/imgloader.cpp
+++ b/engines/sludge/imgloader.cpp
@@ -49,7 +49,7 @@ bool ImgLoader::loadPNGImage(Common::SeekableReadStream *stream, Graphics::Surfa
 	if (!png.loadStream(*stream))
 		return false;
 	const Graphics::Surface *sourceSurface = png.getSurface();
-	Graphics::Surface *pngSurface = sourceSurface->convertTo(g_sludge->getScreenPixelFormat(), png.getPalette());
+	Graphics::Surface *pngSurface = sourceSurface->convertTo(*g_sludge->getScreenPixelFormat(), png.getPalette());
 	dest->copyFrom(*pngSurface);
 	pngSurface->free();
 	delete pngSurface;
diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index db6afb1..fb668b5 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -74,7 +74,9 @@ extern bool captureAllKeys;
 extern bool allowAnyFilename;
 extern unsigned short saveEncoding;                 // in savedata.cpp
 extern unsigned char currentBurnR, currentBurnG, currentBurnB;
+#if 0
 extern unsigned int currentBlankColour;             // in backdrop.cpp
+#endif
 extern parallaxLayer *parallaxStuff;                //      "
 extern int lightMapMode;                    //      "
 extern int languageNum;
diff --git a/engines/sludge/sludge.cpp b/engines/sludge/sludge.cpp
index 90bdd45..c4e3083 100644
--- a/engines/sludge/sludge.cpp
+++ b/engines/sludge/sludge.cpp
@@ -34,12 +34,8 @@ namespace Sludge {
 
 SludgeEngine *g_sludge;
 
-Graphics::PixelFormat SludgeEngine::getScreenPixelFormat() const { return _pixelFormat; }
-Graphics::PixelFormat SludgeEngine::getOrigPixelFormat() const {
-	return Graphics::PixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0);
-	//return _origFormat;
-	// TODO: get segmentation fault when returning _origFormat
-}
+Graphics::PixelFormat *SludgeEngine::getScreenPixelFormat() const { return _pixelFormat; }
+Graphics::PixelFormat *SludgeEngine::getOrigPixelFormat() const { return _origFormat; }
 
 SludgeEngine::SludgeEngine(OSystem *syst, const SludgeGameDescription *gameDesc) :
 		Engine(syst), _gameDescription(gameDesc), _console(nullptr) {
@@ -62,12 +58,20 @@ SludgeEngine::~SludgeEngine() {
 
 	// Dispose resources
 	delete _rnd;
+	_rnd = nullptr;
 
 	// Remove debug levels
 	DebugMan.clearAllDebugChannels();
 
 	// Dispose console
 	delete _console;
+	_console = nullptr;
+
+	// Dispose pixel formats
+	delete _origFormat;
+	_origFormat = nullptr;
+	delete _pixelFormat;
+	_pixelFormat = nullptr;
 }
 
 Common::Error SludgeEngine::run() {
@@ -75,9 +79,9 @@ Common::Error SludgeEngine::run() {
 	g_sludge = this;
 
 	// init graphics
-	_origFormat = Graphics::PixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0);
-	_pixelFormat = Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0);
-	initGraphics(640, 480, false, &_pixelFormat);
+	_origFormat = new Graphics::PixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0);
+	_pixelFormat = new Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0);
+	initGraphics(640, 480, false, _pixelFormat);
 
 	// create console
 	_console = new SludgeConsole(this);
diff --git a/engines/sludge/sludge.h b/engines/sludge/sludge.h
index 5fe09c3..5ec197f 100644
--- a/engines/sludge/sludge.h
+++ b/engines/sludge/sludge.h
@@ -60,8 +60,8 @@ public:
 	const char *getGameId() const;
 	uint32 getFeatures() const;
 	Common::Language getLanguage() const;
-	Graphics::PixelFormat getScreenPixelFormat() const;
-	Graphics::PixelFormat getOrigPixelFormat() const;
+	Graphics::PixelFormat *getScreenPixelFormat() const;
+	Graphics::PixelFormat *getOrigPixelFormat() const;
 
 	const char *getGameFile() const;
 
@@ -70,8 +70,8 @@ public:
 private:
 	SludgeConsole *_console;
 	Common::RandomSource *_rnd;
-	Graphics::PixelFormat _pixelFormat;
-	Graphics::PixelFormat _origFormat;
+	Graphics::PixelFormat *_pixelFormat;
+	Graphics::PixelFormat *_origFormat;
 };
 
 } // End of namespace Sludge
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index 3ea82c8..dbbf74c 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -181,9 +181,9 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 		}
 
 		// init data
-		loadhere.sprites[i].surface.create(picwidth, picheight, g_sludge->getScreenPixelFormat());
+		loadhere.sprites[i].surface.create(picwidth, picheight, *g_sludge->getScreenPixelFormat());
 		if (isFont) {
-			loadhere.sprites[i].burnSurface.create(picwidth, picheight, g_sludge->getScreenPixelFormat());
+			loadhere.sprites[i].burnSurface.create(picwidth, picheight, *g_sludge->getScreenPixelFormat());
 		}
 		data = (byte *)new byte[picwidth * (picheight + 1)];
 		if (!checkNew(data)) return false;
@@ -231,7 +231,7 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 		loadhere.myPalette.g[i + startIndex] = (byte)bigDataFile->readByte();
 		loadhere.myPalette.b[i + startIndex] = (byte)bigDataFile->readByte();
 		loadhere.myPalette.pal[i + startIndex] =
-				(uint16)g_sludge->getOrigPixelFormat().RGBToColor(
+				(uint16)g_sludge->getOrigPixelFormat()->RGBToColor(
 						loadhere.myPalette.r[i + startIndex],
 						loadhere.myPalette.g[i + startIndex],
 						loadhere.myPalette.b[i + startIndex]);


Commit: 09b4a0675e95e003ccea691f1c9e5a95aec4149c
    https://github.com/scummvm/scummvm/commit/09b4a0675e95e003ccea691f1c9e5a95aec4149c
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove value setting loop by memset

Changed paths:
    engines/sludge/sprites.cpp


diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index dbbf74c..b6701d4 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -187,10 +187,7 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 		}
 		data = (byte *)new byte[picwidth * (picheight + 1)];
 		if (!checkNew(data)) return false;
-		int ooo = picwidth * picheight;
-		for (int tt = 0; tt < picwidth; tt++) {
-			data[ooo++] = 0;
-		}
+		memset(data + picwidth * picheight, 0, picwidth);
 		spriteData[i] = data;
 
 		// read color


Commit: da842ee14ed6a91894449ab277f93289a8744dad
    https://github.com/scummvm/scummvm/commit/da842ee14ed6a91894449ab277f93289a8744dad
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove unused sound files and rename cpp

Changed paths:
  A engines/sludge/sound.cpp
  R engines/sludge/sound_bass.cpp
  R engines/sludge/sound_nosound.cpp
  R engines/sludge/sound_openal.cpp
    engines/sludge/module.mk


diff --git a/engines/sludge/module.mk b/engines/sludge/module.mk
index b091361..f1e4cad 100644
--- a/engines/sludge/module.mk
+++ b/engines/sludge/module.mk
@@ -30,7 +30,7 @@ MODULE_OBJS := \
 	savedata.o \
 	sludge.o \
 	sludger.o \
-	sound_openal.o \
+	sound.o \
 	sprbanks.o \
 	sprites.o \
 	statusba.o \
diff --git a/engines/sludge/sound.cpp b/engines/sludge/sound.cpp
new file mode 100644
index 0000000..360ad6d
--- /dev/null
+++ b/engines/sludge/sound.cpp
@@ -0,0 +1,833 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+#if 0
+#include "AL/alure.h"
+#endif
+
+#include "common/file.h"
+
+#include "sludge/allfiles.h"
+#include "sludge/debug.h"
+#include "sludge/newfatal.h"
+#include "sludge/sound.h"
+#include "sludge/moreio.h"
+#include "sludge/fileset.h"
+
+#define MAX_SAMPLES 8
+#define MAX_MODS 3
+#define NUM_BUFS 3
+
+namespace Sludge {
+
+bool soundOK = false;
+bool cacheLoopySound = false;
+bool SilenceIKillYou = false;
+
+struct soundThing {
+#if 0
+	alureStream *stream;
+	ALuint playingOnSource;
+#endif
+	bool playing;
+	int fileLoaded, vol;    //Used for sounds only.
+	bool looping;           //Used for sounds only.
+};
+
+soundThing soundCache[MAX_SAMPLES];
+soundThing modCache[MAX_MODS];
+int intpointers[MAX_SAMPLES];
+
+int defVol = 128;
+int defSoundVol = 255;
+const float modLoudness = 0.95f;
+
+/*
+ * Set up, tear down:
+ */
+
+bool initSoundStuff(HWND hwnd) {
+#if 0
+	if (!alureInitDevice(NULL, NULL)) {
+		debugOut("Failed to open OpenAL device: %s\n", alureGetErrorString());
+		return 1;
+	}
+
+	int a;
+	for (a = 0; a < MAX_SAMPLES; a ++) {
+		soundCache[a].stream = NULL;
+		soundCache[a].playing = false;
+		soundCache[a].fileLoaded = -1;
+		soundCache[a].looping = false;
+		intpointers[a] = a;
+	}
+
+	for (a = 0; a < MAX_MODS; a ++) {
+		modCache[a].stream = NULL;
+		modCache[a].playing = false;
+	}
+
+	if (! alureUpdateInterval(0.01)) {
+		debugOut("Failed to set Alure update interval: %s\n", alureGetErrorString());
+		return 1;
+	}
+#endif
+	return soundOK = true;
+}
+
+void killSoundStuff() {
+	if (!soundOK)
+		return;
+#if 0
+	SilenceIKillYou = true;
+	for (int i = 0; i < MAX_SAMPLES; i ++) {
+		if (soundCache[i].playing) {
+
+			if (! alureStopSource(soundCache[i].playingOnSource, AL_TRUE)) {
+				debugOut("Failed to stop source: %s\n",
+						alureGetErrorString());
+			}
+
+		}
+
+		if (soundCache[i].stream != NULL) {
+
+			if (! alureDestroyStream(soundCache[i].stream, 0, NULL)) {
+				debugOut("Failed to destroy stream: %s\n",
+						alureGetErrorString());
+			}
+
+		}
+	}
+
+	for (int i = 0; i < MAX_MODS; i ++) {
+		if (modCache[i].playing) {
+
+			if (! alureStopSource(modCache[i].playingOnSource, AL_TRUE)) {
+				debugOut("Failed to stop source: %s\n",
+						alureGetErrorString());
+			}
+
+		}
+
+		if (modCache[i].stream != NULL) {
+
+			if (! alureDestroyStream(modCache[i].stream, 0, NULL)) {
+				debugOut("Failed to destroy stream: %s\n",
+						alureGetErrorString());
+			}
+
+		}
+	}
+
+	SilenceIKillYou = false;
+
+	alureShutdownDevice();
+#endif
+}
+
+/*
+ * Some setters:
+ */
+
+void setMusicVolume(int a, int v) {
+	if (!soundOK)
+		return;
+
+	if (modCache[a].playing) {
+#if 0
+		alSourcef(modCache[a].playingOnSource, AL_GAIN, (float) modLoudness * v / 256);
+#endif
+	}
+}
+
+void setDefaultMusicVolume(int v) {
+	defVol = v;
+}
+
+void setSoundVolume(int a, int v) {
+	if (!soundOK)
+		return;
+	int ch = findInSoundCache(a);
+	if (ch != -1) {
+		if (soundCache[ch].playing) {
+			soundCache[ch].vol = v;
+#if 0
+			alSourcef(soundCache[ch].playingOnSource, AL_GAIN, (float) v / 256);
+#endif
+		}
+	}
+}
+
+void setDefaultSoundVolume(int v) {
+	defSoundVol = v;
+}
+
+void setSoundLoop(int a, int s, int e) {
+//#pragma unused (a,s,e)
+}
+
+/*
+ * End of stream callbacks:
+ */
+
+#if 0
+static void sound_eos_callback(void *cacheIndex, ALuint source) {
+	int *a = (int *)cacheIndex;
+
+	alDeleteSources(1, &source);
+	if (alGetError() != AL_NO_ERROR) {
+		debugOut("Failed to delete OpenAL source!\n");
+	}
+
+	soundCache[*a].playingOnSource = 0;
+	soundCache[*a].playing = false;
+	soundCache[*a].looping = false;
+
+}
+#endif
+
+#if 0
+static void mod_eos_callback(void *cacheIndex, ALuint source) {
+	int *a = (int *)cacheIndex;
+
+	alDeleteSources(1, &source);
+	if (alGetError() != AL_NO_ERROR) {
+		debugOut("Failed to delete OpenAL source!\n");
+	}
+
+	modCache[*a].playingOnSource = 0;
+
+	if (! alureDestroyStream(modCache[*a].stream, 0, NULL)) {
+		debugOut("Failed to destroy stream: %s\n",
+				alureGetErrorString());
+	}
+
+	modCache[*a].stream = NULL;
+	modCache[*a].playing = false;
+}
+#endif
+
+/*
+ * Stopping things:
+ */
+
+int findInSoundCache(int a) {
+	int i;
+	for (i = 0; i < MAX_SAMPLES; i++) {
+		if (soundCache[i].fileLoaded == a) {
+			return i;
+		}
+	}
+	return -1;
+}
+
+void stopMOD(int i) {
+	if (!soundOK)
+		return;
+#if 0
+	alGetError();
+	if (modCache[i].playing) {
+		if (! alureStopSource(modCache[i].playingOnSource, AL_TRUE)) {
+			debugOut("Failed to stop source: %s\n", alureGetErrorString());
+		}
+	}
+#endif
+}
+
+void huntKillSound(int filenum) {
+	if (!soundOK)
+		return;
+#if 0
+	// Clear OpenAL errors to make sure they don't block anything:
+	alGetError();
+
+	int gotSlot = findInSoundCache(filenum);
+	if (gotSlot == -1) return;
+
+	SilenceIKillYou = true;
+
+	if (soundCache[gotSlot].playing) {
+		if (! alureStopSource(soundCache[gotSlot].playingOnSource, AL_TRUE)) {
+			debugOut("Failed to stop source: %s\n", alureGetErrorString());
+		}
+	}
+#endif
+	SilenceIKillYou = false;
+}
+
+void freeSound(int a) {
+	if (!soundOK)
+		return;
+#if 0
+	// Clear OpenAL errors to make sure they don't block anything:
+	alGetError();
+
+	SilenceIKillYou = true;
+
+	if (soundCache[a].playing) {
+		if (! alureStopSource(soundCache[a].playingOnSource, AL_TRUE)) {
+			debugOut("Failed to stop source: %s\n",
+					alureGetErrorString());
+		}
+	}
+	if (! alureDestroyStream(soundCache[a].stream, 0, NULL)) {
+		debugOut("Failed to destroy stream: %s\n",
+				alureGetErrorString());
+	}
+
+	soundCache[a].stream = NULL;
+	soundCache[a].fileLoaded = -1;
+#endif
+	SilenceIKillYou = false;
+}
+
+void huntKillFreeSound(int filenum) {
+	if (!soundOK)
+		return;
+	int gotSlot = findInSoundCache(filenum);
+	if (gotSlot == -1)
+		return;
+	freeSound(gotSlot);
+}
+
+/*
+ * Loading and playing:
+ */
+
+void playStream(int a, bool isMOD, bool loopy) {
+#if 0
+	if (! soundOK) return;
+	ALboolean ok;
+	ALuint src;
+	soundThing *st;
+	void (*eos_callback)(void *userdata, ALuint source);
+
+	if (isMOD) {
+		st = &modCache[a];
+		eos_callback = mod_eos_callback;
+	} else {
+		st = &soundCache[a];
+		eos_callback = sound_eos_callback;
+	}
+
+	alGenSources(1, &src);
+	if (alGetError() != AL_NO_ERROR) {
+		debugOut("Failed to create OpenAL source!\n");
+		return;
+	}
+
+	if (isMOD) {
+		alSourcef(src, AL_GAIN, (float) modLoudness * defVol / 256);
+	} else {
+		alSourcef(src, AL_GAIN, (float) soundCache[a].vol / 256);
+	}
+
+	if (loopy) {
+		ok = alurePlaySourceStream(src, (*st).stream,
+				NUM_BUFS, -1, eos_callback, &intpointers[a]);
+	} else {
+		ok = alurePlaySourceStream(src, (*st).stream,
+				NUM_BUFS, 0, eos_callback, &intpointers[a]);
+	}
+
+	if (!ok) {
+
+		debugOut("Failed to play stream: %s\n", alureGetErrorString());
+		alDeleteSources(1, &src);
+		if (alGetError() != AL_NO_ERROR) {
+			debugOut("Failed to delete OpenAL source!\n");
+		}
+
+		(*st).playingOnSource = 0;
+	} else {
+		(*st).playingOnSource = src;
+		(*st).playing = true;
+	}
+#endif
+}
+
+char *loadEntireFileToMemory(Common::SeekableReadStream *inputFile,
+		uint32 size) {
+	char *allData = new char[size];
+	if (!allData)
+		return NULL;
+
+	size_t bytes_read = inputFile->read(allData, size);
+	if (bytes_read != size && inputFile->err()) {
+		debugOut("Reading error in loadEntireFileToMemory.\n");
+	}
+
+	finishAccess();
+
+	return allData;
+}
+
+bool playMOD(int f, int a, int fromTrack) {
+	if (!soundOK)
+		return true;
+	stopMOD(a);
+
+	setResourceForFatal(f);
+	uint32 length = openFileFromNum(f);
+	if (length == 0) {
+		finishAccess();
+		setResourceForFatal(-1);
+		return false;
+	}
+#if 0
+	unsigned char *memImage;
+	memImage = (unsigned char *) loadEntireFileToMemory(bigDataFile, length);
+	if (! memImage) return fatal(ERROR_MUSIC_MEMORY_LOW);
+
+	modCache[a].stream = alureCreateStreamFromMemory(memImage, length, 19200, 0, NULL);
+
+	delete memImage;
+
+	if (modCache[a].stream != NULL) {
+		setMusicVolume(a, defVol);
+
+		if (! alureSetStreamOrder(modCache[a].stream, fromTrack)) {
+			debugOut("Failed to set stream order: %s\n",
+					alureGetErrorString());
+		}
+
+		playStream(a, true, true);
+
+	} else {
+
+		debugOut("Failed to create stream from MOD: %s\n",
+				alureGetErrorString());
+
+		warning(ERROR_MUSIC_ODDNESS);
+		soundCache[a].stream = NULL;
+		soundCache[a].playing = false;
+		soundCache[a].playingOnSource = 0;
+	}
+	setResourceForFatal(-1);
+#endif
+	return true;
+}
+
+bool stillPlayingSound(int ch) {
+	if (soundOK)
+		if (ch != -1)
+			if (soundCache[ch].fileLoaded != -1)
+				if (soundCache[ch].playing)
+					return true;
+
+	return false;
+}
+
+bool forceRemoveSound() {
+	for (int a = 0; a < MAX_SAMPLES; a++) {
+		if (soundCache[a].fileLoaded != -1 && !stillPlayingSound(a)) {
+//			soundWarning ("Deleting silent sound", a);
+			freeSound(a);
+			return 1;
+		}
+	}
+
+	for (int a = 0; a < MAX_SAMPLES; a++) {
+		if (soundCache[a].fileLoaded != -1) {
+//			soundWarning ("Deleting playing sound", a);
+			freeSound(a);
+			return 1;
+		}
+	}
+//	soundWarning ("Cache is empty!", 0);
+	return 0;
+}
+
+int emptySoundSlot = 0;
+
+int findEmptySoundSlot() {
+	int t;
+	for (t = 0; t < MAX_SAMPLES; t++) {
+		emptySoundSlot++;
+		emptySoundSlot %= MAX_SAMPLES;
+#if 0
+		if (soundCache[emptySoundSlot].stream == NULL)
+		return emptySoundSlot;
+#endif
+	}
+
+	for (t = 0; t < MAX_SAMPLES; t++) {
+		emptySoundSlot++;
+		emptySoundSlot %= MAX_SAMPLES;
+		if (!soundCache[emptySoundSlot].playing)
+			return emptySoundSlot;
+	}
+
+	// Argh! They're all playing! Let's trash the oldest that's not looping...
+
+	for (t = 0; t < MAX_SAMPLES; t++) {
+		emptySoundSlot++;
+		emptySoundSlot %= MAX_SAMPLES;
+		if (!soundCache[emptySoundSlot].looping)
+			return emptySoundSlot;
+	}
+
+	// Holy crap, they're all looping! What's this twat playing at?
+
+	emptySoundSlot++;
+	emptySoundSlot %= MAX_SAMPLES;
+	return emptySoundSlot;
+}
+
+int cacheSound(int f) {
+
+	if (!soundOK)
+		return -1;
+
+	unsigned int chunkLength;
+	int retval;
+	bool loopy;
+#if 0
+	loopy = cacheLoopySound;
+	cacheLoopySound = false;
+
+	setResourceForFatal(f);
+
+	if (! soundOK) return 0;
+
+	int a = findInSoundCache(f);
+	if (a != -1) {
+
+		if (soundCache[a].playing) {
+			if (! alureStopSource(soundCache[a].playingOnSource, AL_TRUE)) {
+				debugOut("Failed to stop source: %s\n",
+						alureGetErrorString());
+			}
+		}
+		if (! alureRewindStream(soundCache[a].stream)) {
+			debugOut("Failed to rewind stream: %s\n",
+					alureGetErrorString());
+		}
+
+		return a;
+	}
+	if (f == -2) return -1;
+	a = findEmptySoundSlot();
+	freeSound(a);
+
+	uint32 length = openFileFromNum(f);
+	if (! length) return -1;
+
+	unsigned char *memImage;
+
+	bool tryAgain = true;
+
+	while (tryAgain) {
+		memImage = (unsigned char *)loadEntireFileToMemory(bigDataFile, length);
+		tryAgain = memImage == NULL;
+		if (tryAgain) {
+			if (! forceRemoveSound()) {
+				fatal(ERROR_SOUND_MEMORY_LOW);
+				return -1;
+			}
+		}
+	}
+
+	chunkLength = 19200;
+
+	// Small looping sounds need small chunklengths.
+	if (loopy) {
+		if (length < NUM_BUFS * chunkLength) {
+			chunkLength = length / NUM_BUFS;
+		}
+	} else if (length < chunkLength) {
+		chunkLength = length;
+	}
+
+	soundCache[a].stream = alureCreateStreamFromMemory(memImage, length, chunkLength, 0, NULL);
+
+	delete[] memImage;
+
+	if (soundCache[a].stream != NULL) {
+		soundCache[a].fileLoaded = f;
+		setResourceForFatal(-1);
+		retval = a;
+	} else {
+
+		debugOut("Failed to create stream from sound: %s\n",
+				alureGetErrorString());
+
+		warning(ERROR_SOUND_ODDNESS);
+		soundCache[a].stream = NULL;
+		soundCache[a].playing = false;
+		soundCache[a].playingOnSource = 0;
+		soundCache[a].fileLoaded = -1;
+		soundCache[a].looping = false;
+		retval = -1;
+	}
+#endif
+	return retval;
+}
+
+bool startSound(int f, bool loopy) {
+	if (soundOK) {
+#if 0
+		cacheLoopySound = loopy;
+		int a = cacheSound(f);
+		if (a == -1) {
+			debugOut("Failed to cache sound!\n");
+			return false;
+		}
+		soundCache[a].looping = loopy;
+		soundCache[a].vol = defSoundVol;
+
+		playStream(a, false, loopy);
+#endif
+	}
+	return true;
+}
+
+void saveSounds(Common::WriteStream *stream) {
+	if (soundOK) {
+		for (int i = 0; i < MAX_SAMPLES; i++) {
+			if (soundCache[i].looping) {
+				stream->writeByte(1);
+				stream->writeUint16BE(soundCache[i].fileLoaded);
+				stream->writeUint16BE(soundCache[i].vol);
+			}
+		}
+	}
+	stream->writeByte(0);
+	stream->writeUint16BE(defSoundVol);
+	stream->writeUint16BE(defVol);
+}
+
+void loadSounds(Common::SeekableReadStream *stream) {
+	for (int i = 0; i < MAX_SAMPLES; i++)
+		freeSound(i);
+
+	while (stream->readByte()) {
+		int fileLoaded = stream->readUint16BE();
+		defSoundVol = stream->readUint16BE();
+		startSound(fileLoaded, 1);
+	}
+
+	defSoundVol = stream->readUint16BE();
+	defVol = stream->readUint16BE();
+}
+
+bool getSoundCacheStack(stackHandler *sH) {
+	variable newFileHandle;
+	newFileHandle.varType = SVT_NULL;
+
+	for (int a = 0; a < MAX_SAMPLES; a++) {
+		if (soundCache[a].fileLoaded != -1) {
+			setVariable(newFileHandle, SVT_FILE, soundCache[a].fileLoaded);
+			if (!addVarToStackQuick(newFileHandle, sH->first))
+				return false;
+			if (sH->last == NULL)
+				sH->last = sH->first;
+		}
+	}
+	return true;
+}
+
+soundList *deleteSoundFromList(soundList *s) {
+	// Don't delete a playing sound.
+	if (s->cacheIndex)
+		return NULL;
+
+	soundList *o = NULL;
+	if (!s->next) {
+		o = s->prev;
+		if (o)
+			o->next = NULL;
+		delete s;
+		return o;
+	}
+	if (s != s->next) {
+		o = s->next;
+		o->prev = s->prev;
+		if (o->prev)
+			o->prev->next = o;
+	}
+	delete s;
+	return o;
+}
+
+#if 0
+static void list_eos_callback(void *list, ALuint source) {
+	soundList *s = (soundList *) list;
+
+	int a = s->cacheIndex;
+#if 0
+	alDeleteSources(1, &source);
+	if (alGetError() != AL_NO_ERROR) {
+		debugOut("Failed to delete OpenAL source!\n");
+	}
+#endif
+	soundCache[a].playingOnSource = 0;
+	soundCache[a].playing = false;
+	soundCache[a].looping = false;
+	s-> cacheIndex = false;
+	if (SilenceIKillYou) {
+		while (s = deleteSoundFromList(s));
+	} else {
+		if (s->next) {
+			if (s->next == s) {
+				int v = defSoundVol;
+				defSoundVol = soundCache[a].vol;
+				startSound(s->sound, true);
+				defSoundVol = v;
+				while (s = deleteSoundFromList(s));
+				return;
+			}
+			s->next->vol = soundCache[a].vol;
+			playSoundList(s->next);
+		} else {
+			while (s = deleteSoundFromList(s));
+		}
+	}
+}
+#endif
+
+void playSoundList(soundList *s) {
+#if 0
+	if (soundOK) {
+		cacheLoopySound = true;
+		int a = cacheSound(s->sound);
+		if (a == -1) {
+			debugOut("Failed to cache sound!\n");
+			return;
+		}
+		soundCache[a].looping = false;
+		if (s->vol < 0)
+		soundCache[a].vol = defSoundVol;
+		else
+		soundCache[a].vol = s->vol;
+		s-> cacheIndex = a;
+
+		ALboolean ok;
+		ALuint src;
+		soundThing *st;
+
+		st = &soundCache[a];
+
+		alGenSources(1, &src);
+		if (alGetError() != AL_NO_ERROR) {
+			debugOut("Failed to create OpenAL source!\n");
+			return;
+		}
+
+		alSourcef(src, AL_GAIN, (float) soundCache[a].vol / 256);
+
+		ok = alurePlaySourceStream(src, (*st).stream,
+				NUM_BUFS, 0, list_eos_callback, s);
+
+		if (!ok) {
+
+			debugOut("Failed to play stream: %s\n", alureGetErrorString());
+			alDeleteSources(1, &src);
+			if (alGetError() != AL_NO_ERROR) {
+				debugOut("Failed to delete OpenAL source!\n");
+			}
+
+			(*st).playingOnSource = 0;
+		} else {
+			(*st).playingOnSource = src;
+			(*st).playing = true;
+		}
+	}
+#endif
+}
+
+void playMovieStream(int a) {
+#if 0
+	if (! soundOK) return;
+	ALboolean ok;
+	ALuint src;
+
+	alGenSources(1, &src);
+	if (alGetError() != AL_NO_ERROR) {
+		debugOut("Failed to create OpenAL source!\n");
+		return;
+	}
+
+	alSourcef(src, AL_GAIN, (float) soundCache[a].vol / 256);
+
+	ok = alurePlaySourceStream(src, soundCache[a].stream,
+			10, 0, sound_eos_callback, &intpointers[a]);
+	if (!ok) {
+		debugOut("Failed to play stream: %s\n", alureGetErrorString());
+		alDeleteSources(1, &src);
+		if (alGetError() != AL_NO_ERROR) {
+			debugOut("Failed to delete OpenAL source!\n");
+		}
+
+		soundCache[a].playingOnSource = 0;
+	} else {
+		soundCache[a].playingOnSource = src;
+		soundCache[a].playing = true;
+	}
+#endif
+}
+
+#if 0
+int initMovieSound(int f, ALenum format, int audioChannels, ALuint samplerate,
+		ALuint(*callback)(void *userdata, ALubyte *data, ALuint bytes)) {
+	if (! soundOK) return 0;
+
+	int retval;
+	int a = findEmptySoundSlot();
+	freeSound(a);
+
+	soundCache[a].looping = false;
+#if 0
+	// audioChannel * sampleRate gives us a buffer of half a second. Not much, but it should be enough.
+	soundCache[a].stream = alureCreateStreamFromCallback(
+			callback,
+			&intpointers[a], format, samplerate,
+			audioChannels * samplerate, 0, NULL);
+#endif
+	if (soundCache[a].stream != NULL) {
+		soundCache[a].fileLoaded = f;
+		soundCache[a].vol = defSoundVol;
+		retval = a;
+	} else {
+#if 0
+		debugOut("Failed to create stream from sound: %s\n",
+				alureGetErrorString());
+#endif
+		warning(ERROR_SOUND_ODDNESS);
+		soundCache[a].stream = NULL;
+		soundCache[a].playing = false;
+		soundCache[a].playingOnSource = 0;
+		soundCache[a].fileLoaded = -1;
+		retval = -1;
+	}
+	//fprintf (stderr, "Stream %d created. Sample rate: %d Channels: %d\n", retval, samplerate, audioChannels);
+
+	return retval;
+}
+#endif
+
+unsigned int getSoundSource(int index) {
+	return 0; /*soundCache[index].playingOnSource;*/ //TODO:false value
+}
+
+} // End of namespace Sludge
diff --git a/engines/sludge/sound_bass.cpp b/engines/sludge/sound_bass.cpp
deleted file mode 100644
index d85981e..0000000
--- a/engines/sludge/sound_bass.cpp
+++ /dev/null
@@ -1,409 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-
-#include "sludge/allfiles.h"
-#include "sludge/newfatal.h"
-#include "sludge/sound.h"
-#include "sludge/moreio.h"
-#include "sludge/fileset.h"
-
-#define MAX_SAMPLES 8
-#define MAX_MODS 3
-#define EFFECT_CHANNELS 8
-#define TOTAL_CHANNELS 32
-
-namespace Sludge {
-
-bool soundOK = false;
-
-struct soundThing {
-	HSAMPLE sample;
-	int fileLoaded, vol;
-	int mostRecentChannel;
-	bool looping;
-};
-
-DWORD mod[MAX_MODS];
-
-soundThing soundCache[MAX_SAMPLES];
-
-int defVol = 128;
-int defSoundVol = 255;
-
-char *loadEntireFileToMemory(Common::SeekableReadStream *inputFile, uint32 size) {
-	char *allData = new char[size];
-	if (!allData)
-		return NULL;
-	inputFile->read(allData, size);
-	finishAccess();
-
-	return allData;
-}
-
-void stopMOD(int i) {
-	if (mod[i]) {
-		BASS_ChannelStop(mod[i]);
-		BASS_MusicFree(mod[i]);
-		mod[i] = NULL;
-	}
-}
-
-int findInSoundCache(int a) {
-	int i;
-	for (i = 0; i < MAX_SAMPLES; i++) {
-		if (soundCache[i].fileLoaded == a)
-			return i;
-	}
-	return -1;
-}
-
-void huntKillSound(int filenum) {
-	int gotSlot = findInSoundCache(filenum);
-	if (gotSlot == -1)
-		return;
-	soundCache[gotSlot].looping = false;
-	BASS_SampleStop(soundCache[gotSlot].sample);
-}
-
-void freeSound(int a) {
-	BASS_SampleFree(soundCache[a].sample);
-	soundCache[a].sample = NULL;
-	soundCache[a].fileLoaded = -1;
-	soundCache[a].looping = false;
-}
-
-void huntKillFreeSound(int filenum) {
-	int gotSlot = findInSoundCache(filenum);
-	if (gotSlot != -1)
-		freeSound(gotSlot);
-}
-
-bool initSoundStuff(HWND hwnd) {
-	if (HIWORD(BASS_GetVersion()) != BASSVERSION) {
-		warning(WARNING_BASS_WRONG_VERSION);
-		return false;
-	}
-
-	if (!BASS_Init(-1, 44100, 0, hwnd, NULL)) {
-		warning(WARNING_BASS_FAIL);
-		return false;
-	}
-
-	int a;
-	for (a = 0; a < MAX_SAMPLES; a ++) {
-		soundCache[a].sample = NULL;
-		soundCache[a].fileLoaded = -1;
-	}
-
-	BASS_SetConfig(BASS_CONFIG_GVOL_MUSIC, 10000);
-	BASS_SetConfig(BASS_CONFIG_GVOL_SAMPLE, 10000);
-	BASS_SetConfig(BASS_CONFIG_GVOL_STREAM, 10000);
-	return soundOK = true;
-}
-
-void killSoundStuff() {
-	if (soundOK) {
-		int a;
-		for (a = 0; a < MAX_MODS; a++)
-			stopMOD(a);
-		for (a = 0; a < MAX_SAMPLES; a++)
-			freeSound(a);
-		BASS_Free();
-	}
-}
-
-bool playMOD(int f, int a, int fromTrack) {
-	if (soundOK) {
-
-		stopMOD(a);
-
-		setResourceForFatal(f);
-		uint32 length = openFileFromNum(f);
-		if (length == 0)
-			return NULL;
-
-		char *memImage;
-		memImage = loadEntireFileToMemory(bigDataFile, length);
-		if (!memImage)
-			return fatal(ERROR_MUSIC_MEMORY_LOW);
-
-		mod[a] = BASS_MusicLoad(true, memImage, 0, length, BASS_MUSIC_LOOP | BASS_MUSIC_RAMP/*|BASS_MUSIC_PRESCAN needed too if we're going to set the position in bytes*/, 0);
-		delete memImage;
-
-		if (!mod[a]) {
-
-		} else {
-			setMusicVolume(a, defVol);
-
-			if (!BASS_ChannelPlay(mod[a], true))
-				debugOut("playMOD: Error %d!\n", BASS_ErrorGetCode());
-
-			BASS_ChannelSetPosition(mod[a], MAKELONG(fromTrack, 0), BASS_POS_MUSIC_ORDER);
-			BASS_ChannelFlags(mod[a], BASS_SAMPLE_LOOP | BASS_MUSIC_RAMP, BASS_SAMPLE_LOOP | BASS_MUSIC_RAMP);
-		}
-		setResourceForFatal(-1);
-	}
-	return true;
-}
-
-void setMusicVolume(int a, int v) {
-	int ret;
-	if (soundOK && mod[a]) {
-		ret = BASS_ChannelSetAttribute(mod[a], BASS_ATTRIB_VOL, (float)v / 256);
-		if (!ret) {
-			debugOut("setMusicVolume: Error %d\n", BASS_ErrorGetCode());
-		}
-	}
-}
-
-void setDefaultMusicVolume(int v) {
-	defVol = v;
-}
-
-void setSoundVolume(int a, int v) {
-	if (soundOK) {
-		int ch = findInSoundCache(a);
-		if (ch != -1) {
-			if (BASS_ChannelIsActive(soundCache[ch].mostRecentChannel)) {
-				BASS_ChannelSetAttribute(soundCache[ch].mostRecentChannel, BASS_ATTRIB_VOL, (float)v / 256);
-			}
-		}
-	}
-}
-
-bool stillPlayingSound(int ch) {
-	if (soundOK)
-		if (ch != -1)
-			if (soundCache[ch].fileLoaded != -1)
-				if (BASS_ChannelIsActive(soundCache[ch].mostRecentChannel) != BASS_ACTIVE_STOPPED)
-					return true;
-	return false;
-}
-
-void setSoundLoop(int a, int s, int e) {
-//	if (soundOK) {
-//		int ch = findInSoundCache (a);
-//		if (ch != -1) {
-//			int en = FSOUND_Sample_GetLength (soundCache[ch].sample);
-//			if (e < 1 || e >= en) e = en - 1;
-//			if (s < 0 || s >= e) s = 0;
-//
-//			FSOUND_Sample_SetLoopPoints (soundCache[ch].sample, s, e);
-//		}
-//	}
-}
-
-void setDefaultSoundVolume(int v) {
-	defSoundVol = v;
-}
-
-int emptySoundSlot = 0;
-
-int findEmptySoundSlot() {
-	int t;
-	for (t = 0; t < MAX_SAMPLES; t++) {
-		emptySoundSlot++;
-		emptySoundSlot %= MAX_SAMPLES;
-		if (!soundCache[emptySoundSlot].sample)
-			return emptySoundSlot;
-	}
-
-	// Argh!They're all playing!Let's trash the oldest that's not looping...
-
-	for (t = 0; t < MAX_SAMPLES; t++) {
-		emptySoundSlot++;
-		emptySoundSlot %= MAX_SAMPLES;
-		if (!soundCache[emptySoundSlot].looping)
-			return emptySoundSlot;
-	}
-
-	// Holy crap, they're all looping!What's this twat playing at?
-
-	emptySoundSlot++;
-	emptySoundSlot %= MAX_SAMPLES;
-	return emptySoundSlot;
-}
-
-int guessSoundFree = 0;
-
-/*
- void soundWarning (char * t, int i) {
- FILE * u = fopen ("soundlog.txt", "at");
- fprintf (u, "%s: %i\n", t, i);
- fclose (u);
- }
- */
-
-bool forceRemoveSound() {
-	for (int a = 0; a < 8; a++) {
-		if (soundCache[a].fileLoaded != -1 && !stillPlayingSound(a)) {
-//			soundWarning ("Deleting silent sound", a);
-			freeSound(a);
-			return 1;
-		}
-	}
-
-	for (int a = 0; a < 8; a++) {
-		if (soundCache[a].fileLoaded != -1) {
-//			soundWarning ("Deleting playing sound", a);
-			freeSound(a);
-			return 1;
-		}
-	}
-//	soundWarning ("Cache is empty!", 0);
-	return 0;
-}
-
-int cacheSound(int f) {
-	setResourceForFatal(f);
-
-	if (!soundOK)
-		return 0;
-
-	int a = findInSoundCache(f);
-	if (a != -1)
-		return a;
-	if (f == -2)
-		return -1;
-	a = findEmptySoundSlot();
-	freeSound(a);
-
-	uint32 length = openFileFromNum(f);
-	if (!length)
-		return -1;
-
-	char *memImage;
-
-	bool tryAgain = true;
-
-	while (tryAgain) {
-		memImage = loadEntireFileToMemory(bigDataFile, length);
-		tryAgain = memImage == NULL;
-		if (tryAgain) {
-			if (!forceRemoveSound()) {
-				fatal(ERROR_SOUND_MEMORY_LOW);
-				return -1;
-			}
-		}
-	}
-
-	for (;;) {
-//		soundWarning ("  Trying to load sound into slot", a);
-		soundCache[a].sample = BASS_SampleLoad(true, memImage, 0, length, 65535, 0);
-
-		if (soundCache[a].sample) {
-			soundCache[a].fileLoaded = f;
-			delete memImage;
-			setResourceForFatal(-1);
-			return a;
-		}
-
-		warning(ERROR_SOUND_ODDNESS);
-		soundCache[a].sample = NULL;
-		soundCache[a].fileLoaded = -1;
-		soundCache[a].looping = false;
-		return -1;
-	}
-}
-
-bool startSound(int f, bool loopy) {
-	if (soundOK) {
-		int a = cacheSound(f);
-		if (a == -1)
-			return false;
-
-		soundCache[a].looping = loopy;
-		soundCache[a].vol = defSoundVol;
-
-		soundCache[a].mostRecentChannel = BASS_SampleGetChannel(soundCache[a].sample, false);
-		if (soundCache[a].mostRecentChannel) {
-			BASS_ChannelPlay(soundCache[a].mostRecentChannel, true);
-			BASS_ChannelSetAttribute(soundCache[a].mostRecentChannel, BASS_ATTRIB_VOL, defSoundVol);
-			if (loopy) {
-				BASS_ChannelFlags(soundCache[a].mostRecentChannel, BASS_SAMPLE_LOOP, BASS_SAMPLE_LOOP); // set LOOP flag
-			}
-		}
-
-	}
-	return true;
-}
-
-/*
- void debugSounds () {
- FILE * fp = fopen ("newdebug.txt", "at");
- if (fp) {
- for (int aa = 0; aa < 32; aa ++) {
- if (aa == EFFECT_CHANNELS) fprintf (fp, "|");
- fprintf (fp, FSOUND_IsPlaying (aa) ? "#" : ".");
- }
- fprintf (fp, "\n");
- fclose (fp);
- }
- }
- // */
-
-void saveSounds(Common::WriteStream *stream) {
-	if (soundOK) {
-		for (int i = 0; i < MAX_SAMPLES; i++) {
-			if (soundCache[i].looping) {
-				stream->writeByte(1);
-				stream->writeUint16BE(soundCache[i].fileLoaded);
-				stream->writeUint16BE(soundCache[i].vol);
-			}
-		}
-	}
-	stream->writeByte(0);
-	stream->writeUint16BE(defSoundVol);
-	stream->writeUint16BE(defVol);
-}
-
-void loadSounds(Common::SeekableReadStream *stream) {
-	for (int i = 0; i < MAX_SAMPLES; i++)
-		freeSound(i);
-
-	while (stream->readByte()) {
-		int fileLoaded = stream->readUint16BE();
-		defSoundVol = stream->readUint16BE();
-		startSound(fileLoaded, 1);
-	}
-
-	defSoundVol = stream->readUint16BE();
-	defVol = stream->readUint16BE();
-}
-
-bool getSoundCacheStack(stackHandler *sH) {
-	variable newFileHandle;
-	newFileHandle.varType = SVT_NULL;
-
-	for (int a = 0; a < MAX_SAMPLES; a++) {
-		if (soundCache[a].fileLoaded != -1) {
-			setVariable(newFileHandle, SVT_FILE, soundCache[a].fileLoaded);
-			if (!addVarToStackQuick(newFileHandle, sH->first))
-				return false;
-			if (sH->last == NULL)
-				sH->last = sH->first;
-		}
-	}
-	return true;
-}
-
-} // End of namespace Sludge
diff --git a/engines/sludge/sound_nosound.cpp b/engines/sludge/sound_nosound.cpp
deleted file mode 100644
index 46b6963..0000000
--- a/engines/sludge/sound_nosound.cpp
+++ /dev/null
@@ -1,137 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-
-#include "sludge/allfiles.h"
-#include "sludge/newfatal.h"
-#include "sludge/sound.h"
-#include "sludge/moreio.h"
-#include "sludge/fileset.h"
-
-namespace Sludge {
-
-bool soundOK = false;
-
-int defVol = 128;
-int defSoundVol = 255;
-
-#if 0
-char *loadEntireFileToMemory(FILE *inputFile, uint32 size) {
-	char *allData = new char[size];
-	if (! allData) return NULL;
-	fread(allData, size, 1, inputFile);
-	finishAccess();
-
-	return allData;
-}
-#endif
-
-int findInSoundCache(int a) {
-//#pragma unused(a)
-	return -1;
-}
-
-void stopMOD(int i) {
-//#pragma unused(i)
-}
-
-void huntKillSound(int filenum) {
-//#pragma unused(filenum)
-}
-
-void huntKillFreeSound(int filenum) {
-//#pragma unused(filenum)
-}
-
-bool initSoundStuff(HWND hwnd) {
-//	#pragma unused(hwnd)
-	return false;
-}
-
-void killSoundStuff() {
-}
-
-bool playMOD(int f, int a, int fromTrack) {
-//#pragma unused (f,a,fromTrack)
-	return true;
-}
-
-void setMusicVolume(int a, int v) {
-//#pragma unused (a,v)
-}
-
-void setDefaultMusicVolume(int v) {
-	defVol = v;
-}
-
-void setSoundVolume(int a, int v) {
-//#pragma unused (a,v)
-}
-
-bool stillPlayingSound(int ch) {
-//#pragma unused (ch)
-	return false;
-}
-
-void setSoundLoop(int a, int s, int e) {
-//#pragma unused (a,s,e)
-}
-
-void setDefaultSoundVolume(int v) {
-	defSoundVol = v;
-}
-
-bool forceRemoveSound() {
-	return 0;
-}
-
-int cacheSound(int f) {
-//#pragma unused (f)
-	return 0;
-}
-
-bool startSound(int f, bool loopy) {
-//#pragma unused (f,loopy)
-	return true;
-}
-
-void saveSounds(Common::WriteStream *stream) {
-	stream->writeByte(0);
-	stream->writeUint16BE(defSoundVol);
-	stream->writeUint16BE(defVol);
-}
-
-void loadSounds(Common::SeekableReadStream *stream) {
-	while (stream->readByte()) {
-		stream->readUint16BE();
-		stream->readUint16BE();
-	}
-
-	defSoundVol = stream->readUint16BE();
-	defVol = stream->readUint16BE();
-}
-
-bool getSoundCacheStack(stackHandler *sH) {
-//#pragma unused (sH)
-	return true;
-}
-
-} // End of namespace Sludge
diff --git a/engines/sludge/sound_openal.cpp b/engines/sludge/sound_openal.cpp
deleted file mode 100644
index c728151..0000000
--- a/engines/sludge/sound_openal.cpp
+++ /dev/null
@@ -1,831 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-
-#if 0
-#include "AL/alure.h"
-#endif
-
-#include "common/file.h"
-
-#include "sludge/allfiles.h"
-#include "sludge/debug.h"
-#include "sludge/newfatal.h"
-#include "sludge/sound.h"
-#include "sludge/moreio.h"
-#include "sludge/fileset.h"
-
-#define MAX_SAMPLES 8
-#define MAX_MODS 3
-#define NUM_BUFS 3
-
-namespace Sludge {
-
-bool soundOK = false;
-bool cacheLoopySound = false;
-bool SilenceIKillYou = false;
-
-struct soundThing {
-#if 0
-	alureStream *stream;
-	ALuint playingOnSource;
-#endif
-	bool playing;
-	int fileLoaded, vol;    //Used for sounds only.
-	bool looping;           //Used for sounds only.
-};
-
-soundThing soundCache[MAX_SAMPLES];
-soundThing modCache[MAX_MODS];
-int intpointers[MAX_SAMPLES];
-
-int defVol = 128;
-int defSoundVol = 255;
-const float modLoudness = 0.95f;
-
-/*
- * Set up, tear down:
- */
-
-bool initSoundStuff(HWND hwnd) {
-#if 0
-	if (!alureInitDevice(NULL, NULL)) {
-		debugOut("Failed to open OpenAL device: %s\n", alureGetErrorString());
-		return 1;
-	}
-
-	int a;
-	for (a = 0; a < MAX_SAMPLES; a ++) {
-		soundCache[a].stream = NULL;
-		soundCache[a].playing = false;
-		soundCache[a].fileLoaded = -1;
-		soundCache[a].looping = false;
-		intpointers[a] = a;
-	}
-
-	for (a = 0; a < MAX_MODS; a ++) {
-		modCache[a].stream = NULL;
-		modCache[a].playing = false;
-	}
-
-	if (! alureUpdateInterval(0.01)) {
-		debugOut("Failed to set Alure update interval: %s\n", alureGetErrorString());
-		return 1;
-	}
-#endif
-	return soundOK = true;
-}
-
-void killSoundStuff() {
-	if (!soundOK)
-		return;
-#if 0
-	SilenceIKillYou = true;
-	for (int i = 0; i < MAX_SAMPLES; i ++) {
-		if (soundCache[i].playing) {
-
-			if (! alureStopSource(soundCache[i].playingOnSource, AL_TRUE)) {
-				debugOut("Failed to stop source: %s\n",
-						alureGetErrorString());
-			}
-
-		}
-
-		if (soundCache[i].stream != NULL) {
-
-			if (! alureDestroyStream(soundCache[i].stream, 0, NULL)) {
-				debugOut("Failed to destroy stream: %s\n",
-						alureGetErrorString());
-			}
-
-		}
-	}
-
-	for (int i = 0; i < MAX_MODS; i ++) {
-		if (modCache[i].playing) {
-
-			if (! alureStopSource(modCache[i].playingOnSource, AL_TRUE)) {
-				debugOut("Failed to stop source: %s\n",
-						alureGetErrorString());
-			}
-
-		}
-
-		if (modCache[i].stream != NULL) {
-
-			if (! alureDestroyStream(modCache[i].stream, 0, NULL)) {
-				debugOut("Failed to destroy stream: %s\n",
-						alureGetErrorString());
-			}
-
-		}
-	}
-
-	SilenceIKillYou = false;
-
-	alureShutdownDevice();
-#endif
-}
-
-/*
- * Some setters:
- */
-
-void setMusicVolume(int a, int v) {
-	if (!soundOK)
-		return;
-
-	if (modCache[a].playing) {
-#if 0
-		alSourcef(modCache[a].playingOnSource, AL_GAIN, (float) modLoudness * v / 256);
-#endif
-	}
-}
-
-void setDefaultMusicVolume(int v) {
-	defVol = v;
-}
-
-void setSoundVolume(int a, int v) {
-	if (!soundOK)
-		return;
-	int ch = findInSoundCache(a);
-	if (ch != -1) {
-		if (soundCache[ch].playing) {
-			soundCache[ch].vol = v;
-#if 0
-			alSourcef(soundCache[ch].playingOnSource, AL_GAIN, (float) v / 256);
-#endif
-		}
-	}
-}
-
-void setDefaultSoundVolume(int v) {
-	defSoundVol = v;
-}
-
-void setSoundLoop(int a, int s, int e) {
-//#pragma unused (a,s,e)
-}
-
-/*
- * End of stream callbacks:
- */
-
-#if 0
-static void sound_eos_callback(void *cacheIndex, ALuint source) {
-	int *a = (int *)cacheIndex;
-
-	alDeleteSources(1, &source);
-	if (alGetError() != AL_NO_ERROR) {
-		debugOut("Failed to delete OpenAL source!\n");
-	}
-
-	soundCache[*a].playingOnSource = 0;
-	soundCache[*a].playing = false;
-	soundCache[*a].looping = false;
-
-}
-#endif
-
-#if 0
-static void mod_eos_callback(void *cacheIndex, ALuint source) {
-	int *a = (int *)cacheIndex;
-
-	alDeleteSources(1, &source);
-	if (alGetError() != AL_NO_ERROR) {
-		debugOut("Failed to delete OpenAL source!\n");
-	}
-
-	modCache[*a].playingOnSource = 0;
-
-	if (! alureDestroyStream(modCache[*a].stream, 0, NULL)) {
-		debugOut("Failed to destroy stream: %s\n",
-				alureGetErrorString());
-	}
-
-	modCache[*a].stream = NULL;
-	modCache[*a].playing = false;
-}
-#endif
-
-/*
- * Stopping things:
- */
-
-int findInSoundCache(int a) {
-	int i;
-	for (i = 0; i < MAX_SAMPLES; i++) {
-		if (soundCache[i].fileLoaded == a) {
-			return i;
-		}
-	}
-	return -1;
-}
-
-void stopMOD(int i) {
-	if (!soundOK)
-		return;
-#if 0
-	alGetError();
-	if (modCache[i].playing) {
-		if (! alureStopSource(modCache[i].playingOnSource, AL_TRUE)) {
-			debugOut("Failed to stop source: %s\n", alureGetErrorString());
-		}
-	}
-#endif
-}
-
-void huntKillSound(int filenum) {
-	if (!soundOK)
-		return;
-#if 0
-	// Clear OpenAL errors to make sure they don't block anything:
-	alGetError();
-
-	int gotSlot = findInSoundCache(filenum);
-	if (gotSlot == -1) return;
-
-	SilenceIKillYou = true;
-
-	if (soundCache[gotSlot].playing) {
-		if (! alureStopSource(soundCache[gotSlot].playingOnSource, AL_TRUE)) {
-			debugOut("Failed to stop source: %s\n", alureGetErrorString());
-		}
-	}
-#endif
-	SilenceIKillYou = false;
-}
-
-void freeSound(int a) {
-	if (!soundOK)
-		return;
-#if 0
-	// Clear OpenAL errors to make sure they don't block anything:
-	alGetError();
-
-	SilenceIKillYou = true;
-
-	if (soundCache[a].playing) {
-		if (! alureStopSource(soundCache[a].playingOnSource, AL_TRUE)) {
-			debugOut("Failed to stop source: %s\n",
-					alureGetErrorString());
-		}
-	}
-	if (! alureDestroyStream(soundCache[a].stream, 0, NULL)) {
-		debugOut("Failed to destroy stream: %s\n",
-				alureGetErrorString());
-	}
-
-	soundCache[a].stream = NULL;
-	soundCache[a].fileLoaded = -1;
-#endif
-	SilenceIKillYou = false;
-}
-
-void huntKillFreeSound(int filenum) {
-	if (!soundOK)
-		return;
-	int gotSlot = findInSoundCache(filenum);
-	if (gotSlot == -1)
-		return;
-	freeSound(gotSlot);
-}
-
-/*
- * Loading and playing:
- */
-
-void playStream(int a, bool isMOD, bool loopy) {
-#if 0
-	if (! soundOK) return;
-	ALboolean ok;
-	ALuint src;
-	soundThing *st;
-	void (*eos_callback)(void *userdata, ALuint source);
-
-	if (isMOD) {
-		st = &modCache[a];
-		eos_callback = mod_eos_callback;
-	} else {
-		st = &soundCache[a];
-		eos_callback = sound_eos_callback;
-	}
-
-	alGenSources(1, &src);
-	if (alGetError() != AL_NO_ERROR) {
-		debugOut("Failed to create OpenAL source!\n");
-		return;
-	}
-
-	if (isMOD) {
-		alSourcef(src, AL_GAIN, (float) modLoudness * defVol / 256);
-	} else {
-		alSourcef(src, AL_GAIN, (float) soundCache[a].vol / 256);
-	}
-
-	if (loopy) {
-		ok = alurePlaySourceStream(src, (*st).stream,
-				NUM_BUFS, -1, eos_callback, &intpointers[a]);
-	} else {
-		ok = alurePlaySourceStream(src, (*st).stream,
-				NUM_BUFS, 0, eos_callback, &intpointers[a]);
-	}
-
-	if (!ok) {
-
-		debugOut("Failed to play stream: %s\n", alureGetErrorString());
-		alDeleteSources(1, &src);
-		if (alGetError() != AL_NO_ERROR) {
-			debugOut("Failed to delete OpenAL source!\n");
-		}
-
-		(*st).playingOnSource = 0;
-	} else {
-		(*st).playingOnSource = src;
-		(*st).playing = true;
-	}
-#endif
-}
-
-char *loadEntireFileToMemory(Common::SeekableReadStream *inputFile,
-		uint32 size) {
-	char *allData = new char[size];
-	if (!allData)
-		return NULL;
-
-	size_t bytes_read = inputFile->read(allData, size);
-	if (bytes_read != size && inputFile->err()) {
-		debugOut("Reading error in loadEntireFileToMemory.\n");
-	}
-
-	finishAccess();
-
-	return allData;
-}
-
-bool playMOD(int f, int a, int fromTrack) {
-	if (!soundOK)
-		return true;
-	stopMOD(a);
-
-	setResourceForFatal(f);
-	uint32 length = openFileFromNum(f);
-	if (length == 0) {
-		finishAccess();
-		setResourceForFatal(-1);
-		return false;
-	}
-#if 0
-	unsigned char *memImage;
-	memImage = (unsigned char *) loadEntireFileToMemory(bigDataFile, length);
-	if (! memImage) return fatal(ERROR_MUSIC_MEMORY_LOW);
-
-	modCache[a].stream = alureCreateStreamFromMemory(memImage, length, 19200, 0, NULL);
-
-	delete memImage;
-
-	if (modCache[a].stream != NULL) {
-		setMusicVolume(a, defVol);
-
-		if (! alureSetStreamOrder(modCache[a].stream, fromTrack)) {
-			debugOut("Failed to set stream order: %s\n",
-					alureGetErrorString());
-		}
-
-		playStream(a, true, true);
-
-	} else {
-
-		debugOut("Failed to create stream from MOD: %s\n",
-				alureGetErrorString());
-
-		warning(ERROR_MUSIC_ODDNESS);
-		soundCache[a].stream = NULL;
-		soundCache[a].playing = false;
-		soundCache[a].playingOnSource = 0;
-	}
-	setResourceForFatal(-1);
-#endif
-	return true;
-}
-
-bool stillPlayingSound(int ch) {
-	if (soundOK)
-		if (ch != -1)
-			if (soundCache[ch].fileLoaded != -1)
-				if (soundCache[ch].playing)
-					return true;
-
-	return false;
-}
-
-bool forceRemoveSound() {
-	for (int a = 0; a < MAX_SAMPLES; a++) {
-		if (soundCache[a].fileLoaded != -1 && !stillPlayingSound(a)) {
-//			soundWarning ("Deleting silent sound", a);
-			freeSound(a);
-			return 1;
-		}
-	}
-
-	for (int a = 0; a < MAX_SAMPLES; a++) {
-		if (soundCache[a].fileLoaded != -1) {
-//			soundWarning ("Deleting playing sound", a);
-			freeSound(a);
-			return 1;
-		}
-	}
-//	soundWarning ("Cache is empty!", 0);
-	return 0;
-}
-
-int emptySoundSlot = 0;
-
-int findEmptySoundSlot() {
-	int t;
-	for (t = 0; t < MAX_SAMPLES; t++) {
-		emptySoundSlot++;
-		emptySoundSlot %= MAX_SAMPLES;
-#if 0
-		if (soundCache[emptySoundSlot].stream == NULL)
-		return emptySoundSlot;
-#endif
-	}
-
-	for (t = 0; t < MAX_SAMPLES; t++) {
-		emptySoundSlot++;
-		emptySoundSlot %= MAX_SAMPLES;
-		if (!soundCache[emptySoundSlot].playing)
-			return emptySoundSlot;
-	}
-
-	// Argh! They're all playing! Let's trash the oldest that's not looping...
-
-	for (t = 0; t < MAX_SAMPLES; t++) {
-		emptySoundSlot++;
-		emptySoundSlot %= MAX_SAMPLES;
-		if (!soundCache[emptySoundSlot].looping)
-			return emptySoundSlot;
-	}
-
-	// Holy crap, they're all looping! What's this twat playing at?
-
-	emptySoundSlot++;
-	emptySoundSlot %= MAX_SAMPLES;
-	return emptySoundSlot;
-}
-
-int cacheSound(int f) {
-
-	if (!soundOK)
-		return -1;
-
-	unsigned int chunkLength;
-	int retval;
-	bool loopy;
-#if 0
-	loopy = cacheLoopySound;
-	cacheLoopySound = false;
-
-	setResourceForFatal(f);
-
-	if (! soundOK) return 0;
-
-	int a = findInSoundCache(f);
-	if (a != -1) {
-
-		if (soundCache[a].playing) {
-			if (! alureStopSource(soundCache[a].playingOnSource, AL_TRUE)) {
-				debugOut("Failed to stop source: %s\n",
-						alureGetErrorString());
-			}
-		}
-		if (! alureRewindStream(soundCache[a].stream)) {
-			debugOut("Failed to rewind stream: %s\n",
-					alureGetErrorString());
-		}
-
-		return a;
-	}
-	if (f == -2) return -1;
-	a = findEmptySoundSlot();
-	freeSound(a);
-
-	uint32 length = openFileFromNum(f);
-	if (! length) return -1;
-
-	unsigned char *memImage;
-
-	bool tryAgain = true;
-
-	while (tryAgain) {
-		memImage = (unsigned char *)loadEntireFileToMemory(bigDataFile, length);
-		tryAgain = memImage == NULL;
-		if (tryAgain) {
-			if (! forceRemoveSound()) {
-				fatal(ERROR_SOUND_MEMORY_LOW);
-				return -1;
-			}
-		}
-	}
-
-	chunkLength = 19200;
-
-	// Small looping sounds need small chunklengths.
-	if (loopy) {
-		if (length < NUM_BUFS * chunkLength) {
-			chunkLength = length / NUM_BUFS;
-		}
-	} else if (length < chunkLength) {
-		chunkLength = length;
-	}
-
-	soundCache[a].stream = alureCreateStreamFromMemory(memImage, length, chunkLength, 0, NULL);
-
-	delete[] memImage;
-
-	if (soundCache[a].stream != NULL) {
-		soundCache[a].fileLoaded = f;
-		setResourceForFatal(-1);
-		retval = a;
-	} else {
-
-		debugOut("Failed to create stream from sound: %s\n",
-				alureGetErrorString());
-
-		warning(ERROR_SOUND_ODDNESS);
-		soundCache[a].stream = NULL;
-		soundCache[a].playing = false;
-		soundCache[a].playingOnSource = 0;
-		soundCache[a].fileLoaded = -1;
-		soundCache[a].looping = false;
-		retval = -1;
-	}
-#endif
-	return retval;
-}
-
-bool startSound(int f, bool loopy) {
-	if (soundOK) {
-		cacheLoopySound = loopy;
-		int a = cacheSound(f);
-		if (a == -1) {
-			debugOut("Failed to cache sound!\n");
-			return false;
-		}
-		soundCache[a].looping = loopy;
-		soundCache[a].vol = defSoundVol;
-
-		playStream(a, false, loopy);
-	}
-	return true;
-}
-
-void saveSounds(Common::WriteStream *stream) {
-	if (soundOK) {
-		for (int i = 0; i < MAX_SAMPLES; i++) {
-			if (soundCache[i].looping) {
-				stream->writeByte(1);
-				stream->writeUint16BE(soundCache[i].fileLoaded);
-				stream->writeUint16BE(soundCache[i].vol);
-			}
-		}
-	}
-	stream->writeByte(0);
-	stream->writeUint16BE(defSoundVol);
-	stream->writeUint16BE(defVol);
-}
-
-void loadSounds(Common::SeekableReadStream *stream) {
-	for (int i = 0; i < MAX_SAMPLES; i++)
-		freeSound(i);
-
-	while (stream->readByte()) {
-		int fileLoaded = stream->readUint16BE();
-		defSoundVol = stream->readUint16BE();
-		startSound(fileLoaded, 1);
-	}
-
-	defSoundVol = stream->readUint16BE();
-	defVol = stream->readUint16BE();
-}
-
-bool getSoundCacheStack(stackHandler *sH) {
-	variable newFileHandle;
-	newFileHandle.varType = SVT_NULL;
-
-	for (int a = 0; a < MAX_SAMPLES; a++) {
-		if (soundCache[a].fileLoaded != -1) {
-			setVariable(newFileHandle, SVT_FILE, soundCache[a].fileLoaded);
-			if (!addVarToStackQuick(newFileHandle, sH->first))
-				return false;
-			if (sH->last == NULL)
-				sH->last = sH->first;
-		}
-	}
-	return true;
-}
-
-soundList *deleteSoundFromList(soundList *s) {
-	// Don't delete a playing sound.
-	if (s->cacheIndex)
-		return NULL;
-
-	soundList *o = NULL;
-	if (!s->next) {
-		o = s->prev;
-		if (o)
-			o->next = NULL;
-		delete s;
-		return o;
-	}
-	if (s != s->next) {
-		o = s->next;
-		o->prev = s->prev;
-		if (o->prev)
-			o->prev->next = o;
-	}
-	delete s;
-	return o;
-}
-
-#if 0
-static void list_eos_callback(void *list, ALuint source) {
-	soundList *s = (soundList *) list;
-
-	int a = s->cacheIndex;
-#if 0
-	alDeleteSources(1, &source);
-	if (alGetError() != AL_NO_ERROR) {
-		debugOut("Failed to delete OpenAL source!\n");
-	}
-#endif
-	soundCache[a].playingOnSource = 0;
-	soundCache[a].playing = false;
-	soundCache[a].looping = false;
-	s-> cacheIndex = false;
-	if (SilenceIKillYou) {
-		while (s = deleteSoundFromList(s));
-	} else {
-		if (s->next) {
-			if (s->next == s) {
-				int v = defSoundVol;
-				defSoundVol = soundCache[a].vol;
-				startSound(s->sound, true);
-				defSoundVol = v;
-				while (s = deleteSoundFromList(s));
-				return;
-			}
-			s->next->vol = soundCache[a].vol;
-			playSoundList(s->next);
-		} else {
-			while (s = deleteSoundFromList(s));
-		}
-	}
-}
-#endif
-
-void playSoundList(soundList *s) {
-#if 0
-	if (soundOK) {
-		cacheLoopySound = true;
-		int a = cacheSound(s->sound);
-		if (a == -1) {
-			debugOut("Failed to cache sound!\n");
-			return;
-		}
-		soundCache[a].looping = false;
-		if (s->vol < 0)
-		soundCache[a].vol = defSoundVol;
-		else
-		soundCache[a].vol = s->vol;
-		s-> cacheIndex = a;
-
-		ALboolean ok;
-		ALuint src;
-		soundThing *st;
-
-		st = &soundCache[a];
-
-		alGenSources(1, &src);
-		if (alGetError() != AL_NO_ERROR) {
-			debugOut("Failed to create OpenAL source!\n");
-			return;
-		}
-
-		alSourcef(src, AL_GAIN, (float) soundCache[a].vol / 256);
-
-		ok = alurePlaySourceStream(src, (*st).stream,
-				NUM_BUFS, 0, list_eos_callback, s);
-
-		if (!ok) {
-
-			debugOut("Failed to play stream: %s\n", alureGetErrorString());
-			alDeleteSources(1, &src);
-			if (alGetError() != AL_NO_ERROR) {
-				debugOut("Failed to delete OpenAL source!\n");
-			}
-
-			(*st).playingOnSource = 0;
-		} else {
-			(*st).playingOnSource = src;
-			(*st).playing = true;
-		}
-	}
-#endif
-}
-
-void playMovieStream(int a) {
-#if 0
-	if (! soundOK) return;
-	ALboolean ok;
-	ALuint src;
-
-	alGenSources(1, &src);
-	if (alGetError() != AL_NO_ERROR) {
-		debugOut("Failed to create OpenAL source!\n");
-		return;
-	}
-
-	alSourcef(src, AL_GAIN, (float) soundCache[a].vol / 256);
-
-	ok = alurePlaySourceStream(src, soundCache[a].stream,
-			10, 0, sound_eos_callback, &intpointers[a]);
-	if (!ok) {
-		debugOut("Failed to play stream: %s\n", alureGetErrorString());
-		alDeleteSources(1, &src);
-		if (alGetError() != AL_NO_ERROR) {
-			debugOut("Failed to delete OpenAL source!\n");
-		}
-
-		soundCache[a].playingOnSource = 0;
-	} else {
-		soundCache[a].playingOnSource = src;
-		soundCache[a].playing = true;
-	}
-#endif
-}
-
-#if 0
-int initMovieSound(int f, ALenum format, int audioChannels, ALuint samplerate,
-		ALuint(*callback)(void *userdata, ALubyte *data, ALuint bytes)) {
-	if (! soundOK) return 0;
-
-	int retval;
-	int a = findEmptySoundSlot();
-	freeSound(a);
-
-	soundCache[a].looping = false;
-#if 0
-	// audioChannel * sampleRate gives us a buffer of half a second. Not much, but it should be enough.
-	soundCache[a].stream = alureCreateStreamFromCallback(
-			callback,
-			&intpointers[a], format, samplerate,
-			audioChannels * samplerate, 0, NULL);
-#endif
-	if (soundCache[a].stream != NULL) {
-		soundCache[a].fileLoaded = f;
-		soundCache[a].vol = defSoundVol;
-		retval = a;
-	} else {
-#if 0
-		debugOut("Failed to create stream from sound: %s\n",
-				alureGetErrorString());
-#endif
-		warning(ERROR_SOUND_ODDNESS);
-		soundCache[a].stream = NULL;
-		soundCache[a].playing = false;
-		soundCache[a].playingOnSource = 0;
-		soundCache[a].fileLoaded = -1;
-		retval = -1;
-	}
-	//fprintf (stderr, "Stream %d created. Sample rate: %d Channels: %d\n", retval, samplerate, audioChannels);
-
-	return retval;
-}
-#endif
-
-unsigned int getSoundSource(int index) {
-	return 0; /*soundCache[index].playingOnSource;*/ //TODO:false value
-}
-
-} // End of namespace Sludge


Commit: ef9438065fea8c1a58b6ebb2a8f1ecc72b2037f7
    https://github.com/scummvm/scummvm/commit/ef9438065fea8c1a58b6ebb2a8f1ecc72b2037f7
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: play game wav sound in a rough way

Changed paths:
    engines/sludge/sound.cpp


diff --git a/engines/sludge/sound.cpp b/engines/sludge/sound.cpp
index 360ad6d..26bf176 100644
--- a/engines/sludge/sound.cpp
+++ b/engines/sludge/sound.cpp
@@ -24,14 +24,21 @@
 #include "AL/alure.h"
 #endif
 
+#include "common/debug.h"
 #include "common/file.h"
 
+#include "audio/audiostream.h"
+#include "audio/mixer.h"
+#include "audio/decoders/wave.h"
+#include "audio/decoders/vorbis.h"
+
 #include "sludge/allfiles.h"
 #include "sludge/debug.h"
 #include "sludge/newfatal.h"
 #include "sludge/sound.h"
 #include "sludge/moreio.h"
 #include "sludge/fileset.h"
+#include "sludge/sludge.h"
 
 #define MAX_SAMPLES 8
 #define MAX_MODS 3
@@ -585,8 +592,30 @@ int cacheSound(int f) {
 }
 
 bool startSound(int f, bool loopy) {
-	if (soundOK) {
+	if (loopy) // TODO: don't consider loop sound yet at this stage
+		return false;
+	// load sound
+	setResourceForFatal(f);
+	uint32 length = openFileFromNum(f);
+	Common::SeekableReadStream *memImage = bigDataFile->readStream(length);
+	if (memImage->size() != length || bigDataFile->err())
+		debug("Sound reading failed");
+	Audio::AudioStream *stream = Audio::makeWAVStream(memImage, DisposeAfterUse::NO);
+#ifdef USE_VORBIS
+	if (!stream) {
+		stream = Audio::makeVorbisStream(memImage, DisposeAfterUse::NO);
+	}
+#endif
+	delete memImage;
+	if (!stream)
+		return false;
+
+	// play sound
+	Audio::SoundHandle soundHandle;
+	g_sludge->_mixer->playStream(Audio::Mixer::kSFXSoundType, &soundHandle, stream, -1, Audio::Mixer::kMaxChannelVolume);
 #if 0
+	if (soundOK) {
+
 		cacheLoopySound = loopy;
 		int a = cacheSound(f);
 		if (a == -1) {
@@ -597,8 +626,8 @@ bool startSound(int f, bool loopy) {
 		soundCache[a].vol = defSoundVol;
 
 		playStream(a, false, loopy);
-#endif
 	}
+#endif
 	return true;
 }
 


Commit: 51a20af06427e1e40facf0dd0bd9cb614ccfffca
    https://github.com/scummvm/scummvm/commit/51a20af06427e1e40facf0dd0bd9cb614ccfffca
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: leave MOD sound loading aside

Changed paths:
    engines/sludge/sound.cpp


diff --git a/engines/sludge/sound.cpp b/engines/sludge/sound.cpp
index 26bf176..0aa9d57 100644
--- a/engines/sludge/sound.cpp
+++ b/engines/sludge/sound.cpp
@@ -31,6 +31,7 @@
 #include "audio/mixer.h"
 #include "audio/decoders/wave.h"
 #include "audio/decoders/vorbis.h"
+#include "audio/mods/protracker.h"
 
 #include "sludge/allfiles.h"
 #include "sludge/debug.h"
@@ -390,6 +391,30 @@ char *loadEntireFileToMemory(Common::SeekableReadStream *inputFile,
 }
 
 bool playMOD(int f, int a, int fromTrack) {
+#if 0
+	// load sound
+	setResourceForFatal(f);
+	uint32 length = openFileFromNum(f);
+	if (length == 0) {
+		finishAccess();
+		setResourceForFatal(-1);
+		return false;
+	}
+
+	Common::SeekableReadStream *memImage = bigDataFile->readStream(length);
+	if (memImage->size() != length || bigDataFile->err())
+		debug("Sound reading failed");
+	Audio::AudioStream *stream = Audio::makeProtrackerStream(memImage);
+	//TODO: replace by xm file decoders
+	if (!stream)
+		return false;
+
+	// play sound
+	Audio::SoundHandle soundHandle;
+	g_sludge->_mixer->playStream(Audio::Mixer::kSFXSoundType, &soundHandle,
+			stream, -1, Audio::Mixer::kMaxChannelVolume);
+#endif
+#if 0
 	if (!soundOK)
 		return true;
 	stopMOD(a);
@@ -401,7 +426,7 @@ bool playMOD(int f, int a, int fromTrack) {
 		setResourceForFatal(-1);
 		return false;
 	}
-#if 0
+
 	unsigned char *memImage;
 	memImage = (unsigned char *) loadEntireFileToMemory(bigDataFile, length);
 	if (! memImage) return fatal(ERROR_MUSIC_MEMORY_LOW);


Commit: 7b2a2123f4cfacf44ab51220c271121b1cb9ba89
    https://github.com/scummvm/scummvm/commit/7b2a2123f4cfacf44ab51220c271121b1cb9ba89
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: add new game for testing

Changed paths:
    engines/sludge/detection.cpp
    engines/sludge/detection_tables.h


diff --git a/engines/sludge/detection.cpp b/engines/sludge/detection.cpp
index 69e202c..2ce5f8f 100644
--- a/engines/sludge/detection.cpp
+++ b/engines/sludge/detection.cpp
@@ -46,8 +46,7 @@ const char *SludgeEngine::getGameFile() const {
 static const PlainGameDescriptor sludgeGames[] = {
 	{ "sludge", "Sludge Game" },
 	{ "welcome", "Welcome Example" },
-	{ "welcome2", "Welcome Example 2" },
-	{ "welcomePng", "Welcome For PNG Test" },
+	{ "welcomeloop", "Welcome Loop Test" },
 	{ "verbcoin", "Verb Coin" },
 	{ 0, 0 }
 };
diff --git a/engines/sludge/detection_tables.h b/engines/sludge/detection_tables.h
index 1176832..5d366d7 100644
--- a/engines/sludge/detection_tables.h
+++ b/engines/sludge/detection_tables.h
@@ -49,6 +49,19 @@ static const SludgeGameDescription gameDescriptions[] = {
 		0
 	},
 
+	{
+		{
+			"welcomeloop",
+			"",
+			AD_ENTRY1s("WelcomeLoop.slg", "af6e20c7cfae9101f1a49236d45014ef", 34932),
+			Common::EN_ANY,
+			Common::kPlatformUnknown,
+			ADGF_NO_FLAGS,
+			GUIO0()
+		},
+		0
+	},
+
 	{ AD_TABLE_END_MARKER, 0 }
 };
 


Commit: 747820bbede13235fbf2bd301ebae88ffa0ccf40
    https://github.com/scummvm/scummvm/commit/747820bbede13235fbf2bd301ebae88ffa0ccf40
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: get loop sound work for wav and ogg

Changed paths:
    engines/sludge/main_loop.cpp
    engines/sludge/sound.cpp


diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index 7498ab2..6655b9b 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -361,11 +361,10 @@ int main_loop(const char *filename)
 		cursor = SDL_CreateCursor(&data, &data, 1, 1, 0, 0);
 		SDL_SetCursor(cursor);
 	}
-
+#endif
 	if (!(specialSettings & SPECIAL_SILENT)) {
 		initSoundStuff(hMainWindow);
 	}
-#endif
 
 	startNewFunctionNum(0, 0, NULL, noStack);
 
@@ -391,9 +390,7 @@ int main_loop(const char *filename)
 
 	delete[] gamePath;
 
-#if 0
 	killSoundStuff();
-#endif
 
 #if defined(HAVE_GLES2)
 	EGL_Close();
diff --git a/engines/sludge/sound.cpp b/engines/sludge/sound.cpp
index 0aa9d57..88604dd 100644
--- a/engines/sludge/sound.cpp
+++ b/engines/sludge/sound.cpp
@@ -20,12 +20,9 @@
  *
  */
 
-#if 0
-#include "AL/alure.h"
-#endif
-
 #include "common/debug.h"
 #include "common/file.h"
+#include "common/memstream.h"
 
 #include "audio/audiostream.h"
 #include "audio/mixer.h"
@@ -48,21 +45,18 @@
 namespace Sludge {
 
 bool soundOK = false;
-bool cacheLoopySound = false;
 bool SilenceIKillYou = false;
 
 struct soundThing {
-#if 0
-	alureStream *stream;
-	ALuint playingOnSource;
-#endif
-	bool playing;
-	int fileLoaded, vol;    //Used for sounds only.
-	bool looping;           //Used for sounds only.
+	Audio::SoundHandle handle;
+	int fileLoaded, vol;    //Used for sounds only. (sound saving/loading)
+	bool looping;      		//Used for sounds only. (sound saving/loading)
 };
 
 soundThing soundCache[MAX_SAMPLES];
+#if 0
 soundThing modCache[MAX_MODS];
+#endif
 int intpointers[MAX_SAMPLES];
 
 int defVol = 128;
@@ -74,30 +68,16 @@ const float modLoudness = 0.95f;
  */
 
 bool initSoundStuff(HWND hwnd) {
-#if 0
-	if (!alureInitDevice(NULL, NULL)) {
-		debugOut("Failed to open OpenAL device: %s\n", alureGetErrorString());
-		return 1;
-	}
-
-	int a;
-	for (a = 0; a < MAX_SAMPLES; a ++) {
-		soundCache[a].stream = NULL;
-		soundCache[a].playing = false;
+	for (int a = 0; a < MAX_SAMPLES; a ++) {
 		soundCache[a].fileLoaded = -1;
 		soundCache[a].looping = false;
 		intpointers[a] = a;
 	}
-
-	for (a = 0; a < MAX_MODS; a ++) {
+#if 0
+	for (int a = 0; a < MAX_MODS; a ++) {
 		modCache[a].stream = NULL;
 		modCache[a].playing = false;
 	}
-
-	if (! alureUpdateInterval(0.01)) {
-		debugOut("Failed to set Alure update interval: %s\n", alureGetErrorString());
-		return 1;
-	}
 #endif
 	return soundOK = true;
 }
@@ -105,28 +85,14 @@ bool initSoundStuff(HWND hwnd) {
 void killSoundStuff() {
 	if (!soundOK)
 		return;
-#if 0
+
 	SilenceIKillYou = true;
 	for (int i = 0; i < MAX_SAMPLES; i ++) {
-		if (soundCache[i].playing) {
-
-			if (! alureStopSource(soundCache[i].playingOnSource, AL_TRUE)) {
-				debugOut("Failed to stop source: %s\n",
-						alureGetErrorString());
-			}
-
-		}
-
-		if (soundCache[i].stream != NULL) {
-
-			if (! alureDestroyStream(soundCache[i].stream, 0, NULL)) {
-				debugOut("Failed to destroy stream: %s\n",
-						alureGetErrorString());
-			}
-
+		if (g_sludge->_mixer->isSoundHandleActive(soundCache[i].handle)) {
+			g_sludge->_mixer->stopHandle(soundCache[i].handle);
 		}
 	}
-
+#if 0
 	for (int i = 0; i < MAX_MODS; i ++) {
 		if (modCache[i].playing) {
 
@@ -146,11 +112,8 @@ void killSoundStuff() {
 
 		}
 	}
-
-	SilenceIKillYou = false;
-
-	alureShutdownDevice();
 #endif
+	SilenceIKillYou = false;
 }
 
 /*
@@ -160,12 +123,11 @@ void killSoundStuff() {
 void setMusicVolume(int a, int v) {
 	if (!soundOK)
 		return;
-
-	if (modCache[a].playing) {
 #if 0
+	if (modCache[a].playing) {
 		alSourcef(modCache[a].playingOnSource, AL_GAIN, (float) modLoudness * v / 256);
-#endif
 	}
+#endif
 }
 
 void setDefaultMusicVolume(int v) {
@@ -177,11 +139,9 @@ void setSoundVolume(int a, int v) {
 		return;
 	int ch = findInSoundCache(a);
 	if (ch != -1) {
-		if (soundCache[ch].playing) {
+		if (g_sludge->_mixer->isSoundHandleActive(soundCache[ch].handle)) {
 			soundCache[ch].vol = v;
-#if 0
-			alSourcef(soundCache[ch].playingOnSource, AL_GAIN, (float) v / 256);
-#endif
+			g_sludge->_mixer->setChannelVolume(soundCache[ch].handle, v);
 		}
 	}
 }
@@ -286,26 +246,15 @@ void huntKillSound(int filenum) {
 void freeSound(int a) {
 	if (!soundOK)
 		return;
-#if 0
-	// Clear OpenAL errors to make sure they don't block anything:
-	alGetError();
 
 	SilenceIKillYou = true;
 
-	if (soundCache[a].playing) {
-		if (! alureStopSource(soundCache[a].playingOnSource, AL_TRUE)) {
-			debugOut("Failed to stop source: %s\n",
-					alureGetErrorString());
-		}
-	}
-	if (! alureDestroyStream(soundCache[a].stream, 0, NULL)) {
-		debugOut("Failed to destroy stream: %s\n",
-				alureGetErrorString());
+	if (g_sludge->_mixer->isSoundHandleActive(soundCache[a].handle)) {
+		g_sludge->_mixer->stopHandle(soundCache[a].handle);
 	}
 
-	soundCache[a].stream = NULL;
 	soundCache[a].fileLoaded = -1;
-#endif
+
 	SilenceIKillYou = false;
 }
 
@@ -321,75 +270,6 @@ void huntKillFreeSound(int filenum) {
 /*
  * Loading and playing:
  */
-
-void playStream(int a, bool isMOD, bool loopy) {
-#if 0
-	if (! soundOK) return;
-	ALboolean ok;
-	ALuint src;
-	soundThing *st;
-	void (*eos_callback)(void *userdata, ALuint source);
-
-	if (isMOD) {
-		st = &modCache[a];
-		eos_callback = mod_eos_callback;
-	} else {
-		st = &soundCache[a];
-		eos_callback = sound_eos_callback;
-	}
-
-	alGenSources(1, &src);
-	if (alGetError() != AL_NO_ERROR) {
-		debugOut("Failed to create OpenAL source!\n");
-		return;
-	}
-
-	if (isMOD) {
-		alSourcef(src, AL_GAIN, (float) modLoudness * defVol / 256);
-	} else {
-		alSourcef(src, AL_GAIN, (float) soundCache[a].vol / 256);
-	}
-
-	if (loopy) {
-		ok = alurePlaySourceStream(src, (*st).stream,
-				NUM_BUFS, -1, eos_callback, &intpointers[a]);
-	} else {
-		ok = alurePlaySourceStream(src, (*st).stream,
-				NUM_BUFS, 0, eos_callback, &intpointers[a]);
-	}
-
-	if (!ok) {
-
-		debugOut("Failed to play stream: %s\n", alureGetErrorString());
-		alDeleteSources(1, &src);
-		if (alGetError() != AL_NO_ERROR) {
-			debugOut("Failed to delete OpenAL source!\n");
-		}
-
-		(*st).playingOnSource = 0;
-	} else {
-		(*st).playingOnSource = src;
-		(*st).playing = true;
-	}
-#endif
-}
-
-char *loadEntireFileToMemory(Common::SeekableReadStream *inputFile,
-		uint32 size) {
-	char *allData = new char[size];
-	if (!allData)
-		return NULL;
-
-	size_t bytes_read = inputFile->read(allData, size);
-	if (bytes_read != size && inputFile->err()) {
-		debugOut("Reading error in loadEntireFileToMemory.\n");
-	}
-
-	finishAccess();
-
-	return allData;
-}
-
 bool playMOD(int f, int a, int fromTrack) {
 #if 0
 	// load sound
@@ -464,7 +344,7 @@ bool stillPlayingSound(int ch) {
 	if (soundOK)
 		if (ch != -1)
 			if (soundCache[ch].fileLoaded != -1)
-				if (soundCache[ch].playing)
+				if (g_sludge->_mixer->isSoundHandleActive(soundCache[ch].handle))
 					return true;
 
 	return false;
@@ -493,26 +373,16 @@ bool forceRemoveSound() {
 int emptySoundSlot = 0;
 
 int findEmptySoundSlot() {
-	int t;
-	for (t = 0; t < MAX_SAMPLES; t++) {
-		emptySoundSlot++;
-		emptySoundSlot %= MAX_SAMPLES;
-#if 0
-		if (soundCache[emptySoundSlot].stream == NULL)
-		return emptySoundSlot;
-#endif
-	}
-
-	for (t = 0; t < MAX_SAMPLES; t++) {
+	for (int t = 0; t < MAX_SAMPLES; t++) {
 		emptySoundSlot++;
 		emptySoundSlot %= MAX_SAMPLES;
-		if (!soundCache[emptySoundSlot].playing)
+		if (!g_sludge->_mixer->isSoundHandleActive(soundCache[emptySoundSlot].handle))
 			return emptySoundSlot;
 	}
 
 	// Argh! They're all playing! Let's trash the oldest that's not looping...
 
-	for (t = 0; t < MAX_SAMPLES; t++) {
+	for (int t = 0; t < MAX_SAMPLES; t++) {
 		emptySoundSlot++;
 		emptySoundSlot %= MAX_SAMPLES;
 		if (!soundCache[emptySoundSlot].looping)
@@ -527,132 +397,72 @@ int findEmptySoundSlot() {
 }
 
 int cacheSound(int f) {
+	return 0; // don't load source in advance
+}
 
+int makeSoundAudioStream(int f, Audio::AudioStream *&audiostream, bool loopy) {
 	if (!soundOK)
 		return -1;
 
-	unsigned int chunkLength;
-	int retval;
-	bool loopy;
-#if 0
-	loopy = cacheLoopySound;
-	cacheLoopySound = false;
-
-	setResourceForFatal(f);
-
-	if (! soundOK) return 0;
-
 	int a = findInSoundCache(f);
-	if (a != -1) {
-
-		if (soundCache[a].playing) {
-			if (! alureStopSource(soundCache[a].playingOnSource, AL_TRUE)) {
-				debugOut("Failed to stop source: %s\n",
-						alureGetErrorString());
-			}
-		}
-		if (! alureRewindStream(soundCache[a].stream)) {
-			debugOut("Failed to rewind stream: %s\n",
-					alureGetErrorString());
+	if (a != -1) { // if this sound has been loaded before
+		// still playing
+		if (g_sludge->_mixer->isSoundHandleActive(soundCache[a].handle)) {
+			g_sludge->_mixer->stopHandle(soundCache[a].handle); // stop it
 		}
-
-		return a;
+	} else {
+		if (f == -2)
+			return -1;
+		a = findEmptySoundSlot();
+		freeSound(a);
 	}
-	if (f == -2) return -1;
-	a = findEmptySoundSlot();
-	freeSound(a);
 
+	setResourceForFatal(f);
 	uint32 length = openFileFromNum(f);
-	if (! length) return -1;
-
-	unsigned char *memImage;
-
-	bool tryAgain = true;
-
-	while (tryAgain) {
-		memImage = (unsigned char *)loadEntireFileToMemory(bigDataFile, length);
-		tryAgain = memImage == NULL;
-		if (tryAgain) {
-			if (! forceRemoveSound()) {
-				fatal(ERROR_SOUND_MEMORY_LOW);
-				return -1;
-			}
-		}
-	}
+	if (!length)
+		return -1;
 
-	chunkLength = 19200;
+	uint curr_ptr = bigDataFile->pos();
+	Audio::RewindableAudioStream *stream = Audio::makeWAVStream(bigDataFile->readStream(length), DisposeAfterUse::NO);
 
-	// Small looping sounds need small chunklengths.
-	if (loopy) {
-		if (length < NUM_BUFS * chunkLength) {
-			chunkLength = length / NUM_BUFS;
-		}
-	} else if (length < chunkLength) {
-		chunkLength = length;
+#ifdef USE_VORBIS
+	if (!stream) {
+		bigDataFile->seek(curr_ptr);
+		stream = Audio::makeVorbisStream(bigDataFile->readStream(length), DisposeAfterUse::NO);
 	}
+#endif
+	finishAccess();
 
-	soundCache[a].stream = alureCreateStreamFromMemory(memImage, length, chunkLength, 0, NULL);
-
-	delete[] memImage;
-
-	if (soundCache[a].stream != NULL) {
+	if (stream) {
+		audiostream = Audio::makeLoopingAudioStream(stream, loopy ? 0 : 1);
 		soundCache[a].fileLoaded = f;
 		setResourceForFatal(-1);
-		retval = a;
 	} else {
-
-		debugOut("Failed to create stream from sound: %s\n",
-				alureGetErrorString());
-
+		audiostream = nullptr;
 		warning(ERROR_SOUND_ODDNESS);
-		soundCache[a].stream = NULL;
-		soundCache[a].playing = false;
-		soundCache[a].playingOnSource = 0;
 		soundCache[a].fileLoaded = -1;
 		soundCache[a].looping = false;
-		retval = -1;
+		return -1;
 	}
-#endif
-	return retval;
+
+	return a;
 }
 
 bool startSound(int f, bool loopy) {
-	if (loopy) // TODO: don't consider loop sound yet at this stage
-		return false;
-	// load sound
-	setResourceForFatal(f);
-	uint32 length = openFileFromNum(f);
-	Common::SeekableReadStream *memImage = bigDataFile->readStream(length);
-	if (memImage->size() != length || bigDataFile->err())
-		debug("Sound reading failed");
-	Audio::AudioStream *stream = Audio::makeWAVStream(memImage, DisposeAfterUse::NO);
-#ifdef USE_VORBIS
-	if (!stream) {
-		stream = Audio::makeVorbisStream(memImage, DisposeAfterUse::NO);
-	}
-#endif
-	delete memImage;
-	if (!stream)
-		return false;
-
-	// play sound
-	Audio::SoundHandle soundHandle;
-	g_sludge->_mixer->playStream(Audio::Mixer::kSFXSoundType, &soundHandle, stream, -1, Audio::Mixer::kMaxChannelVolume);
-#if 0
 	if (soundOK) {
-
-		cacheLoopySound = loopy;
-		int a = cacheSound(f);
+		// Load sound
+		Audio::AudioStream *stream = nullptr;
+		int a = makeSoundAudioStream(f, stream, loopy);
 		if (a == -1) {
 			debugOut("Failed to cache sound!\n");
 			return false;
 		}
+
+		// play sound
 		soundCache[a].looping = loopy;
 		soundCache[a].vol = defSoundVol;
-
-		playStream(a, false, loopy);
+		g_sludge->_mixer->playStream(Audio::Mixer::kSFXSoundType, &soundCache[a].handle, stream, -1, soundCache[a].vol);
 	}
-#endif
 	return true;
 }
 
@@ -760,54 +570,26 @@ static void list_eos_callback(void *list, ALuint source) {
 }
 #endif
 
+// loop a list of sound
 void playSoundList(soundList *s) {
-#if 0
 	if (soundOK) {
-		cacheLoopySound = true;
-		int a = cacheSound(s->sound);
+		// Load sound
+		Audio::AudioStream *stream;
+		int a = makeSoundAudioStream(s->sound, stream, true);
 		if (a == -1) {
 			debugOut("Failed to cache sound!\n");
 			return;
 		}
+
+		// Play sound
 		soundCache[a].looping = false;
 		if (s->vol < 0)
-		soundCache[a].vol = defSoundVol;
+			soundCache[a].vol = defSoundVol;
 		else
-		soundCache[a].vol = s->vol;
+			soundCache[a].vol = s->vol;
 		s-> cacheIndex = a;
-
-		ALboolean ok;
-		ALuint src;
-		soundThing *st;
-
-		st = &soundCache[a];
-
-		alGenSources(1, &src);
-		if (alGetError() != AL_NO_ERROR) {
-			debugOut("Failed to create OpenAL source!\n");
-			return;
-		}
-
-		alSourcef(src, AL_GAIN, (float) soundCache[a].vol / 256);
-
-		ok = alurePlaySourceStream(src, (*st).stream,
-				NUM_BUFS, 0, list_eos_callback, s);
-
-		if (!ok) {
-
-			debugOut("Failed to play stream: %s\n", alureGetErrorString());
-			alDeleteSources(1, &src);
-			if (alGetError() != AL_NO_ERROR) {
-				debugOut("Failed to delete OpenAL source!\n");
-			}
-
-			(*st).playingOnSource = 0;
-		} else {
-			(*st).playingOnSource = src;
-			(*st).playing = true;
-		}
+		g_sludge->_mixer->playStream(Audio::Mixer::kSFXSoundType, &soundCache[a].handle, stream, -1, soundCache[a].vol);
 	}
-#endif
 }
 
 void playMovieStream(int a) {


Commit: 36d078cfe42572d298ccd5840ca7a5bd13f4c23d
    https://github.com/scummvm/scummvm/commit/36d078cfe42572d298ccd5840ca7a5bd13f4c23d
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: add sound loop test game

game links: https://github.com/yinsimei/sludge-test-games

Changed paths:
    engines/sludge/detection_tables.h


diff --git a/engines/sludge/detection_tables.h b/engines/sludge/detection_tables.h
index 5d366d7..72df456 100644
--- a/engines/sludge/detection_tables.h
+++ b/engines/sludge/detection_tables.h
@@ -53,7 +53,7 @@ static const SludgeGameDescription gameDescriptions[] = {
 		{
 			"welcomeloop",
 			"",
-			AD_ENTRY1s("WelcomeLoop.slg", "af6e20c7cfae9101f1a49236d45014ef", 34932),
+			AD_ENTRY1s("WelcomeLoop.slg", "89c67f14f88cfb54989847ef0cbb0d3b", 36947),
 			Common::EN_ANY,
 			Common::kPlatformUnknown,
 			ADGF_NO_FLAGS,


Commit: 15c7958d57a6b92f3e5fc20ec4c5043c249b81fa
    https://github.com/scummvm/scummvm/commit/15c7958d57a6b92f3e5fc20ec4c5043c249b81fa
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: add sound loop for wav and ogg

Changed paths:
    engines/sludge/main_loop.cpp
    engines/sludge/sound.cpp
    engines/sludge/sound.h


diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index 6655b9b..8b12ddd 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -380,6 +380,7 @@ int main_loop(const char *filename)
 		walkAllPeople();
 		handleInput();
 		sludgeDisplay();
+		handleSoundLists();
 		g_system->delayMillis(100);
 #if 0
 		Wait_Frame();
diff --git a/engines/sludge/sound.cpp b/engines/sludge/sound.cpp
index 88604dd..4278d4b 100644
--- a/engines/sludge/sound.cpp
+++ b/engines/sludge/sound.cpp
@@ -22,6 +22,7 @@
 
 #include "common/debug.h"
 #include "common/file.h"
+#include "common/list.h"
 #include "common/memstream.h"
 
 #include "audio/audiostream.h"
@@ -47,6 +48,10 @@ namespace Sludge {
 bool soundOK = false;
 bool SilenceIKillYou = false;
 
+// there's possibility that several sound list played at the same time
+typedef Common::List<soundList *> SoundListHandles;
+SoundListHandles soundListHandles;
+
 struct soundThing {
 	Audio::SoundHandle handle;
 	int fileLoaded, vol;    //Used for sounds only. (sound saving/loading)
@@ -155,47 +160,6 @@ void setSoundLoop(int a, int s, int e) {
 }
 
 /*
- * End of stream callbacks:
- */
-
-#if 0
-static void sound_eos_callback(void *cacheIndex, ALuint source) {
-	int *a = (int *)cacheIndex;
-
-	alDeleteSources(1, &source);
-	if (alGetError() != AL_NO_ERROR) {
-		debugOut("Failed to delete OpenAL source!\n");
-	}
-
-	soundCache[*a].playingOnSource = 0;
-	soundCache[*a].playing = false;
-	soundCache[*a].looping = false;
-
-}
-#endif
-
-#if 0
-static void mod_eos_callback(void *cacheIndex, ALuint source) {
-	int *a = (int *)cacheIndex;
-
-	alDeleteSources(1, &source);
-	if (alGetError() != AL_NO_ERROR) {
-		debugOut("Failed to delete OpenAL source!\n");
-	}
-
-	modCache[*a].playingOnSource = 0;
-
-	if (! alureDestroyStream(modCache[*a].stream, 0, NULL)) {
-		debugOut("Failed to destroy stream: %s\n",
-				alureGetErrorString());
-	}
-
-	modCache[*a].stream = NULL;
-	modCache[*a].playing = false;
-}
-#endif
-
-/*
  * Stopping things:
  */
 
@@ -511,10 +475,10 @@ bool getSoundCacheStack(stackHandler *sH) {
 	return true;
 }
 
-soundList *deleteSoundFromList(soundList *s) {
+bool deleteSoundFromList(soundList *&s) {
 	// Don't delete a playing sound.
 	if (s->cacheIndex)
-		return NULL;
+		return false;
 
 	soundList *o = NULL;
 	if (!s->next) {
@@ -522,7 +486,8 @@ soundList *deleteSoundFromList(soundList *s) {
 		if (o)
 			o->next = NULL;
 		delete s;
-		return o;
+		s = o;
+		return (s != NULL);
 	}
 	if (s != s->next) {
 		o = s->next;
@@ -531,51 +496,56 @@ soundList *deleteSoundFromList(soundList *s) {
 			o->prev->next = o;
 	}
 	delete s;
-	return o;
+	s = o;
+	return (s != NULL);
 }
 
-#if 0
-static void list_eos_callback(void *list, ALuint source) {
-	soundList *s = (soundList *) list;
-
-	int a = s->cacheIndex;
-#if 0
-	alDeleteSources(1, &source);
-	if (alGetError() != AL_NO_ERROR) {
-		debugOut("Failed to delete OpenAL source!\n");
-	}
-#endif
-	soundCache[a].playingOnSource = 0;
-	soundCache[a].playing = false;
-	soundCache[a].looping = false;
-	s-> cacheIndex = false;
-	if (SilenceIKillYou) {
-		while (s = deleteSoundFromList(s));
-	} else {
-		if (s->next) {
-			if (s->next == s) {
-				int v = defSoundVol;
-				defSoundVol = soundCache[a].vol;
-				startSound(s->sound, true);
-				defSoundVol = v;
-				while (s = deleteSoundFromList(s));
-				return;
+void handleSoundLists() {
+	for (SoundListHandles::iterator it = soundListHandles.begin(); it != soundListHandles.end(); ++it) {
+		soundList *s = (*it);
+		int a = s->cacheIndex;
+		bool remove = false;
+		if (!g_sludge->_mixer->isSoundHandleActive(soundCache[a].handle)) { // reach the end of stream
+			s->cacheIndex = false;
+			if (SilenceIKillYou) {
+				while (deleteSoundFromList(s))
+					;
+				remove = (s == NULL); // s not null if still playing
+			} else {
+				if (s->next) {
+					if (s->next == s) { // loop the same sound
+						int v = defSoundVol;
+						defSoundVol = soundCache[a].vol;
+						startSound(s->sound, true);
+						defSoundVol = v;
+						while (deleteSoundFromList(s))
+							;
+						remove = (s == NULL); // s not null if still playing
+					} else { // repush the next sound list
+						s->next->vol = soundCache[a].vol;
+						playSoundList(s->next);
+						remove = true; // remove this one
+					}
+
+				} else {
+					while (deleteSoundFromList(s))
+						;
+					remove = (s == NULL); // s not null if still playing
+				}
 			}
-			s->next->vol = soundCache[a].vol;
-			playSoundList(s->next);
-		} else {
-			while (s = deleteSoundFromList(s));
+		}
+		if (remove) {
+			it = soundListHandles.reverse_erase(it);
 		}
 	}
 }
-#endif
 
 // loop a list of sound
 void playSoundList(soundList *s) {
 	if (soundOK) {
 		// Load sound
 		Audio::AudioStream *stream;
-		int a = makeSoundAudioStream(s->sound, stream, true);
+		int a = makeSoundAudioStream(s->sound, stream, false);
 		if (a == -1) {
 			debugOut("Failed to cache sound!\n");
 			return;
@@ -589,6 +559,10 @@ void playSoundList(soundList *s) {
 			soundCache[a].vol = s->vol;
 		s-> cacheIndex = a;
 		g_sludge->_mixer->playStream(Audio::Mixer::kSFXSoundType, &soundCache[a].handle, stream, -1, soundCache[a].vol);
+
+		// push sound list
+		soundListHandles.push_back(s);
+
 	}
 }
 
diff --git a/engines/sludge/sound.h b/engines/sludge/sound.h
index 2e31943..05db6a4 100644
--- a/engines/sludge/sound.h
+++ b/engines/sludge/sound.h
@@ -39,8 +39,9 @@ struct soundList {
 	int cacheIndex;
 	int vol;
 };
-soundList *deleteSoundFromList(soundList *s);
+bool deleteSoundFromList(soundList *&s);
 void playSoundList(soundList *s);
+void handleSoundLists(); // to produce the same effects as end of stream call back functions
 
 // GENERAL...
 bool initSoundStuff(HWND);


Commit: 5baae657fd42f5635024cd659c04a1160fdddaf7
    https://github.com/scummvm/scummvm/commit/5baae657fd42f5635024cd659c04a1160fdddaf7
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: cache of ended sound in playlist won't be used before handled

Changed paths:
    engines/sludge/sound.cpp


diff --git a/engines/sludge/sound.cpp b/engines/sludge/sound.cpp
index 4278d4b..56a28d8 100644
--- a/engines/sludge/sound.cpp
+++ b/engines/sludge/sound.cpp
@@ -47,7 +47,7 @@ namespace Sludge {
 
 bool soundOK = false;
 bool SilenceIKillYou = false;
-
+bool isHandlingSoundList = false;
 // there's possibility that several sound list played at the same time
 typedef Common::List<soundList *> SoundListHandles;
 SoundListHandles soundListHandles;
@@ -56,13 +56,13 @@ struct soundThing {
 	Audio::SoundHandle handle;
 	int fileLoaded, vol;    //Used for sounds only. (sound saving/loading)
 	bool looping;      		//Used for sounds only. (sound saving/loading)
+	bool inSoundList;
 };
 
 soundThing soundCache[MAX_SAMPLES];
 #if 0
 soundThing modCache[MAX_MODS];
 #endif
-int intpointers[MAX_SAMPLES];
 
 int defVol = 128;
 int defSoundVol = 255;
@@ -76,7 +76,7 @@ bool initSoundStuff(HWND hwnd) {
 	for (int a = 0; a < MAX_SAMPLES; a ++) {
 		soundCache[a].fileLoaded = -1;
 		soundCache[a].looping = false;
-		intpointers[a] = a;
+		soundCache[a].inSoundList = false;
 	}
 #if 0
 	for (int a = 0; a < MAX_MODS; a ++) {
@@ -215,6 +215,8 @@ void freeSound(int a) {
 
 	if (g_sludge->_mixer->isSoundHandleActive(soundCache[a].handle)) {
 		g_sludge->_mixer->stopHandle(soundCache[a].handle);
+		if (soundCache[a].inSoundList)
+			handleSoundLists();
 	}
 
 	soundCache[a].fileLoaded = -1;
@@ -340,7 +342,7 @@ int findEmptySoundSlot() {
 	for (int t = 0; t < MAX_SAMPLES; t++) {
 		emptySoundSlot++;
 		emptySoundSlot %= MAX_SAMPLES;
-		if (!g_sludge->_mixer->isSoundHandleActive(soundCache[emptySoundSlot].handle))
+		if (!g_sludge->_mixer->isSoundHandleActive(soundCache[emptySoundSlot].handle) && !soundCache[emptySoundSlot].inSoundList)
 			return emptySoundSlot;
 	}
 
@@ -349,7 +351,7 @@ int findEmptySoundSlot() {
 	for (int t = 0; t < MAX_SAMPLES; t++) {
 		emptySoundSlot++;
 		emptySoundSlot %= MAX_SAMPLES;
-		if (!soundCache[emptySoundSlot].looping)
+		if (!soundCache[emptySoundSlot].looping && !soundCache[emptySoundSlot].inSoundList)
 			return emptySoundSlot;
 	}
 
@@ -373,6 +375,9 @@ int makeSoundAudioStream(int f, Audio::AudioStream *&audiostream, bool loopy) {
 		// still playing
 		if (g_sludge->_mixer->isSoundHandleActive(soundCache[a].handle)) {
 			g_sludge->_mixer->stopHandle(soundCache[a].handle); // stop it
+			if (soundCache[a].inSoundList) {
+				handleSoundLists();
+			}
 		}
 	} else {
 		if (f == -2)
@@ -501,12 +506,16 @@ bool deleteSoundFromList(soundList *&s) {
 }
 
 void handleSoundLists() {
+	if (isHandlingSoundList)
+		return;
+	isHandlingSoundList = true;
 	for (SoundListHandles::iterator it = soundListHandles.begin(); it != soundListHandles.end(); ++it) {
 		soundList *s = (*it);
 		int a = s->cacheIndex;
 		bool remove = false;
 		if (!g_sludge->_mixer->isSoundHandleActive(soundCache[a].handle)) { // reach the end of stream
 			s->cacheIndex = false;
+			soundCache[a].inSoundList = false;
 			if (SilenceIKillYou) {
 				while (deleteSoundFromList(s))
 					;
@@ -538,6 +547,7 @@ void handleSoundLists() {
 			it = soundListHandles.reverse_erase(it);
 		}
 	}
+	isHandlingSoundList = false;
 }
 
 // loop a list of sound
@@ -559,6 +569,7 @@ void playSoundList(soundList *s) {
 			soundCache[a].vol = s->vol;
 		s-> cacheIndex = a;
 		g_sludge->_mixer->playStream(Audio::Mixer::kSFXSoundType, &soundCache[a].handle, stream, -1, soundCache[a].vol);
+		soundCache[a].inSoundList = true;
 
 		// push sound list
 		soundListHandles.push_back(s);


Commit: bbde5f4bf4d46bc0c6f32cc197f698aa89676f70
    https://github.com/scummvm/scummvm/commit/bbde5f4bf4d46bc0c6f32cc197f698aa89676f70
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove #ifndef of cursor display and formatting code

Changed paths:
    engines/sludge/cursors.cpp
    engines/sludge/sprites.cpp


diff --git a/engines/sludge/cursors.cpp b/engines/sludge/cursors.cpp
index 519b636..232dca8 100644
--- a/engines/sludge/cursors.cpp
+++ b/engines/sludge/cursors.cpp
@@ -43,40 +43,37 @@ void pickAnimCursor(personaAnimation *pp) {
 }
 
 void displayCursor() {
-#if 0
-	if (mouseCursorAnim && mouseCursorAnim -> numFrames) {
+	if (mouseCursorAnim && mouseCursorAnim->numFrames) {
 
-		int spriteNum = mouseCursorAnim -> frames[mouseCursorFrameNum].frameNum;
+		int spriteNum = mouseCursorAnim->frames[mouseCursorFrameNum].frameNum;
 		int flipMe = 0;
 
 		if (spriteNum < 0) {
 			spriteNum = -spriteNum;
 			flipMe = 1;
-			if (spriteNum >= mouseCursorAnim -> theSprites -> bank.total) spriteNum = 0;
+			if (spriteNum >= mouseCursorAnim->theSprites->bank.total)
+				spriteNum = 0;
 		} else {
-			if (spriteNum >= mouseCursorAnim -> theSprites -> bank.total) flipMe = 2;
+			if (spriteNum >= mouseCursorAnim->theSprites->bank.total)
+				flipMe = 2;
 		}
 
 		if (flipMe != 2) {
-			(flipMe ? flipFontSprite : fontSprite)(input.mouseX, input.mouseY,
-					mouseCursorAnim -> theSprites -> bank.sprites[spriteNum],
-					mouseCursorAnim -> theSprites -> bank.myPalette /* ( spritePalette&) NULL*/);
+			(flipMe ? flipFontSprite : fontSprite)(input.mouseX, input.mouseY, mouseCursorAnim->theSprites->bank.sprites[spriteNum],
+					mouseCursorAnim->theSprites->bank.myPalette /* ( spritePalette&) NULL*/);
 		}
 
-		if (++ mouseCursorCountUp >= mouseCursorAnim -> frames[mouseCursorFrameNum].howMany) {
+		if (++mouseCursorCountUp >= mouseCursorAnim->frames[mouseCursorFrameNum].howMany) {
 			mouseCursorCountUp = 0;
-			mouseCursorFrameNum ++;
-			mouseCursorFrameNum %= mouseCursorAnim -> numFrames;
+			mouseCursorFrameNum++;
+			mouseCursorFrameNum %= mouseCursorAnim->numFrames;
 		}
 	}
-#endif
 }
 
 void pasteCursor(int x, int y, personaAnimation *c) {
 	if (c->numFrames)
-		pasteSpriteToBackDrop(x, y,
-				c->theSprites->bank.sprites[c->frames[0].frameNum],
-				c->theSprites->bank.myPalette);
+		pasteSpriteToBackDrop(x, y, c->theSprites->bank.sprites[c->frames[0].frameNum], c->theSprites->bank.myPalette);
 }
 
 } // End of namespace Sludge
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index b6701d4..1837095 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -501,9 +501,13 @@ void fontSprite(bool flip, int x, int y, sprite &single, const spritePalette &fo
 
 	// Use Transparent surface to scale and blit
 	Graphics::TransparentSurface tmp(single.surface, false);
-	Graphics::TransparentSurface tmp2(single.burnSurface, false);
 	tmp.blit(renderSurface, x1, y1, (flip? Graphics::FLIP_H : Graphics::FLIP_NONE));
-	tmp2.blit(renderSurface, x1, y1, (flip? Graphics::FLIP_H : Graphics::FLIP_NONE), 0, TS_RGB(fontPal.originalRed, fontPal.originalGreen, fontPal.originalBlue));
+
+	if (single.burnSurface.getPixels() != nullptr) {
+		Graphics::TransparentSurface tmp2(single.burnSurface, false);
+		tmp2.blit(renderSurface, x1, y1, (flip? Graphics::FLIP_H : Graphics::FLIP_NONE), 0, TS_RGB(fontPal.originalRed, fontPal.originalGreen, fontPal.originalBlue));
+
+	}
 
 #if 0
 	float x2 = x1 + (float) single.surface.w / cameraZoom;


Commit: 0eb18c26276ac15c28fa2fb5f6163999eeeb9caf
    https://github.com/scummvm/scummvm/commit/0eb18c26276ac15c28fa2fb5f6163999eeeb9caf
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: set to right delay time

Changed paths:
    engines/sludge/main_loop.cpp


diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index 8b12ddd..a7b209f 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -60,6 +60,7 @@ HWND hMainWindow = NULL;
 int realWinWidth = 640, realWinHeight = 480;
 extern float cameraZoom;
 
+extern int desiredfps;
 extern int specialSettings;
 extern inputType input;
 extern variableStack *noStack;
@@ -381,7 +382,7 @@ int main_loop(const char *filename)
 		handleInput();
 		sludgeDisplay();
 		handleSoundLists();
-		g_system->delayMillis(100);
+		g_system->delayMillis(1000 / desiredfps);
 #if 0
 		Wait_Frame();
 #endif


Commit: 536ddf7e89b2b1d3c4541944dff3779c6551c5a7
    https://github.com/scummvm/scummvm/commit/536ddf7e89b2b1d3c4541944dff3779c6551c5a7
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: change struct texture to Surface

Changed paths:
    engines/sludge/backdrop.cpp
    engines/sludge/backdrop.h
    engines/sludge/graphics.h


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index 850a23d..3904cf5 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -57,7 +57,7 @@ GLfloat backdropTexH = 1.0;
 GLuint snapshotTextureName = 0;
 #endif
 
-texture lightMap;
+Graphics::Surface lightMap;
 Graphics::Surface backdropSurface;
 
 float snapTexW = 1.0;
@@ -215,8 +215,8 @@ void killBackDrop() {
 }
 
 void killLightMap() {
-	if (lightMap.surface.getPixels()) {
-		lightMap.surface.free();
+	if (lightMap.getPixels()) {
+		lightMap.free();
 	}
 	lightMapNumber = 0;
 #if 0
@@ -619,14 +619,14 @@ bool loadLightMap(int v) {
 	killLightMap();
 	lightMapNumber = v;
 
-	if (!ImgLoader::loadImage(bigDataFile, &lightMap.surface))
+	if (!ImgLoader::loadImage(bigDataFile, &lightMap))
 		return false;
 
-	int newPicWidth = lightMap.surface.w;
-	int newPicHeight = lightMap.surface.h;
+	int newPicWidth = lightMap.w;
+	int newPicHeight = lightMap.h;
 
 	if (lightMapMode == LIGHTMAPMODE_HOTSPOT) {
-		if (lightMap.surface.w != sceneWidth || lightMap.surface.h != sceneHeight) {
+		if (lightMap.w != sceneWidth || lightMap.h != sceneHeight) {
 			return fatal("Light map width and height don't match scene width and height. That is required for lightmaps in HOTSPOT mode.");
 		}
 	}
diff --git a/engines/sludge/backdrop.h b/engines/sludge/backdrop.h
index a381389..e614c4a 100644
--- a/engines/sludge/backdrop.h
+++ b/engines/sludge/backdrop.h
@@ -73,7 +73,7 @@ bool getRGBIntoStack(unsigned int x, unsigned int y, stackHandler *sH);
 void killLightMap();
 bool loadLightMap(int v);
 
-extern texture lightMap;
+extern Graphics::Surface lightMap;
 
 // And background parallax scrolling
 
diff --git a/engines/sludge/graphics.h b/engines/sludge/graphics.h
index b6d82ab..444d8a4 100644
--- a/engines/sludge/graphics.h
+++ b/engines/sludge/graphics.h
@@ -26,15 +26,6 @@
 
 namespace Sludge {
 
-struct texture {
-#if 0
-	GLubyte *data;
-	GLuint name;
-	double texW, texH;
-#endif
-	Graphics::Surface surface;
-};
-
 #if 0
 struct shaders {
 	GLuint paste;


Commit: e52dbca7fd9cd972f529f38346a2706a519cc310
    https://github.com/scummvm/scummvm/commit/e52dbca7fd9cd972f529f38346a2706a519cc310
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove unused variable in parallaxLayer

Changed paths:
    engines/sludge/backdrop.cpp
    engines/sludge/backdrop.h


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index 3904cf5..dc46c41 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -735,7 +735,7 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 
 	if (fracX == 65535) {
 		nP->wrapS = false;
-		if (nP->width < winWidth) {
+		if (nP->surface.w < winWidth) {
 			fatal("For AUTOFIT parallax backgrounds, the image must be at least as wide as the game window/screen.");
 			return false;
 		}
@@ -745,7 +745,7 @@ bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY)
 
 	if (fracY == 65535) {
 		nP->wrapT = false;
-		if (nP->height < winHeight) {
+		if (nP->surface.h < winHeight) {
 			fatal("For AUTOFIT parallax backgrounds, the image must be at least as tall as the game window/screen.");
 			return false;
 		}
diff --git a/engines/sludge/backdrop.h b/engines/sludge/backdrop.h
index e614c4a..216b656 100644
--- a/engines/sludge/backdrop.h
+++ b/engines/sludge/backdrop.h
@@ -40,7 +40,7 @@ extern int lightMapMode;
 
 struct parallaxLayer {
 	Graphics::Surface surface;
-	int width, height, speedX, speedY;
+	int speedX, speedY;
 	bool wrapS, wrapT;
 	unsigned short fileNum, fractionX, fractionY;
 	int cameraX, cameraY;


Commit: 941889123799d0d5b65f8ad63576427c5d80b043
    https://github.com/scummvm/scummvm/commit/941889123799d0d5b65f8ad63576427c5d80b043
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: get freeze and unfreeze scene work

Changed paths:
    engines/sludge/backdrop.cpp
    engines/sludge/freeze.cpp
    engines/sludge/freeze.h
    engines/sludge/zbuffer.h


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index dc46c41..a1f656f 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -24,6 +24,7 @@
 #include "common/rect.h"
 #include "image/png.h"
 #include "graphics/surface.h"
+#include "graphics/transparent_surface.h"
 #include "graphics/palette.h"
 
 #include "sludge/allfiles.h"
@@ -50,13 +51,14 @@ void unfreeze(bool);    // Because FREEZE.H needs a load of other includes
 #if 0
 GLubyte *backdropTexture = NULL;
 GLuint backdropTextureName = 0;
-bool backdropExists = false;
 GLfloat backdropTexW = 1.0;
 GLfloat backdropTexH = 1.0;
 
 GLuint snapshotTextureName = 0;
 #endif
 
+bool backdropExists = false;
+
 Graphics::Surface lightMap;
 Graphics::Surface backdropSurface;
 
@@ -210,8 +212,8 @@ void killBackDrop() {
 #if 0
 	deleteTextures(1, &backdropTextureName);
 	backdropTextureName = 0;
-	backdropExists = false;
 #endif
+	backdropExists = false;
 }
 
 void killLightMap() {
@@ -935,19 +937,19 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 	renderToTexture(tmpTex, x, y, picWidth, picHeight, realPicWidth, realPicHeight);
 
 	deleteTextures(1, &tmpTex);
-
-	backdropExists = true;
 #endif
+	backdropExists = true;
 	return true;
 }
 
 bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 	debug(kSludgeDebugGraphics, "Load mixHSI");
-	if (!ImgLoader::loadImage(stream, &backdropSurface, 0))
+	Graphics::Surface mixSurface;
+	if (!ImgLoader::loadImage(stream, &mixSurface, 0))
 		return false;
 
-	int realPicWidth = backdropSurface.w;
-	int realPicHeight = backdropSurface.h;
+	int realPicWidth = mixSurface.w;
+	int realPicHeight = mixSurface.h;
 
 	if (x == IN_THE_CENTRE)
 		x = (sceneWidth - realPicWidth) >> 1;
@@ -955,6 +957,11 @@ bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 		y = (sceneHeight - realPicHeight) >> 1;
 	if (x < 0 || x + realPicWidth > sceneWidth || y < 0 || y + realPicHeight > sceneHeight)
 		return false;
+
+	Graphics::TransparentSurface tmp(mixSurface, false);
+	tmp.blit(backdropSurface, x, y);
+	mixSurface.free();
+;
 #if 0
 	float btx1, tx1;
 	float btx2, tx2;
diff --git a/engines/sludge/freeze.cpp b/engines/sludge/freeze.cpp
index 676c06b..57d7d0d 100644
--- a/engines/sludge/freeze.cpp
+++ b/engines/sludge/freeze.cpp
@@ -26,6 +26,7 @@
 #include "sludge/sprites.h"
 #include "sludge/sprbanks.h"
 #include "sludge/people.h"
+#include "sludge/sludge.h"
 #include "sludge/sludger.h"
 #include "sludge/objtypes.h"
 #include "sludge/region.h"
@@ -43,9 +44,8 @@ extern screenRegion *allScreenRegions;
 extern screenRegion *overRegion;
 extern speechStruct *speech;
 extern inputType input;
-#if 0
-extern GLuint backdropTextureName;
-#endif
+extern Graphics::Surface backdropSurface;
+extern Graphics::Surface renderSurface;
 extern parallaxLayer *parallaxStuff;
 extern int lightMapNumber, zBufferNumber;
 extern eventHandlers *currentEvents;
@@ -58,33 +58,17 @@ extern zBufferData zBuffer;
 extern bool backdropExists;
 frozenStuffStruct *frozenStuff = NULL;
 extern unsigned int sceneWidth, sceneHeight;
+Graphics::Surface freezeSurface;
 
 void shufflePeople();
-#if 0
-GLuint freezeTextureName = 0;
-#endif
 
 void freezeGraphics() {
-#if 0
-	glViewport(0, 0, realWinWidth, realWinHeight);
 
-	glGenTextures(1, &freezeTextureName);
-#endif
 	int w = winWidth;
 	int h = winHeight;
-	if (!NPOT_textures) {
-		w = getNextPOT(winWidth);
-		h = getNextPOT(winHeight);
-	}
-#if 0
-	glBindTexture(GL_TEXTURE_2D, freezeTextureName);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-
-	texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0, freezeTextureName);
-#endif
+
+	freezeSurface.create(w, h, *g_sludge->getScreenPixelFormat());
+
 	// Temporarily disable AA
 	int antiAlias = gameSettings.antiAlias;
 	gameSettings.antiAlias = 0;
@@ -106,45 +90,17 @@ void freezeGraphics() {
 			} else {
 				h = realWinHeight;
 			}
-#if 0
-			const GLfloat bPMVMatrix[] = {
-				2.0f / realWinWidth * cameraZoom, .0, .0, .0,
-				.0, 2.0f / realWinHeight * cameraZoom, .0, .0,
-				.0, .0, 1.0f, .0,
-				-2.0f * (x / realWinWidth) - 1.0f, -2.0f * (y / realWinHeight) - 1.0f, .0, 1.0f
-
-			};
-			for (int i = 0; i < 16; i++) {
-				aPMVMatrix[i] = bPMVMatrix[i];
-			}
-			// Render scene
-			glDepthMask(GL_TRUE);
-			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Clear The Screen
-			glDepthMask(GL_FALSE);
-
 			drawBackDrop();// Draw the room
 			drawZBuffer(cameraX, cameraY, false);
-
-			glEnable(GL_DEPTH_TEST);
-
 			drawPeople();// Then add any moving characters...
+			freezeSurface.copyFrom(renderSurface);
 
-			glDisable(GL_DEPTH_TEST);
-
-			// Copy Our ViewPort To The Texture
-			copyTexSubImage2D(GL_TEXTURE_2D, 0, x, y, 0, 0, w, h, freezeTextureName);
-#endif
 			y += h;
 		}
 		x += w;
 	}
 
 	gameSettings.antiAlias = antiAlias;
-
-#if 0
-	glViewport(viewportOffsetX, viewportOffsetY, viewportWidth, viewportHeight);
-	setPixelCoords(false);
-#endif
 }
 
 bool freeze() {
@@ -155,77 +111,36 @@ bool freeze() {
 
 	// Grab a copy of the current scene
 	freezeGraphics();
-#if 0
-	newFreezer->backdropTextureName = backdropTextureName;
-#endif
 	int picWidth = sceneWidth;
 	int picHeight = sceneHeight;
 	if (!NPOT_textures) {
 		picWidth = getNextPOT(picWidth);
 		picHeight = getNextPOT(picHeight);
 	}
-#if 0
-	newFreezer->backdropTexture = new GLubyte[picHeight * picWidth * 4];
-	if (!checkNew(newFreezer->backdropTexture))
-		return false;
-
-	saveTexture(backdropTextureName, newFreezer->backdropTexture);
-
-	backdropTextureName = 0;
-#endif
+	newFreezer->backdropSurface.copyFrom(backdropSurface);
 	newFreezer->sceneWidth = sceneWidth;
 	newFreezer->sceneHeight = sceneHeight;
 	newFreezer->cameraX = cameraX;
 	newFreezer->cameraY = cameraY;
 	newFreezer->cameraZoom = cameraZoom;
-#if 0
-	newFreezer->lightMapTexture = lightMap.data;
-	newFreezer->lightMapTextureName = lightMap.name;
+
+	newFreezer->lightMapSurface.copyFrom(lightMap);
 	newFreezer->lightMapNumber = lightMapNumber;
-	lightMap.data = NULL;
-	lightMap.name = 0;
+
 	newFreezer->parallaxStuff = parallaxStuff;
 	parallaxStuff = NULL;
-	newFreezer->zBufferImage = zBuffer.tex;
+	newFreezer->zBufferImage.copyFrom(zBuffer.surface);
 	newFreezer->zBufferNumber = zBuffer.originalNum;
 	newFreezer->zPanels = zBuffer.numPanels;
-	zBuffer.tex = NULL;
-#endif
+	zBuffer.surface.free();
 	// resizeBackdrop kills parallax stuff, light map, z-buffer...
 	if (!killResizeBackdrop(winWidth, winHeight))
 		return fatal("Can't create new temporary backdrop buffer");
 
-	if (!NPOT_textures) {
-		picWidth = getNextPOT(sceneWidth);
-		picHeight = getNextPOT(sceneHeight);
-#if 0
-		backdropTexW = (double)sceneWidth / picWidth;
-		backdropTexH = (double)sceneHeight / picHeight;
-#endif
-	}
-
-#if 0
 	// Copy the old scene to the new backdrop
-	deleteTextures(1, &backdropTextureName);
-	backdropTextureName = freezeTextureName;
+	backdropSurface.copyFrom(freezeSurface);
 	backdropExists = true;
 
-	// Free texture memory used by old stuff
-	parallaxStuff = newFreezer->parallaxStuff;
-	while (parallaxStuff) {
-		deleteTextures(1, &parallaxStuff->textureName);
-		parallaxStuff = parallaxStuff->next;
-	}
-	if (newFreezer->zBufferImage) {
-		deleteTextures(1, &zBuffer.texName);
-	}
-	if (newFreezer->lightMapTextureName) {
-		deleteTextures(1, &newFreezer->lightMapTextureName);
-	}
-	if (newFreezer->backdropTextureName) {
-		deleteTextures(1, &newFreezer->backdropTextureName);
-	}
-#endif
 	newFreezer->allPeople = allPeople;
 	allPeople = NULL;
 
@@ -268,10 +183,6 @@ int howFrozen() {
 	return a;
 }
 
-#if 0
-extern GLubyte *backdropTexture;
-#endif
-
 void unfreeze(bool killImage) {
 	frozenStuffStruct *killMe = frozenStuff;
 
@@ -297,21 +208,18 @@ void unfreeze(bool killImage) {
 	allScreenRegions = frozenStuff->allScreenRegions;
 
 	killLightMap();
-#if 0
-	lightMap.data = frozenStuff->lightMapTexture;
-	lightMap.name = frozenStuff->lightMapTextureName;
+
+	lightMap.copyFrom(frozenStuff->lightMapSurface);
 	lightMapNumber = frozenStuff->lightMapNumber;
 	if (lightMapNumber) {
-		lightMap.name = 0;
 		loadLightMap(lightMapNumber);
 	}
 
 	killZBuffer();
-	zBuffer.tex = frozenStuff->zBufferImage;
+	zBuffer.surface.copyFrom(frozenStuff->zBufferImage);
 	zBuffer.originalNum = frozenStuff->zBufferNumber;
 	zBuffer.numPanels = frozenStuff->zPanels;
 	if (zBuffer.numPanels) {
-		zBuffer.texName = 0;
 		setZBuffer(zBuffer.originalNum);
 	}
 
@@ -321,36 +229,11 @@ void unfreeze(bool killImage) {
 
 	if (killImage)
 		killBackDrop();
-	backdropTextureName = frozenStuff->backdropTextureName;
-	if (backdropTexture)
-		delete[] backdropTexture;
-	backdropTexture = frozenStuff->backdropTexture;
+	if (backdropSurface.getPixels())
+		backdropSurface.free();
+	backdropSurface.copyFrom(frozenStuff->backdropSurface);
 	backdropExists = true;
-	if (backdropTextureName) {
-		backdropTextureName = 0;
-		glGenTextures(1, &backdropTextureName);
-		glBindTexture(GL_TEXTURE_2D, backdropTextureName);
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-
-		if (gameSettings.antiAlias < 0) {
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-		} else {
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-		}
 
-		int picWidth = sceneWidth;
-		int picHeight = sceneHeight;
-		if (!NPOT_textures) {
-			picWidth = getNextPOT(picWidth);
-			picHeight = getNextPOT(picHeight);
-		}
-		// Restore the backdrop
-		texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, frozenStuff->backdropTexture, backdropTextureName);
-	}
-#endif
 	deleteAnim(mouseCursorAnim);
 	mouseCursorAnim = frozenStuff->mouseCursorAnim;
 	mouseCursorFrameNum = frozenStuff->mouseCursorFrameNum;
diff --git a/engines/sludge/freeze.h b/engines/sludge/freeze.h
index 4472852..cfd5747 100644
--- a/engines/sludge/freeze.h
+++ b/engines/sludge/freeze.h
@@ -22,18 +22,16 @@
 #ifndef SLUDGE_FREEZE_H
 #define SLUDGE_FREEZE_H
 
+#include "graphics/surface.h"
+
 namespace Sludge {
 
 struct frozenStuffStruct {
 	onScreenPerson *allPeople;
 	screenRegion *allScreenRegions;
-#if 0
-	GLubyte *backdropTexture;
-	GLuint backdropTextureName;
-	GLuint lightMapTextureName;
-	GLubyte *lightMapTexture;
-	GLubyte *zBufferImage;
-#endif
+	Graphics::Surface backdropSurface;
+	Graphics::Surface lightMapSurface;
+	Graphics::Surface zBufferImage;
 	int zPanels;
 	parallaxLayer *parallaxStuff;
 	int lightMapNumber, zBufferNumber;
diff --git a/engines/sludge/zbuffer.h b/engines/sludge/zbuffer.h
index bb0b2ed..f78b655 100644
--- a/engines/sludge/zbuffer.h
+++ b/engines/sludge/zbuffer.h
@@ -22,15 +22,18 @@
 #ifndef SLUDGE_ZBUFFER_H
 #define SLUDGE_ZBUFFER_H
 
+#include "graphics/surface.h"
+
 namespace Sludge {
 
 struct zBufferData {
-	int width, height;
 //	bool loaded;
 	int numPanels;
 	int panel[16];
 	int originalNum;
+	Graphics::Surface surface;
 #if 0
+	int width, height;
 	GLubyte *tex;
 	GLuint texName;
 #endif


Commit: 43ffa3bcc830c5fc8fe6818ad05d0407236b3709
    https://github.com/scummvm/scummvm/commit/43ffa3bcc830c5fc8fe6818ad05d0407236b3709
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: give a 0.5 opacity for mixOverlay image

Changed paths:
    engines/sludge/backdrop.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index a1f656f..7c21183 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -959,7 +959,7 @@ bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 		return false;
 
 	Graphics::TransparentSurface tmp(mixSurface, false);
-	tmp.blit(backdropSurface, x, y);
+	tmp.blit(backdropSurface, x, y, Graphics::FLIP_NONE, nullptr, TS_ARGB(255, 255 >> 1, 255, 255));
 	mixSurface.free();
 ;
 #if 0


Commit: ea1f2412ee18e5825f28d7ea64586c163647f4ea
    https://github.com/scummvm/scummvm/commit/ea1f2412ee18e5825f28d7ea64586c163647f4ea
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: get input work by replacing sdl event by scummvm event

Changed paths:
    engines/sludge/main_loop.cpp


diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index a7b209f..a347b64 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -21,6 +21,8 @@
  */
 
 #include "common/debug.h"
+#include "common/events.h"
+#include "common/keyboard.h"
 
 #include "graphics/surface.h"
 
@@ -114,28 +116,32 @@ extern bool reallyWantToQuit;
 int weAreDoneSoQuit;
 
 void checkInput() {
-	static bool fakeRightclick = false;
 #if 0
-	SDL_Event event;
+	static bool fakeRightclick = false;
+#endif
+	Common::Event event;
 
 	/* Check for events */
-	while (SDL_PollEvent(&event)) {
+	while (g_system->getEventManager()->pollEvent(event)) {
 		switch (event.type) {
-
+#if 0
 			case SDL_VIDEORESIZE:
-			realWinWidth = event.resize.w;
-			realWinHeight = event.resize.h;
-			setGraphicsWindow(false, true, true);
-			break;
-
-			case SDL_MOUSEMOTION:
-			input.justMoved = true;
-			input.mouseX = event.motion.x * ((float)winWidth / cameraZoom) / realWinWidth;
-			input.mouseY = event.motion.y * ((float)winHeight / cameraZoom) / realWinHeight;
-			break;
-
-			case SDL_MOUSEBUTTONDOWN:
-			if (event.button.button == SDL_BUTTON_LEFT) {
+				realWinWidth = event.resize.w;
+				realWinHeight = event.resize.h;
+				setGraphicsWindow(false, true, true);
+				break;
+#endif
+			case Common::EVENT_MOUSEMOVE:
+				input.justMoved = true;
+				input.mouseX = event.mouse.x * ((float)winWidth / cameraZoom) / realWinWidth;
+				input.mouseY = event.mouse.y * ((float)winHeight / cameraZoom) / realWinHeight;
+				break;
+
+			case Common::EVENT_LBUTTONDOWN:
+				input.leftClick = true;
+				input.mouseX = event.mouse.x * ((float)winWidth / cameraZoom) / realWinWidth;
+				input.mouseY = event.mouse.y * ((float)winHeight / cameraZoom) / realWinHeight;
+#if 0
 				if (SDL_GetModState() & KMOD_CTRL) {
 					input.rightClick = true;
 					fakeRightclick = true;
@@ -143,157 +149,95 @@ void checkInput() {
 					input.leftClick = true;
 					fakeRightclick = false;
 				}
-			}
-			if (event.button.button == SDL_BUTTON_RIGHT) input.rightClick = true;
-			input.mouseX = event.motion.x * ((float)winWidth / cameraZoom) / realWinWidth;
-			input.mouseY = event.motion.y * ((float)winHeight / cameraZoom) / realWinHeight;
-			break;
-
-			case SDL_MOUSEBUTTONUP:
-			if (event.button.button == SDL_BUTTON_LEFT) {
-				if (fakeRightclick) {
-					fakeRightclick = false;
-					input.rightRelease = true;
-				} else {
-					input.leftRelease = true;
-				}
-			}
-			if (event.button.button == SDL_BUTTON_RIGHT) input.rightRelease = true;
-			input.mouseX = event.motion.x * ((float)winWidth / cameraZoom) / realWinWidth;
-			input.mouseY = event.motion.y * ((float)winHeight / cameraZoom) / realWinHeight;
-			break;
-
-			case SDL_KEYDOWN:
-			// A Windows key is pressed - let's leave fullscreen.
-			if (runningFullscreen) {
-				if (event.key.keysym.sym == SDLK_LSUPER || event.key.keysym.sym == SDLK_LSUPER) {
-					setGraphicsWindow(!runningFullscreen);
-				}
-			}
-			// Ignore Command keypresses - they're for the OS to handle.
-			if (event.key.keysym.mod & KMOD_META) {
-				// Command+F - let's switch to/from full screen
-				if ('f' == event.key.keysym.unicode) {
-					setGraphicsWindow(!runningFullscreen);
-				}
+#endif
 				break;
-			} else if (event.key.keysym.mod & KMOD_ALT) {
-				// Alt + Enter also switches full screen mode
-				if (SDLK_RETURN == event.key.keysym.sym) {
-					setGraphicsWindow(!runningFullscreen);
-				}
-				if (SDLK_a == event.key.keysym.sym) {
-					gameSettings.antiAlias = !gameSettings.antiAlias;
-					break;
-				}
-				// Allow Alt+F4 to quit
-				if (SDLK_F4 == event.key.keysym.sym) {
-					SDL_Event event;
-					event.type = SDL_QUIT;
-					SDL_PushEvent(&event);
-				}
 
+			case Common::EVENT_RBUTTONDOWN:
+				input.rightClick = true;
+				input.mouseX = event.mouse.x * ((float)winWidth / cameraZoom) / realWinWidth;
+				input.mouseY = event.mouse.y * ((float)winHeight / cameraZoom) / realWinHeight;
 				break;
-			}
-			switch (event.key.keysym.sym) {
-				case SDLK_BACKSPACE:
-				case SDLK_DELETE: // Ok, mapping these to the same key is weird, I admit. But good?
-				input.keyPressed = 127;
-				break;
-				case SDLK_TAB:
-				input.keyPressed = 9;
-				break;
-				case SDLK_RETURN:
-				input.keyPressed = 13;
-				break;
-				case SDLK_ESCAPE:
-				input.keyPressed = 27;
-				break;
-				case SDLK_PAGEUP:
-				input.keyPressed = 63276;
-				break;
-				case SDLK_PAGEDOWN:
-				input.keyPressed = 63277;
-				break;
-				case SDLK_END:
-				input.keyPressed = 63275;
-				break;
-				case SDLK_HOME:
-				input.keyPressed = 63273;
-				break;
-				case SDLK_LEFT:
-				input.keyPressed = 63234;
-				break;
-				case SDLK_UP:
-				input.keyPressed = 63232;
-				break;
-				case SDLK_RIGHT:
-				input.keyPressed = 63235;
-				break;
-				case SDLK_DOWN:
-				input.keyPressed = 63233;
-				break;
-				case SDLK_F1:
-				input.keyPressed = 63236;
-				break;
-				case SDLK_F2:
-				input.keyPressed = 63237;
-				break;
-				case SDLK_F3:
-				input.keyPressed = 63238;
-				break;
-				case SDLK_F4:
-				input.keyPressed = 63239;
-				break;
-				case SDLK_F5:
-				input.keyPressed = 63240;
-				break;
-				case SDLK_F6:
-				input.keyPressed = 63241;
-				break;
-				case SDLK_F7:
-				input.keyPressed = 63242;
-				break;
-				case SDLK_F8:
-				input.keyPressed = 63243;
-				break;
-				case SDLK_F9:
-				input.keyPressed = 63244;
-				break;
-				case SDLK_F10:
-				input.keyPressed = 63245;
-				break;
-				case SDLK_F11:
-				input.keyPressed = 63246;
+
+			case Common::EVENT_LBUTTONUP:
+				input.leftRelease = true;
+				input.mouseX = event.mouse.x * ((float)winWidth / cameraZoom) / realWinWidth;
+				input.mouseY = event.mouse.y * ((float)winHeight / cameraZoom) / realWinHeight;
 				break;
-				case SDLK_F12:
-				input.keyPressed = 63247;
+
+			case Common::EVENT_RBUTTONUP:
+				input.rightRelease = true;
+				input.mouseX = event.mouse.x * ((float)winWidth / cameraZoom) / realWinWidth;
+				input.mouseY = event.mouse.y * ((float)winHeight / cameraZoom) / realWinHeight;
 				break;
-				default:
-				input.keyPressed = event.key.keysym.unicode;
+
+			case Common::EVENT_KEYDOWN:
+#if 0
+				// A Windows key is pressed - let's leave fullscreen.
+				if (runningFullscreen) {
+					if (event.key.keysym.sym == SDLK_LSUPER || event.key.keysym.sym == SDLK_LSUPER) {
+						setGraphicsWindow(!runningFullscreen);
+					}
+				}
+				// Ignore Command keypresses - they're for the OS to handle.
+				if (event.key.keysym.mod & KMOD_META) {
+					// Command+F - let's switch to/from full screen
+					if ('f' == event.key.keysym.unicode) {
+						setGraphicsWindow(!runningFullscreen);
+					}
+					break;
+				} else if (event.key.keysym.mod & KMOD_ALT) {
+					// Alt + Enter also switches full screen mode
+					if (SDLK_RETURN == event.key.keysym.sym) {
+						setGraphicsWindow(!runningFullscreen);
+					}
+					if (SDLK_a == event.key.keysym.sym) {
+						gameSettings.antiAlias = !gameSettings.antiAlias;
+						break;
+					}
+					// Allow Alt+F4 to quit
+					if (SDLK_F4 == event.key.keysym.sym) {
+						SDL_Event event;
+						event.type = SDL_QUIT;
+						SDL_PushEvent(&event);
+					}
+
+					break;
+				}
+#endif
+				switch (event.kbd.keycode) {
+
+					case Common::KEYCODE_BACKSPACE:
+						// fall through
+					case Common::KEYCODE_DELETE:
+						input.keyPressed = Common::KEYCODE_DELETE;
+						break;
+					default:
+						input.keyPressed = event.kbd.keycode;
+						break;
+				}
 				break;
-			}
-			break;
 
-			case SDL_QUIT:
-			if (reallyWantToQuit) {
-				// The game file has requested that we quit
+			case Common::EVENT_QUIT:
 				weAreDoneSoQuit = 1;
-			} else {
-				// The request is from elsewhere - ask for confirmation.
-				setGraphicsWindow(false);
-				//fprintf (stderr, "%s %s\n", gameName, getNumberedString(2));
-				if (msgBoxQuestion(gameName, getNumberedString(2))) {
+#if 0
+				if (reallyWantToQuit) {
+					// The game file has requested that we quit
 					weAreDoneSoQuit = 1;
+				} else {
+					// The request is from elsewhere - ask for confirmation.
+					setGraphicsWindow(false);
+					//fprintf (stderr, "%s %s\n", gameName, getNumberedString(2));
+					if (msgBoxQuestion(gameName, getNumberedString(2))) {
+						weAreDoneSoQuit = 1;
+					}
 				}
-			}
-			break;
+#endif
+				break;
 
 			default:
-			break;
+				break;
 		}
 	}
-#endif
 }
 
 int main_loop(const char *filename)


Commit: 82f023d9bd87ee39de5f93f6ac63afbcd74f8915
    https://github.com/scummvm/scummvm/commit/82f023d9bd87ee39de5f93f6ac63afbcd74f8915
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: free surfaces in freeze struct

Changed paths:
    engines/sludge/freeze.cpp


diff --git a/engines/sludge/freeze.cpp b/engines/sludge/freeze.cpp
index 57d7d0d..2d8a7bc 100644
--- a/engines/sludge/freeze.cpp
+++ b/engines/sludge/freeze.cpp
@@ -249,6 +249,14 @@ void unfreeze(bool killImage) {
 	frozenStuff = frozenStuff->next;
 
 	overRegion = NULL;
+
+	// free current frozen screen struct
+	if (killMe->backdropSurface.getPixels())
+		killMe->backdropSurface.free();
+	if (killMe->lightMapSurface.getPixels())
+		killMe->lightMapSurface.free();
+	if (killMe->zBufferImage.getPixels())
+		killMe->zBufferImage.free();
 	delete killMe;
 	killMe = NULL;
 


Commit: 83926d07a379713c3719cc5745d2eab16ffcf3c5
    https://github.com/scummvm/scummvm/commit/83926d07a379713c3719cc5745d2eab16ffcf3c5
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: fix error that chracter has no click effect

Changed paths:
    engines/sludge/sprites.cpp


diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index 1837095..3662660 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -632,6 +632,13 @@ bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *t
 	Graphics::TransparentSurface tmp(single.surface, false);
 	tmp.blit(renderSurface, x1, y1, (mirror? Graphics::FLIP_H : Graphics::FLIP_NONE), nullptr, TS_ARGB(255, 255, 255, 255), diffX, diffY);
 
+	// Are we pointing at the sprite?
+	if (input.mouseX >= x1 && input.mouseX <= x2 && input.mouseY >= y1 && input.mouseY <= y2) {
+		if (thisPerson->extra & EXTRA_RECTANGULAR) return true;
+			return true;
+		}
+	return false;
+
 #if 0
 	GLfloat z;
 


Commit: 4b941e16dbc21487af4e0e442bf27527d0068dcc
    https://github.com/scummvm/scummvm/commit/4b941e16dbc21487af4e0e442bf27527d0068dcc
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove a low-level graphic loop

Changed paths:
    engines/sludge/freeze.cpp


diff --git a/engines/sludge/freeze.cpp b/engines/sludge/freeze.cpp
index 2d8a7bc..182ffcf 100644
--- a/engines/sludge/freeze.cpp
+++ b/engines/sludge/freeze.cpp
@@ -70,37 +70,17 @@ void freezeGraphics() {
 	freezeSurface.create(w, h, *g_sludge->getScreenPixelFormat());
 
 	// Temporarily disable AA
+#if 0
 	int antiAlias = gameSettings.antiAlias;
 	gameSettings.antiAlias = 0;
-
-	int x = 0;
-	while (x < winWidth) {
-		int y = 0;
-
-		if (winWidth - x < realWinWidth) {
-			w = winWidth - x;
-		} else {
-			w = realWinWidth;
-		}
-
-		while (y < winHeight) {
-
-			if (winHeight - y < realWinHeight) {
-				h = winHeight - y;
-			} else {
-				h = realWinHeight;
-			}
-			drawBackDrop();// Draw the room
-			drawZBuffer(cameraX, cameraY, false);
-			drawPeople();// Then add any moving characters...
-			freezeSurface.copyFrom(renderSurface);
-
-			y += h;
-		}
-		x += w;
-	}
-
+#endif
+	drawBackDrop();// Draw the room
+	drawZBuffer(cameraX, cameraY, false);
+	drawPeople();// Then add any moving characters...
+	freezeSurface.copyFrom(renderSurface);
+#if 0
 	gameSettings.antiAlias = antiAlias;
+#endif
 }
 
 bool freeze() {


Commit: 387a558ec40aa2258a23e6c9c8cb5b3096f9ff9e
    https://github.com/scummvm/scummvm/commit/387a558ec40aa2258a23e6c9c8cb5b3096f9ff9e
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: add dark screen effect

Changed paths:
    engines/sludge/backdrop.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index 7c21183..76d831e 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -457,71 +457,8 @@ void drawHorizontalLine(unsigned int x1, unsigned int y, unsigned int x2) {
 }
 
 void darkScreen() {
-	setPixelCoords(true);
-
-	int xoffset = 0;
-	while (xoffset < sceneWidth) {
-		int w = (sceneWidth - xoffset < viewportWidth) ? sceneWidth - xoffset : viewportWidth;
-
-		int yoffset = 0;
-		while (yoffset < sceneHeight) {
-			int h = (sceneHeight - yoffset < viewportHeight) ? sceneHeight - yoffset : viewportHeight;
-
-			// Render the scene - first the old backdrop
-#if 0
-			//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
-			glBindTexture(GL_TEXTURE_2D, backdropTextureName);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-
-			const GLfloat vertices[] = {
-				(GLfloat) - xoffset, (GLfloat) - yoffset, 0.,
-				(GLfloat)sceneWidth - xoffset, (GLfloat) - yoffset, 0.,
-				(GLfloat) - xoffset, (GLfloat)sceneHeight - yoffset, 0.,
-				(GLfloat)sceneWidth - xoffset, (GLfloat)sceneHeight - yoffset, 0.
-			};
-
-			const GLfloat texCoords[] = {
-				0.0f, 0.0f,
-				backdropTexW, 0.0f,
-				0.0f, backdropTexH,
-				backdropTexW, backdropTexH
-			};
-
-			glUseProgram(shader.texture);
-
-			setPMVMatrix(shader.texture);
-
-			drawQuad(shader.texture, vertices, 1, texCoords);
-
-			// Then the darkness
-			glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE);
-
-			glEnable(GL_BLEND);
-
-			glUseProgram(shader.color);
-
-			setPMVMatrix(shader.color);
-			setPrimaryColor(0.0f, 0.0f, 0.0f, 0.5f);
-			drawQuad(shader.color, vertices, 0);
-
-			glUseProgram(0);
-
-			glDisable(GL_BLEND);
-			glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
-
-			// Copy Our ViewPort To The Texture
-			copyTexSubImage2D(GL_TEXTURE_2D, 0, xoffset, yoffset, viewportOffsetX, viewportOffsetY, w, h, backdropTextureName);
-
-			yoffset += h;
-
-			glClear(GL_COLOR_BUFFER_BIT);
-#endif
-		}
-		xoffset += w;
-	}
-
-	setPixelCoords(false);
+	Graphics::TransparentSurface tmp(backdropSurface, false);
+	tmp.blit(backdropSurface, 0, 0, Graphics::FLIP_NONE, nullptr, TS_ARGB(0, 255 >> 1, 0, 0));
 }
 
 inline int sortOutPCamera(int cX, int fX, int sceneMax, int boxMax) {


Commit: f13854780869f3958098de85cce1052469c4d6d9
    https://github.com/scummvm/scummvm/commit/f13854780869f3958098de85cce1052469c4d6d9
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: paste image to background

Changed paths:
    engines/sludge/sprites.cpp


diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index 3662660..96dec30 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -50,6 +50,7 @@ extern inputType input;
 extern int cameraX, cameraY;
 extern float cameraZoom;
 extern Graphics::Surface renderSurface;
+extern Graphics::Surface backdropSurface;
 
 unsigned char currentBurnR = 0, currentBurnG = 0, currentBurnB = 0;
 
@@ -286,8 +287,11 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 	return true;
 }
 
-void pasteSpriteToBackDrop(int x1, int y1, sprite &single,
-		const spritePalette &fontPal) {
+void pasteSpriteToBackDrop(int x1, int y1, sprite &single, const spritePalette &fontPal) {
+	x1 -= single.xhot;
+	y1 -= single.yhot;
+	Graphics::TransparentSurface tmp(single.surface, false);
+	tmp.blit(backdropSurface, x1, y1);
 #if 0
 	float tx1 = (float)(single.tex_x) / fontPal.tex_w[single.texNum];
 	float ty1 = 0.0;
@@ -382,8 +386,8 @@ void pasteSpriteToBackDrop(int x1, int y1, sprite &single,
 		}
 		xoffset += viewportWidth;
 	}
-#endif
 	setPixelCoords(false);
+#endif
 }
 
 void burnSpriteToBackDrop(int x1, int y1, sprite &single,


Commit: eb9968332eeacf887ae668a5cad9b7cf237ec753
    https://github.com/scummvm/scummvm/commit/eb9968332eeacf887ae668a5cad9b7cf237ec753
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: change background and zByffer restore order in freeze

Changed paths:
    engines/sludge/freeze.cpp


diff --git a/engines/sludge/freeze.cpp b/engines/sludge/freeze.cpp
index 182ffcf..378161c 100644
--- a/engines/sludge/freeze.cpp
+++ b/engines/sludge/freeze.cpp
@@ -195,6 +195,11 @@ void unfreeze(bool killImage) {
 		loadLightMap(lightMapNumber);
 	}
 
+	if (killImage)
+			killBackDrop();
+	backdropSurface.copyFrom(frozenStuff->backdropSurface);
+	backdropExists = true;
+
 	killZBuffer();
 	zBuffer.surface.copyFrom(frozenStuff->zBufferImage);
 	zBuffer.originalNum = frozenStuff->zBufferNumber;
@@ -207,13 +212,6 @@ void unfreeze(bool killImage) {
 	parallaxStuff = frozenStuff->parallaxStuff;
 	reloadParallaxTextures();
 
-	if (killImage)
-		killBackDrop();
-	if (backdropSurface.getPixels())
-		backdropSurface.free();
-	backdropSurface.copyFrom(frozenStuff->backdropSurface);
-	backdropExists = true;
-
 	deleteAnim(mouseCursorAnim);
 	mouseCursorAnim = frozenStuff->mouseCursorAnim;
 	mouseCursorFrameNum = frozenStuff->mouseCursorFrameNum;


Commit: 714196132cf62ec4affe14dd58555cd3f0f99aa2
    https://github.com/scummvm/scummvm/commit/714196132cf62ec4affe14dd58555cd3f0f99aa2
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: load zBuffer sprites as backdrop copies

Changed paths:
    engines/sludge/freeze.cpp
    engines/sludge/freeze.h
    engines/sludge/zbuffer.cpp
    engines/sludge/zbuffer.h


diff --git a/engines/sludge/freeze.cpp b/engines/sludge/freeze.cpp
index 378161c..ddaaf9c 100644
--- a/engines/sludge/freeze.cpp
+++ b/engines/sludge/freeze.cpp
@@ -109,10 +109,10 @@ bool freeze() {
 
 	newFreezer->parallaxStuff = parallaxStuff;
 	parallaxStuff = NULL;
-	newFreezer->zBufferImage.copyFrom(zBuffer.surface);
+	newFreezer->zBufferSprites = zBuffer.sprites;
 	newFreezer->zBufferNumber = zBuffer.originalNum;
 	newFreezer->zPanels = zBuffer.numPanels;
-	zBuffer.surface.free();
+	zBuffer.sprites = NULL;
 	// resizeBackdrop kills parallax stuff, light map, z-buffer...
 	if (!killResizeBackdrop(winWidth, winHeight))
 		return fatal("Can't create new temporary backdrop buffer");
@@ -196,12 +196,12 @@ void unfreeze(bool killImage) {
 	}
 
 	if (killImage)
-			killBackDrop();
+		killBackDrop();
 	backdropSurface.copyFrom(frozenStuff->backdropSurface);
 	backdropExists = true;
 
+	zBuffer.sprites = frozenStuff->zBufferSprites;
 	killZBuffer();
-	zBuffer.surface.copyFrom(frozenStuff->zBufferImage);
 	zBuffer.originalNum = frozenStuff->zBufferNumber;
 	zBuffer.numPanels = frozenStuff->zPanels;
 	if (zBuffer.numPanels) {
@@ -233,8 +233,6 @@ void unfreeze(bool killImage) {
 		killMe->backdropSurface.free();
 	if (killMe->lightMapSurface.getPixels())
 		killMe->lightMapSurface.free();
-	if (killMe->zBufferImage.getPixels())
-		killMe->zBufferImage.free();
 	delete killMe;
 	killMe = NULL;
 
diff --git a/engines/sludge/freeze.h b/engines/sludge/freeze.h
index cfd5747..ae9cd6d 100644
--- a/engines/sludge/freeze.h
+++ b/engines/sludge/freeze.h
@@ -31,7 +31,7 @@ struct frozenStuffStruct {
 	screenRegion *allScreenRegions;
 	Graphics::Surface backdropSurface;
 	Graphics::Surface lightMapSurface;
-	Graphics::Surface zBufferImage;
+	Graphics::Surface *zBufferSprites;
 	int zPanels;
 	parallaxLayer *parallaxStuff;
 	int lightMapNumber, zBufferNumber;
diff --git a/engines/sludge/zbuffer.cpp b/engines/sludge/zbuffer.cpp
index 4f42c98..cc3bb8d 100644
--- a/engines/sludge/zbuffer.cpp
+++ b/engines/sludge/zbuffer.cpp
@@ -20,29 +20,35 @@
  *
  */
 
+#include "common/debug.h"
+#include "graphics/pixelformat.h"
+#include "graphics/transparent_surface.h"
+
 #include "sludge/allfiles.h"
 #include "sludge/zbuffer.h"
 #include "sludge/fileset.h"
 #include "sludge/moreio.h"
 #include "sludge/newfatal.h"
 #include "sludge/graphics.h"
+#include "sludge/sludge.h"
 
 namespace Sludge {
 
 zBufferData zBuffer;
 extern int sceneWidth, sceneHeight;
+extern Graphics::Surface backdropSurface;
+extern Graphics::Surface renderSurface;
 
 void killZBuffer() {
-#if 0
-	if (zBuffer.tex) {
-		deleteTextures(1, &zBuffer.texName);
-		zBuffer.texName = 0;
-		delete zBuffer.tex;
-		zBuffer.tex = NULL;
+	if (zBuffer.sprites) {
+		for (int i = 0; i < zBuffer.numPanels; ++i) {
+			zBuffer.sprites[i].free();
+		}
+		delete []zBuffer.sprites;
+		zBuffer.sprites = nullptr;
 	}
 	zBuffer.numPanels = 0;
 	zBuffer.originalNum = 0;
-#endif
 }
 
 void sortZPal(int *oldpal, int *newpal, int size) {
@@ -65,18 +71,17 @@ void sortZPal(int *oldpal, int *newpal, int size) {
 	}
 }
 
-bool setZBuffer(int y) {
-#if 0
-	int x, n;
+bool setZBuffer(int num) {
+	debug("Setting zBuffer");
 	uint32 stillToGo = 0;
 	int yPalette[16], sorted[16], sortback[16];
 
 	killZBuffer();
 
-	setResourceForFatal(y);
+	setResourceForFatal(num);
 
-	zBuffer.originalNum = y;
-	if (!openFileFromNum(y))
+	zBuffer.originalNum = num;
+	if (!openFileFromNum(num))
 		return false;
 	if (bigDataFile->readByte() != 'S')
 		return fatal("Not a Z-buffer file");
@@ -85,81 +90,93 @@ bool setZBuffer(int y) {
 	if (bigDataFile->readByte() != 'b')
 		return fatal("Not a Z-buffer file");
 
+	int width, height;
 	switch (bigDataFile->readByte()) {
-			case 0:
-				zBuffer.width = 640;
-				zBuffer.height = 480;
-				break;
-
-			case 1:
-				zBuffer.width = bigDataFile->readUint16BE();
-				zBuffer.height = bigDataFile->readUint16BE();
-				break;
-
-			default:
-				return fatal("Extended Z-buffer format not supported in this version of the SLUDGE engine");
-		}
-		if (zBuffer.width != sceneWidth || zBuffer.height != sceneHeight) {
-			char tmp[256];
-			sprintf(tmp, "Z-w: %d Z-h:%d w: %d, h:%d", zBuffer.width, zBuffer.height, sceneWidth, sceneHeight);
-			return fatal("Z-buffer width and height don't match scene width and height", tmp);
-		}
+		case 0:
+			width = 640;
+			height = 480;
+			break;
+
+		case 1:
+			width = bigDataFile->readUint16BE();
+			height = bigDataFile->readUint16BE();
+			break;
+
+		default:
+			return fatal("Extended Z-buffer format not supported in this version of the SLUDGE engine");
+	}
+	if (width != sceneWidth || height != sceneHeight) {
+		char tmp[256];
+		sprintf(tmp, "Z-w: %d Z-h:%d w: %d, h:%d", width, height, sceneWidth, sceneHeight);
+		return fatal("Z-buffer width and height don't match scene width and height", tmp);
+	}
 
-		zBuffer.numPanels = bigDataFile->readByte();
-		for (y = 0; y < zBuffer.numPanels; y++) {
-			yPalette[y] = bigDataFile->readUint16BE();
-		}
-		sortZPal(yPalette, sorted, zBuffer.numPanels);
-		for (y = 0; y < zBuffer.numPanels; y++) {
-			zBuffer.panel[y] = yPalette[sorted[y]];
-			sortback[sorted[y]] = y;
-		}
+	zBuffer.numPanels = bigDataFile->readByte();
+	for (int y = 0; y < zBuffer.numPanels; y++) {
+		yPalette[y] = bigDataFile->readUint16BE();
+	}
+	sortZPal(yPalette, sorted, zBuffer.numPanels);
+	for (int y = 0; y < zBuffer.numPanels; y++) {
+		zBuffer.panel[y] = yPalette[sorted[y]];
+		sortback[sorted[y]] = y;
+	}
 
-		int picWidth = sceneWidth;
-		int picHeight = sceneHeight;
-		if (!NPOT_textures) {
-			picWidth = getNextPOT(picWidth);
-			picHeight = getNextPOT(picHeight);
-		}
-		zBuffer.tex = new GLubyte[picHeight * picWidth];
-		if (!checkNew(zBuffer.tex))
-			return false;
-
-		for (y = 0; y < sceneHeight; y++) {
-			for (x = 0; x < sceneWidth; x++) {
-				if (stillToGo == 0) {
-					n = bigDataFile->readByte();
-					stillToGo = n >> 4;
-					if (stillToGo == 15)
-						stillToGo = bigDataFile->readUint16BE() + 16l;
-					else
-						stillToGo++;
-					n &= 15;
+	int picWidth = sceneWidth;
+	int picHeight = sceneHeight;
+
+	zBuffer.sprites = nullptr;
+	zBuffer.sprites = new Graphics::Surface[zBuffer.numPanels];
+
+	for (int i = 0; i < zBuffer.numPanels; ++i) {
+		zBuffer.sprites[i].create(picWidth, picHeight, *g_sludge->getScreenPixelFormat());
+	}
+
+	for (int y = 0; y < sceneHeight; y++) {
+		for (int x = 0; x < sceneWidth; x++) {
+			int n;
+			if (stillToGo == 0) {
+				n = bigDataFile->readByte();
+				stillToGo = n >> 4;
+				if (stillToGo == 15)
+					stillToGo = bigDataFile->readUint16BE() + 16l;
+				else
+					stillToGo++;
+				n &= 15;
+			}
+			for (int i = 0; i < zBuffer.numPanels; ++i) {
+				byte *target = (byte *)zBuffer.sprites[i].getBasePtr(x, y);
+				if (n && (sortback[i] == n || i == 0)) {
+					byte *source = (byte *)backdropSurface.getBasePtr(x, y);
+					target[0] = source[0];
+					target[1] = source[1];
+					target[2] = source[2];
+					target[3] = source[3];
+				} else {
+					target[0] = 0;
+					target[1] = 0;
+					target[2] = 0;
+					target[3] = 0;
 				}
-				zBuffer.tex[y * picWidth + x] = sortback[n] * 16;
-				stillToGo--;
 			}
+			stillToGo--;
 		}
-		finishAccess();
-#endif
-		setResourceForFatal(-1);
-#if 0
-		if (! zBuffer.texName) glGenTextures(1, &zBuffer.texName);
-		glBindTexture(GL_TEXTURE_2D, zBuffer.texName);
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+	}
+	finishAccess();
+	setResourceForFatal(-1);
+	return true;
+}
 
-		texImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, picWidth, picHeight, 0, GL_ALPHA, GL_UNSIGNED_BYTE, zBuffer.tex, zBuffer.texName);
-#endif
-		return true;
+void drawZBuffer(int x, int y, bool upsidedown) {
+	if (!zBuffer.numPanels || !zBuffer.sprites)
+		return;
+
+	for (int i = 0; i < zBuffer.numPanels; ++i) {
+		Graphics::TransparentSurface tmp(zBuffer.sprites[i], false);
+		tmp.blit(renderSurface, 0, 0, (upsidedown ? Graphics::FLIP_V : Graphics::FLIP_NONE));
 	}
 
-	void drawZBuffer(int x, int y, bool upsidedown) {
-		int i;
 #if 0
-		if (! zBuffer.tex) return;
+	glEnable (GL_DEPTH_TEST);
 
 		glEnable(GL_DEPTH_TEST);
 		glEnable(GL_BLEND);
diff --git a/engines/sludge/zbuffer.h b/engines/sludge/zbuffer.h
index f78b655..0a53d54 100644
--- a/engines/sludge/zbuffer.h
+++ b/engines/sludge/zbuffer.h
@@ -31,12 +31,7 @@ struct zBufferData {
 	int numPanels;
 	int panel[16];
 	int originalNum;
-	Graphics::Surface surface;
-#if 0
-	int width, height;
-	GLubyte *tex;
-	GLuint texName;
-#endif
+	Graphics::Surface *sprites;
 };
 
 bool setZBuffer(int y);


Commit: f89f1aad4c7ba65e6616eab4a6191e200334dbfc
    https://github.com/scummvm/scummvm/commit/f89f1aad4c7ba65e6616eab4a6191e200334dbfc
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: formatting code in sprites.cpp

Changed paths:
    engines/sludge/sprites.cpp


diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index 96dec30..a8f5ed2 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -110,8 +110,7 @@ bool reserveSpritePal(spritePalette &sP, int n) {
 	if (!checkNew(sP.b))
 		return false;
 	sP.total = n;
-	return (bool) (sP.pal != NULL) && (sP.r != NULL) && (sP.g != NULL)
-			&& (sP.b != NULL);
+	return (bool)(sP.pal != NULL) && (sP.r != NULL) && (sP.g != NULL) && (sP.b != NULL);
 }
 
 bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
@@ -120,7 +119,8 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 	byte *data;
 
 	setResourceForFatal(fileNum);
-	if (!openFileFromNum(fileNum)) return fatal("Can't open sprite bank / font");
+	if (!openFileFromNum(fileNum))
+		return fatal("Can't open sprite bank / font");
 
 	loadhere.isFont = isFont;
 
@@ -134,14 +134,18 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 		}
 	}
 
-	if (total <= 0) return fatal("No sprites in bank or invalid sprite bank file");
-	if (spriteBankVersion > 3) return fatal("Unsupported sprite bank file format");
+	if (total <= 0)
+		return fatal("No sprites in bank or invalid sprite bank file");
+	if (spriteBankVersion > 3)
+		return fatal("Unsupported sprite bank file format");
 
 	loadhere.total = total;
-	loadhere.sprites = new sprite [total];
-	if (! checkNew(loadhere.sprites)) return false;
-	byte **spriteData = new byte * [total];
-	if (! checkNew(spriteData)) return false;
+	loadhere.sprites = new sprite[total];
+	if (!checkNew(loadhere.sprites))
+		return false;
+	byte **spriteData = new byte *[total];
+	if (!checkNew(spriteData))
+		return false;
 
 	// version 1, 2, read how many now
 	if (spriteBankVersion && spriteBankVersion < 3) {
@@ -151,7 +155,7 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 
 	// version 3, sprite is png
 	if (spriteBankVersion == 3) {
-		for (int i = 0; i < total; i ++) {
+		for (int i = 0; i < total; i++) {
 			howmany = bigDataFile->readByte();
 			startIndex = 1;
 
@@ -166,7 +170,7 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 	}
 
 	// version 0, 1, 2
-	for (int i = 0; i < total; i ++) {
+	for (int i = 0; i < total; i++) {
 		int picwidth, picheight;
 		// load sprite width, height, relative position
 		if (spriteBankVersion == 2) {
@@ -187,7 +191,8 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 			loadhere.sprites[i].burnSurface.create(picwidth, picheight, *g_sludge->getScreenPixelFormat());
 		}
 		data = (byte *)new byte[picwidth * (picheight + 1)];
-		if (!checkNew(data)) return false;
+		if (!checkNew(data))
+			return false;
 		memset(data + picwidth * picheight, 0, picwidth);
 		spriteData[i] = data;
 
@@ -202,10 +207,11 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 				if (col > howmany) {
 					col -= howmany + 1;
 					looper = bigDataFile->readByte() + 1;
-				} else looper = 1;
+				} else
+					looper = 1;
 
-				while (looper --) {
-					data[pip ++] = col;
+				while (looper--) {
+					data[pip++] = col;
 				}
 			}
 		} else { // RAW DATA
@@ -223,7 +229,8 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 	}
 
 	// Make palette for version 0, 1, 2
-	if (!reserveSpritePal(loadhere.myPalette, howmany + startIndex)) return false;
+	if (!reserveSpritePal(loadhere.myPalette, howmany + startIndex))
+		return false;
 	for (int i = 0; i < howmany; i++) {
 		loadhere.myPalette.r[i + startIndex] = (byte)bigDataFile->readByte();
 		loadhere.myPalette.g[i + startIndex] = (byte)bigDataFile->readByte();
@@ -237,7 +244,7 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 	loadhere.myPalette.originalRed = loadhere.myPalette.originalGreen = loadhere.myPalette.originalBlue = 255;
 
 	// convert
-	for (int i = 0; i < total; i ++) {
+	for (int i = 0; i < total; i++) {
 		int fromhere = 0;
 		int transColour = -1;
 		int size = loadhere.sprites[i].surface.w * loadhere.sprites[i].surface.h;
@@ -390,8 +397,7 @@ void pasteSpriteToBackDrop(int x1, int y1, sprite &single, const spritePalette &
 #endif
 }
 
-void burnSpriteToBackDrop(int x1, int y1, sprite &single,
-		const spritePalette &fontPal) {
+void burnSpriteToBackDrop(int x1, int y1, sprite &single, const spritePalette &fontPal) {
 #if 0
 	float tx1 = (float)(single.tex_x - 0.5) / fontPal.tex_w[single.texNum];
 	float ty1 = 0.0;
@@ -500,16 +506,16 @@ extern GLuint backdropTextureName;
 #endif
 
 void fontSprite(bool flip, int x, int y, sprite &single, const spritePalette &fontPal) {
-	float x1 = (float) x - (float) single.xhot / cameraZoom;
-	float y1 = (float) y - (float) single.yhot / cameraZoom;
+	float x1 = (float)x - (float)single.xhot / cameraZoom;
+	float y1 = (float)y - (float)single.yhot / cameraZoom;
 
 	// Use Transparent surface to scale and blit
 	Graphics::TransparentSurface tmp(single.surface, false);
-	tmp.blit(renderSurface, x1, y1, (flip? Graphics::FLIP_H : Graphics::FLIP_NONE));
+	tmp.blit(renderSurface, x1, y1, (flip ? Graphics::FLIP_H : Graphics::FLIP_NONE));
 
 	if (single.burnSurface.getPixels() != nullptr) {
 		Graphics::TransparentSurface tmp2(single.burnSurface, false);
-		tmp2.blit(renderSurface, x1, y1, (flip? Graphics::FLIP_H : Graphics::FLIP_NONE), 0, TS_RGB(fontPal.originalRed, fontPal.originalGreen, fontPal.originalBlue));
+		tmp2.blit(renderSurface, x1, y1, (flip ? Graphics::FLIP_H : Graphics::FLIP_NONE), 0, TS_RGB(fontPal.originalRed, fontPal.originalGreen, fontPal.originalBlue));
 
 	}
 
@@ -572,8 +578,7 @@ void fontSprite(int x, int y, sprite &single, const spritePalette &fontPal) {
 	fontSprite(false, x, y, single, fontPal);
 }
 
-void flipFontSprite(int x, int y, sprite &single,
-		const spritePalette &fontPal) {
+void flipFontSprite(int x, int y, sprite &single, const spritePalette &fontPal) {
 	fontSprite(true, x, y, single, fontPal);
 }
 
@@ -603,7 +608,8 @@ bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *t
 
 	float scale = thisPerson->scale;
 
-	if (scale <= 0.05) return false;
+	if (scale <= 0.05)
+		return false;
 
 	int diffX = (int)(((float)single.surface.w) * scale);
 	int diffY = (int)(((float)single.surface.h) * scale);
@@ -624,9 +630,9 @@ bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *t
 		x -= cameraX;
 		y -= cameraY;
 		if (single.xhot < 0)
-		x1 = x - (int)((mirror ? (float)(single.surface.w - single.xhot) : (float)(single.xhot + 1)) * scale);
+			x1 = x - (int)((mirror ? (float)(single.surface.w - single.xhot) : (float)(single.xhot + 1)) * scale);
 		else
-		x1 = x - (int)((mirror ? (float)(single.surface.w - (single.xhot + 1)) : (float)single.xhot) * scale);
+			x1 = x - (int)((mirror ? (float)(single.surface.w - (single.xhot + 1)) : (float)single.xhot) * scale);
 		y1 = y - (int)((single.yhot - thisPerson->floaty) * scale);
 		x2 = x1 + diffX;
 		y2 = y1 + diffY;
@@ -777,8 +783,7 @@ bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *t
 }
 
 // Paste a scaled sprite onto the backdrop
-void fixScaleSprite(int x, int y, sprite &single, const spritePalette &fontPal,
-		onScreenPerson *thisPerson, int camX, int camY, bool mirror) {
+void fixScaleSprite(int x, int y, sprite &single, const spritePalette &fontPal, onScreenPerson *thisPerson, int camX, int camY, bool mirror) {
 #if 0
 	float scale = thisPerson-> scale;
 	bool useZB = !(thisPerson->extra & EXTRA_NOZB);


Commit: 52b627bae6f13586f2767d444a3946807b627973
    https://github.com/scummvm/scummvm/commit/52b627bae6f13586f2767d444a3946807b627973
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: use Common::List to reproduce layer effects

Changed paths:
    engines/sludge/freeze.cpp
    engines/sludge/sludger.cpp
    engines/sludge/sludger.h
    engines/sludge/sprites.cpp
    engines/sludge/sprites.h
    engines/sludge/zbuffer.cpp


diff --git a/engines/sludge/freeze.cpp b/engines/sludge/freeze.cpp
index ddaaf9c..d3dde17 100644
--- a/engines/sludge/freeze.cpp
+++ b/engines/sludge/freeze.cpp
@@ -74,9 +74,7 @@ void freezeGraphics() {
 	int antiAlias = gameSettings.antiAlias;
 	gameSettings.antiAlias = 0;
 #endif
-	drawBackDrop();// Draw the room
-	drawZBuffer(cameraX, cameraY, false);
-	drawPeople();// Then add any moving characters...
+	displayBase();
 	freezeSurface.copyFrom(renderSurface);
 #if 0
 	gameSettings.antiAlias = antiAlias;
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index 4743649..cf2a053 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -572,6 +572,14 @@ bool checkColourChange(bool reset) {
 #endif
 	return false;
 }
+
+void displayBase() {
+	drawBackDrop();// Draw the room
+	drawZBuffer(cameraX, cameraY, false);
+	drawPeople();// Then add any moving characters...
+	displaySpriteLayers();
+}
+
 void sludgeDisplay() {
 #if 0
 #if defined(HAVE_GLES2)
@@ -666,15 +674,7 @@ void sludgeDisplay() {
 	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Clear The Screen
 	glDepthMask(GL_FALSE);
 #endif
-	drawBackDrop();// Draw the room
-	drawZBuffer(cameraX, cameraY, false);
-#if 0
-	glEnable(GL_DEPTH_TEST);
-#endif
-	drawPeople();// Then add any moving characters...
-#if 0
-	glDisable(GL_DEPTH_TEST);
-#endif
+	displayBase();
 	viewSpeech();// ...and anything being said
 	drawStatusBar();
 	displayCursor();
diff --git a/engines/sludge/sludger.h b/engines/sludge/sludger.h
index 6234e59..10c1794 100644
--- a/engines/sludge/sludger.h
+++ b/engines/sludge/sludger.h
@@ -77,6 +77,7 @@ extern unsigned char *gameIcon;
 extern int iconW, iconH;
 
 bool initSludge(const char *);
+void displayBase();
 void sludgeDisplay();
 int startNewFunctionNum(unsigned int, unsigned int, loadedFunction *, variableStack*&, bool = true);
 bool handleInput();
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index a8f5ed2..c457410 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -40,6 +40,26 @@
 
 namespace Sludge {
 
+// Sprite display informations
+struct SpriteDisplay {
+	int x, y;
+	int width, height;
+	Graphics::FLIP_FLAGS flip;
+	Graphics::Surface *surface;
+
+	SpriteDisplay(int xpos, int ypos, Graphics::FLIP_FLAGS f, Graphics::Surface *ptr, int w = -1, int h = 1) :
+			x(xpos), y(ypos), flip(f), surface(ptr), width(w), height(h) {
+	}
+};
+
+// All sprites are sorted into different "layers" (up to 16) according to their relative y position to z-buffer zones
+struct SpriteLayers {
+	int numLayers;
+	Common::List<SpriteDisplay> layer[16];
+};
+
+SpriteLayers spriteLayers;
+
 extern zBufferData zBuffer;
 
 #if 0
@@ -639,14 +659,20 @@ bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *t
 	}
 
 	// Use Transparent surface to scale and blit
-	Graphics::TransparentSurface tmp(single.surface, false);
-	tmp.blit(renderSurface, x1, y1, (mirror? Graphics::FLIP_H : Graphics::FLIP_NONE), nullptr, TS_ARGB(255, 255, 255, 255), diffX, diffY);
+	if (!zBuffer.numPanels) {
+		Graphics::TransparentSurface tmp(single.surface, false);
+		tmp.blit(renderSurface, x1, y1, (mirror ? Graphics::FLIP_H : Graphics::FLIP_NONE), nullptr, TS_ARGB(255, 255, 255, 255), diffX, diffY);
+	} else {
+		int d = ((!(thisPerson->extra & EXTRA_NOZB)) && zBuffer.numPanels) ? y + cameraY : sceneHeight + 1;
+		addSpriteDepth(&single.surface, d, x1, y1, (mirror ? Graphics::FLIP_H : Graphics::FLIP_NONE), diffX, diffY);
+	}
 
 	// Are we pointing at the sprite?
 	if (input.mouseX >= x1 && input.mouseX <= x2 && input.mouseY >= y1 && input.mouseY <= y2) {
-		if (thisPerson->extra & EXTRA_RECTANGULAR) return true;
+		if (thisPerson->extra & EXTRA_RECTANGULAR)
 			return true;
-		}
+		return true;
+	}
 	return false;
 
 #if 0
@@ -782,6 +808,46 @@ bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *t
 #endif
 }
 
+void resetSpriteLayers(zBufferData *pz, int x, int y, bool upsidedown) {
+	if (spriteLayers.numLayers > 0)
+		killSpriteLayers();
+	spriteLayers.numLayers = pz->numPanels;
+	for (int i = 0; i < spriteLayers.numLayers; ++i) {
+		SpriteDisplay node(x, y, (upsidedown ? Graphics::FLIP_V : Graphics::FLIP_NONE), &pz->sprites[i], pz->sprites[i].w, pz->sprites[i].h);
+		spriteLayers.layer[i].push_back(node);
+	}
+}
+
+void addSpriteDepth(Graphics::Surface *ptr, int depth, int x, int y, Graphics::FLIP_FLAGS flip, int width, int height) {
+	int i;
+	for (i = 1; i < zBuffer.numPanels; ++i) {
+		if (zBuffer.panel[i] >= depth) {
+			break;
+		}
+	}
+	--i;
+	SpriteDisplay node(x, y, flip, ptr, width, height);
+	spriteLayers.layer[i].push_back(node);
+}
+
+void displaySpriteLayers() {
+	for (int i = 0; i < spriteLayers.numLayers; ++i) {
+		Common::List<SpriteDisplay>::iterator it;
+		for (it = spriteLayers.layer[i].begin(); it != spriteLayers.layer[i].end(); ++it) {
+			Graphics::TransparentSurface tmp(*it->surface, false);
+			tmp.blit(renderSurface, it->x, it->y, it->flip, nullptr, TS_ARGB(255, 255, 255, 255), it->width, it->height);
+		}
+	}
+	killSpriteLayers();
+}
+
+void killSpriteLayers() {
+	for (int i = 0; i < spriteLayers.numLayers; ++i) {
+		spriteLayers.layer[i].clear();
+	}
+	spriteLayers.numLayers = 0;
+}
+
 // Paste a scaled sprite onto the backdrop
 void fixScaleSprite(int x, int y, sprite &single, const spritePalette &fontPal, onScreenPerson *thisPerson, int camX, int camY, bool mirror) {
 #if 0
diff --git a/engines/sludge/sprites.h b/engines/sludge/sprites.h
index f3ec22d..effb512 100644
--- a/engines/sludge/sprites.h
+++ b/engines/sludge/sprites.h
@@ -23,10 +23,12 @@
 #define SLUDGE_SPRITE_H
 
 #include "graphics/surface.h"
+#include "graphics/transparent_surface.h"
 
 namespace Sludge {
 
 struct onScreenPerson;
+struct zBufferData;
 
 struct sprite {
 	int xhot, yhot;
@@ -75,6 +77,11 @@ bool reserveSpritePal(spritePalette &sP, int n);
 void fixScaleSprite(int x1, int y1, sprite &single, const spritePalette &fontPal, onScreenPerson *thisPerson, const int camX, const int camY, bool);
 void burnSpriteToBackDrop(int x1, int y1, sprite &single, const spritePalette &fontPal);
 
+void resetSpriteLayers(zBufferData *ptrZBuffer, int x, int y, bool upsidedown);
+void addSpriteDepth(Graphics::Surface *ptr, int depth, int x, int y, Graphics::FLIP_FLAGS flip, int width = -1, int height = -1);
+void displaySpriteLayers();
+void killSpriteLayers();
+
 } // End of namespace Sludge
 
 #endif
diff --git a/engines/sludge/zbuffer.cpp b/engines/sludge/zbuffer.cpp
index cc3bb8d..76fa515 100644
--- a/engines/sludge/zbuffer.cpp
+++ b/engines/sludge/zbuffer.cpp
@@ -31,6 +31,7 @@
 #include "sludge/newfatal.h"
 #include "sludge/graphics.h"
 #include "sludge/sludge.h"
+#include "sludge/sprites.h"
 
 namespace Sludge {
 
@@ -170,10 +171,7 @@ void drawZBuffer(int x, int y, bool upsidedown) {
 	if (!zBuffer.numPanels || !zBuffer.sprites)
 		return;
 
-	for (int i = 0; i < zBuffer.numPanels; ++i) {
-		Graphics::TransparentSurface tmp(zBuffer.sprites[i], false);
-		tmp.blit(renderSurface, 0, 0, (upsidedown ? Graphics::FLIP_V : Graphics::FLIP_NONE));
-	}
+	resetSpriteLayers(&zBuffer, x, y, upsidedown);
 
 #if 0
 	glEnable (GL_DEPTH_TEST);


Commit: 03f43f789c38fc3596f31d1e39759265f60e4bb0
    https://github.com/scummvm/scummvm/commit/03f43f789c38fc3596f31d1e39759265f60e4bb0
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: add fall back detection

Changed paths:
    engines/sludge/detection.cpp


diff --git a/engines/sludge/detection.cpp b/engines/sludge/detection.cpp
index 2ce5f8f..6760610 100644
--- a/engines/sludge/detection.cpp
+++ b/engines/sludge/detection.cpp
@@ -20,6 +20,7 @@
  *
  */
 #include "common/debug.h"
+#include "common/stream.h"
 
 #include "engines/advancedDetector.h"
 
@@ -50,7 +51,18 @@ static const PlainGameDescriptor sludgeGames[] = {
 	{ "verbcoin", "Verb Coin" },
 	{ 0, 0 }
 };
- 
+
+static ADGameDescription s_fallbackDesc = {
+	"",
+	"",
+	AD_ENTRY1(0, 0), // This should always be AD_ENTRY1(0, 0) in the fallback descriptor
+	Common::UNK_LANG,
+	Common::kPlatformWindows,
+	ADGF_NO_FLAGS,
+	GUIO0()
+};
+static char s_fallbackFileNameBuffer[51];
+
 #include "sludge/detection_tables.h"
 
 class SludgeMetaEngine : public AdvancedMetaEngine {
@@ -68,7 +80,6 @@ public:
 		return "Copyright (C) 2000-2014 Hungry Software and contributors";
 	}
  
- 
 	virtual bool createInstance(OSystem *syst, Engine **engine, const ADGameDescription *desc) const {
 		const Sludge::SludgeGameDescription *gd = (const Sludge::SludgeGameDescription *)desc;
 			if (gd) {
@@ -76,8 +87,63 @@ public:
 			}
 			return gd != 0;
 	}
+
+	// for fall back detection
+	virtual const ADGameDescription *fallbackDetect(const FileMap &allFiles, const Common::FSList &fslist) const;
 };
 
+const ADGameDescription *SludgeMetaEngine::fallbackDetect(const FileMap &allFiles, const Common::FSList &fslist) const {
+	// reset fallback description
+	s_fallbackDesc.gameId = "sludge";
+	s_fallbackDesc.extra = "";
+	s_fallbackDesc.language = Common::EN_ANY;
+	s_fallbackDesc.flags = ADGF_UNSTABLE;
+	s_fallbackDesc.platform = Common::kPlatformUnknown;
+	s_fallbackDesc.guiOptions = GUIO0();
+
+	for (Common::FSList::const_iterator file = fslist.begin(); file != fslist.end(); ++file) {
+		if (file->isDirectory())
+			continue;
+
+		Common::String fileName = file->getName();
+		fileName.toLowercase();
+		if (!(fileName.hasSuffix(".slg") || fileName == "gamedata"))
+			continue;
+
+		SearchMan.clear();
+		SearchMan.addDirectory(file->getParent().getName(), file->getParent());
+
+		Common::SeekableReadStream *stream = SearchMan.createReadStreamForMember(file->getName());
+
+		if (!stream)
+			continue;
+
+		bool headerBad = false;
+		if (stream->readByte() != 'S')
+			headerBad = true;
+		if (stream->readByte() != 'L')
+			headerBad = true;
+		if (stream->readByte() != 'U')
+			headerBad = true;
+		if (stream->readByte() != 'D')
+			headerBad = true;
+		if (stream->readByte() != 'G')
+			headerBad = true;
+		if (stream->readByte() != 'E')
+			headerBad = true;
+		if (headerBad) {
+			continue;
+		}
+
+		strncpy(s_fallbackFileNameBuffer, fileName.c_str(), 50);
+		s_fallbackFileNameBuffer[50] = '\0';
+		s_fallbackDesc.filesDescriptions[0].fileName = s_fallbackFileNameBuffer;
+
+		return &s_fallbackDesc;;
+	}
+	return 0;
+}
+
 #if PLUGIN_ENABLED_DYNAMIC(SLUDGE)
 	REGISTER_PLUGIN_DYNAMIC(SLUDGE, PLUGIN_TYPE_ENGINE, SludgeMetaEngine);
 #else


Commit: 279a53302ad27902c2e90b9ae73a42fbfe414c24
    https://github.com/scummvm/scummvm/commit/279a53302ad27902c2e90b9ae73a42fbfe414c24
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: add game detection for Robin's rescue

Changed paths:
    engines/sludge/detection.cpp
    engines/sludge/detection_tables.h


diff --git a/engines/sludge/detection.cpp b/engines/sludge/detection.cpp
index 6760610..6dc7c12 100644
--- a/engines/sludge/detection.cpp
+++ b/engines/sludge/detection.cpp
@@ -49,6 +49,7 @@ static const PlainGameDescriptor sludgeGames[] = {
 	{ "welcome", "Welcome Example" },
 	{ "welcomeloop", "Welcome Loop Test" },
 	{ "verbcoin", "Verb Coin" },
+	{ "robinsrescue", "Robin's Rescue" },
 	{ 0, 0 }
 };
 
diff --git a/engines/sludge/detection_tables.h b/engines/sludge/detection_tables.h
index 72df456..a64bdab 100644
--- a/engines/sludge/detection_tables.h
+++ b/engines/sludge/detection_tables.h
@@ -62,6 +62,19 @@ static const SludgeGameDescription gameDescriptions[] = {
 		0
 	},
 
+	{
+		{
+			"robinsrescue",
+			"",
+			AD_ENTRY1s("robins_rescue.slg", "16cbf2bf916ed89f9c1b14fab133cf96", 14413769),
+			Common::EN_ANY,
+			Common::kPlatformUnknown,
+			ADGF_NO_FLAGS,
+			GUIO0()
+		},
+		0
+	},
+
 	{ AD_TABLE_END_MARKER, 0 }
 };
 


Commit: e7a22b59f86f40241a29ec24019ea27811deb1ab
    https://github.com/scummvm/scummvm/commit/e7a22b59f86f40241a29ec24019ea27811deb1ab
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: add several debug infos and exit when error

Changed paths:
    engines/sludge/fileset.cpp
    engines/sludge/newfatal.cpp
    engines/sludge/sludger.cpp


diff --git a/engines/sludge/fileset.cpp b/engines/sludge/fileset.cpp
index 0a68f7a..deb4a22 100644
--- a/engines/sludge/fileset.cpp
+++ b/engines/sludge/fileset.cpp
@@ -226,15 +226,15 @@ void setFileIndices(Common::File *fp, int numLanguages, unsigned int skipBefore)
 
 	startOfSubIndex = fp->pos() + 4;
 	fp->seek(fp->readUint32LE(), SEEK_CUR);
-	debug(kSludgeDebugDataLoad, "startOfSubIndex: %i", startOfTextIndex);
+	debug(kSludgeDebugDataLoad, "startOfSubIndex: %i", startOfSubIndex);
 
 	startOfObjectIndex = fp->pos() + 4;
 	fp->seek(fp->readUint32LE(), SEEK_CUR);
-	debug(kSludgeDebugDataLoad, "startOfObjectIndex: %i", startOfTextIndex);
+	debug(kSludgeDebugDataLoad, "startOfObjectIndex: %i", startOfObjectIndex);
 
 	// Remember that the data section starts here
 	startOfDataIndex = fp->pos();
-	debug(kSludgeDebugDataLoad, "startOfDataIndex: %i", startOfTextIndex);
+	debug(kSludgeDebugDataLoad, "startOfDataIndex: %i", startOfDataIndex);
 }
 
 } // End of namespace Sludge
diff --git a/engines/sludge/newfatal.cpp b/engines/sludge/newfatal.cpp
index a44290a..8bafd1f 100644
--- a/engines/sludge/newfatal.cpp
+++ b/engines/sludge/newfatal.cpp
@@ -91,13 +91,15 @@ extern SDL_Event quit_event;
 #endif
 
 int inFatal(const char *str) {
+	error(str);
+	delete []str;
 #if 0
 	FILE *fatFile = fopen("fatal.txt", "wt");
 	if (fatFile) {
 		fprintf(fatFile, "FATAL:\n%s\n", str);
 		fclose(fatFile);
 	}
-#endif
+
 	fatalMessage = copyString(str);
 	if (fatalMessage == NULL)
 		fatalMessage = copyString("Out of memory");
@@ -108,7 +110,6 @@ int inFatal(const char *str) {
 	EGL_Close();
 #endif
 
-#if 0
 	SDL_Quit();
 
 	atexit(displayFatal);
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index cf2a053..cc30de2 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -850,18 +850,14 @@ bool continueFunction(loadedFunction *fun) {
 
 	while (keepLooping) {
 		advanceNow = true;
+		debug(kSludgeDebugStackMachine, "Executing command line %i : ", fun->runThisLine);
 		param = fun->compiledLines[fun->runThisLine].param;
 		com = fun->compiledLines[fun->runThisLine].theCommand;
 //		fprintf (stderr, "com: %d param: %d (%s)\n", com, param,
 //				(com < numSludgeCommands) ? sludgeText[com] : ERROR_UNKNOWN_MCODE); fflush(stderr);
 
 		if (numBIFNames) {
-			setFatalInfo(
-					(fun->originalNumber < numUserFunc) ?
-							allUserFunc[fun->originalNumber] :
-							"Unknown user function",
-					(com < numSludgeCommands) ?
-							sludgeText[com] : ERROR_UNKNOWN_MCODE);
+			setFatalInfo((fun->originalNumber < numUserFunc) ? allUserFunc[fun->originalNumber] : "Unknown user function", (com < numSludgeCommands) ? sludgeText[com] : ERROR_UNKNOWN_MCODE);
 //			newDebug (
 //				(com < numSludgeCommands) ? sludgeText[com] : "Unknown SLUDGE machine code",
 //				param);


Commit: d63953d9ce9d37286c9d01eb7b0ab8f15feab475
    https://github.com/scummvm/scummvm/commit/d63953d9ce9d37286c9d01eb7b0ab8f15feab475
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: free resource when finish reading png sprite

Changed paths:
    engines/sludge/sprites.cpp


diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index c457410..b5a2ef9 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -186,6 +186,8 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 				return false;
 			}
 		}
+		finishAccess();
+		setResourceForFatal(-1);
 		return true;
 	}
 


Commit: 5469aaf8ec48050b517933f69c6b2bcbbc288c0f
    https://github.com/scummvm/scummvm/commit/5469aaf8ec48050b517933f69c6b2bcbbc288c0f
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: move initGraphics after sludge init

Changed paths:
    engines/sludge/main_loop.cpp
    engines/sludge/sludge.cpp


diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index a347b64..84d6d74 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -24,6 +24,8 @@
 #include "common/events.h"
 #include "common/keyboard.h"
 
+#include "engines/util.h"
+
 #include "graphics/surface.h"
 
 #include "sludge/allfiles.h"
@@ -253,6 +255,10 @@ int main_loop(const char *filename)
 		return 0;
 	}
 
+	initGraphics(winWidth, winHeight, false, g_sludge->getScreenPixelFormat());
+
+	// Init screen surface
+	renderSurface.create(g_system->getWidth(), g_system->getHeight(), g_system->getScreenFormat());
 #if 0
 	/* Initialize the SDL library */
 	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
diff --git a/engines/sludge/sludge.cpp b/engines/sludge/sludge.cpp
index c4e3083..ab1eb86 100644
--- a/engines/sludge/sludge.cpp
+++ b/engines/sludge/sludge.cpp
@@ -25,8 +25,6 @@
 #include "common/debug-channels.h"
 #include "common/error.h"
 
-#include "engines/util.h"
-
 #include "sludge/sludge.h"
 #include "sludge/main_loop.h"
 
@@ -81,7 +79,6 @@ Common::Error SludgeEngine::run() {
 	// init graphics
 	_origFormat = new Graphics::PixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0);
 	_pixelFormat = new Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0);
-	initGraphics(640, 480, false, _pixelFormat);
 
 	// create console
 	_console = new SludgeConsole(this);


Commit: 1a27d671233cea7cb5cc25a1ff2a905260116398
    https://github.com/scummvm/scummvm/commit/1a27d671233cea7cb5cc25a1ff2a905260116398
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
IMAGE: add flag to skip signature check in png decoder

Changed paths:
    image/png.cpp
    image/png.h


diff --git a/image/png.cpp b/image/png.cpp
index 37617a1..e11f045 100644
--- a/image/png.cpp
+++ b/image/png.cpp
@@ -39,7 +39,7 @@
 
 namespace Image {
 
-PNGDecoder::PNGDecoder() : _outputSurface(0), _palette(0), _paletteColorCount(0) {
+PNGDecoder::PNGDecoder() : _outputSurface(0), _palette(0), _paletteColorCount(0), _skipSignature(false) {
 }
 
 PNGDecoder::~PNGDecoder() {
@@ -99,12 +99,14 @@ bool PNGDecoder::loadStream(Common::SeekableReadStream &stream) {
 #ifdef USE_PNG
 	destroy();
 
-	// First, check the PNG signature
-	if (stream.readUint32BE() != MKTAG(0x89, 'P', 'N', 'G')) {
-		return false;
-	}
-	if (stream.readUint32BE() != MKTAG(0x0d, 0x0a, 0x1a, 0x0a)) {
-		return false;
+	// First, check the PNG signature (if not set to skip it)
+	if (!_skipSignature) {
+		if (stream.readUint32BE() != MKTAG(0x89, 'P', 'N', 'G')) {
+			return false;
+		}
+		if (stream.readUint32BE() != MKTAG(0x0d, 0x0a, 0x1a, 0x0a)) {
+			return false;
+		}
 	}
 
 	// The following is based on the guide provided in:
diff --git a/image/png.h b/image/png.h
index 7ecf68e..cdc3e3f 100644
--- a/image/png.h
+++ b/image/png.h
@@ -56,10 +56,14 @@ public:
 	const Graphics::Surface *getSurface() const { return _outputSurface; }
 	const byte *getPalette() const { return _palette; }
 	uint16 getPaletteColorCount() const { return _paletteColorCount; }
+	void setSkipSignature(bool skip) { _skipSignature = skip; }
 private:
 	byte *_palette;
 	uint16 _paletteColorCount;
 
+	// flag to skip the png signature check for headless png files
+	bool _skipSignature;
+
 	Graphics::Surface *_outputSurface;
 };
 


Commit: 44d7663a495d74275eceb3c3a5d36cf1ed060d3d
    https://github.com/scummvm/scummvm/commit/44d7663a495d74275eceb3c3a5d36cf1ed060d3d
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: read headless png sprites

Changed paths:
    engines/sludge/imgloader.cpp
    engines/sludge/imgloader.h
    engines/sludge/sprites.cpp


diff --git a/engines/sludge/imgloader.cpp b/engines/sludge/imgloader.cpp
index bfac7fa..002e850 100644
--- a/engines/sludge/imgloader.cpp
+++ b/engines/sludge/imgloader.cpp
@@ -44,10 +44,22 @@ bool ImgLoader::loadImage(Common::SeekableReadStream *stream, Graphics::Surface
 	return true;
 }
 
-bool ImgLoader::loadPNGImage(Common::SeekableReadStream *stream, Graphics::Surface *dest) {
+bool ImgLoader::loadPNGImage(Common::SeekableReadStream *stream, Graphics::Surface *dest, bool checkSig) {
 	::Image::PNGDecoder png;
+
+	// set skip signature
+	if (!checkSig) {
+		png.setSkipSignature(true);
+	}
+
 	if (!png.loadStream(*stream))
 		return false;
+
+	// set value back
+	if (!checkSig) {
+		png.setSkipSignature(false);
+	}
+
 	const Graphics::Surface *sourceSurface = png.getSurface();
 	Graphics::Surface *pngSurface = sourceSurface->convertTo(*g_sludge->getScreenPixelFormat(), png.getPalette());
 	dest->copyFrom(*pngSurface);
diff --git a/engines/sludge/imgloader.h b/engines/sludge/imgloader.h
index 35529f5..e4a09e0 100644
--- a/engines/sludge/imgloader.h
+++ b/engines/sludge/imgloader.h
@@ -33,7 +33,7 @@ protected:
 
 public:
 	static bool loadImage(Common::SeekableReadStream *stream, Graphics::Surface *dest, int reserve = -1);
-	static bool loadPNGImage(Common::SeekableReadStream *stream, Graphics::Surface *dest);
+	static bool loadPNGImage(Common::SeekableReadStream *stream, Graphics::Surface *dest, bool checkSig = true);
 	static bool loadHSIImage(Common::SeekableReadStream *stream, Graphics::Surface *dest, int reserve = -1);
 };
 
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index b5a2ef9..51f3062 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -175,15 +175,12 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 
 	// version 3, sprite is png
 	if (spriteBankVersion == 3) {
+		debug("png sprite");
 		for (int i = 0; i < total; i++) {
-			howmany = bigDataFile->readByte();
-			startIndex = 1;
-
 			loadhere.sprites[i].xhot = getSigned(bigDataFile);
 			loadhere.sprites[i].yhot = getSigned(bigDataFile);
-
-			if (!ImgLoader::loadPNGImage(bigDataFile, &loadhere.sprites[i].surface)) {
-				return false;
+			if (!ImgLoader::loadPNGImage(bigDataFile, &loadhere.sprites[i].surface, false)) {
+				return fatal("fail to read png sprite");
 			}
 		}
 		finishAccess();


Commit: e7d1f272dc7b17609c2737b9cd1d1e5b573b1c0b
    https://github.com/scummvm/scummvm/commit/e7d1f272dc7b17609c2737b9cd1d1e5b573b1c0b
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: set sludge game to 1xScale by default

Changed paths:
    engines/sludge/main_loop.cpp


diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index 84d6d74..0410518 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -255,7 +255,7 @@ int main_loop(const char *filename)
 		return 0;
 	}
 
-	initGraphics(winWidth, winHeight, false, g_sludge->getScreenPixelFormat());
+	initGraphics(winWidth, winHeight, true, g_sludge->getScreenPixelFormat());
 
 	// Init screen surface
 	renderSurface.create(g_system->getWidth(), g_system->getHeight(), g_system->getScreenFormat());


Commit: 639f20f16834e813a75293e1d60f6953560799f2
    https://github.com/scummvm/scummvm/commit/639f20f16834e813a75293e1d60f6953560799f2
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: fix bug of setting zbuffer before backdrop

Changed paths:
    engines/sludge/backdrop.cpp
    engines/sludge/zbuffer.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index 76d831e..9bd8cbf 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -58,6 +58,7 @@ GLuint snapshotTextureName = 0;
 #endif
 
 bool backdropExists = false;
+extern int zBufferToSet;
 
 Graphics::Surface lightMap;
 Graphics::Surface backdropSurface;
@@ -319,6 +320,12 @@ void loadBackDrop(int fileNum, int x, int y) {
 
 	finishAccess();
 	setResourceForFatal(-1);
+
+	// set zBuffer if it's not set
+	if (zBufferToSet >= 0) {
+		setZBuffer(zBufferToSet);
+		zBufferToSet = -1;
+	}
 }
 
 void mixBackDrop(int fileNum, int x, int y) {
@@ -876,6 +883,7 @@ bool loadHSI(Common::SeekableReadStream *stream, int x, int y, bool reserve) {
 	deleteTextures(1, &tmpTex);
 #endif
 	backdropExists = true;
+
 	return true;
 }
 
diff --git a/engines/sludge/zbuffer.cpp b/engines/sludge/zbuffer.cpp
index 76fa515..f2d627e 100644
--- a/engines/sludge/zbuffer.cpp
+++ b/engines/sludge/zbuffer.cpp
@@ -35,6 +35,7 @@
 
 namespace Sludge {
 
+int zBufferToSet = -1;
 zBufferData zBuffer;
 extern int sceneWidth, sceneHeight;
 extern Graphics::Surface backdropSurface;
@@ -73,7 +74,12 @@ void sortZPal(int *oldpal, int *newpal, int size) {
 }
 
 bool setZBuffer(int num) {
-	debug("Setting zBuffer");
+	// if the backdrop has not been set yet
+	// set zbuffer later
+	if (!backdropSurface.getPixels()) {
+		zBufferToSet = num;
+		return true;
+	}
 	uint32 stillToGo = 0;
 	int yPalette[16], sorted[16], sortback[16];
 


Commit: 15e7f5c48e4e2747223d04445902fc13f23bd956
    https://github.com/scummvm/scummvm/commit/15e7f5c48e4e2747223d04445902fc13f23bd956
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: fix unmatched delete []

Changed paths:
    engines/sludge/objtypes.cpp
    engines/sludge/sludger.cpp


diff --git a/engines/sludge/objtypes.cpp b/engines/sludge/objtypes.cpp
index ffd2c83..8b660fc 100644
--- a/engines/sludge/objtypes.cpp
+++ b/engines/sludge/objtypes.cpp
@@ -166,8 +166,8 @@ void removeObjectType(objectType *oT) {
 //			fclose (debuggy2);
 
 			*huntRegion = oT->next;
-			delete oT->allCombis;
-			delete oT->screenName;
+			delete []oT->allCombis;
+			delete []oT->screenName;
 			delete oT;
 			return;
 		} else {
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index cc30de2..c9005e3 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -546,7 +546,7 @@ bool initSludge(const char *filename) {
 
 		if (chdir(dataFolder)) return fatal("This game's data folder is inaccessible!\nI can't access the following directory (maybe there's a file with the same name, or maybe it's read-protected):", dataFolder);
 #endif
-		delete dataFolder;
+		delete []dataFolder;
 	}
 
 	positionStatus(10, winHeight - 15);


Commit: ae54897ff5119ed605b875bc4bcb71691f7eb406
    https://github.com/scummvm/scummvm/commit/ae54897ff5119ed605b875bc4bcb71691f7eb406
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: add channel to debug text

Changed paths:
    engines/sludge/sprites.cpp
    engines/sludge/zbuffer.cpp


diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index 51f3062..e31f66d 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -175,7 +175,7 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 
 	// version 3, sprite is png
 	if (spriteBankVersion == 3) {
-		debug("png sprite");
+		debug(kSludgeDebugGraphics, "png sprite");
 		for (int i = 0; i < total; i++) {
 			loadhere.sprites[i].xhot = getSigned(bigDataFile);
 			loadhere.sprites[i].yhot = getSigned(bigDataFile);
diff --git a/engines/sludge/zbuffer.cpp b/engines/sludge/zbuffer.cpp
index f2d627e..97c44e8 100644
--- a/engines/sludge/zbuffer.cpp
+++ b/engines/sludge/zbuffer.cpp
@@ -80,6 +80,8 @@ bool setZBuffer(int num) {
 		zBufferToSet = num;
 		return true;
 	}
+
+	debug (kSludgeDebugGraphics, "Setting zBuffer");
 	uint32 stillToGo = 0;
 	int yPalette[16], sorted[16], sortback[16];
 


Commit: 3b3c92558bbda6439d74d6fce77f754b83bbdd28
    https://github.com/scummvm/scummvm/commit/3b3c92558bbda6439d74d6fce77f754b83bbdd28
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: add game timing

Changed paths:
    engines/sludge/main_loop.cpp
    engines/sludge/timing.cpp


diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index 0410518..d530555 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -319,12 +319,8 @@ int main_loop(const char *filename)
 
 	startNewFunctionNum(0, 0, NULL, noStack);
 
-#if 0
 	Init_Timer();
 
-	SDL_EnableUNICODE(1);
-#endif
-	renderSurface.create(g_system->getWidth(), g_system->getHeight(), g_system->getScreenFormat());
 	weAreDoneSoQuit = 0;
 	while (!weAreDoneSoQuit) {
 		checkInput();
@@ -332,10 +328,7 @@ int main_loop(const char *filename)
 		handleInput();
 		sludgeDisplay();
 		handleSoundLists();
-		g_system->delayMillis(1000 / desiredfps);
-#if 0
 		Wait_Frame();
-#endif
 	}
 
 	debugOut("Bye!\n\n");
diff --git a/engines/sludge/timing.cpp b/engines/sludge/timing.cpp
index 152d9ae..2e83e1d 100644
--- a/engines/sludge/timing.cpp
+++ b/engines/sludge/timing.cpp
@@ -20,33 +20,35 @@
  *
  */
 
+#include "sludge/allfiles.h"
+#include "sludge/timing.h"
+
 namespace Sludge {
 
 int desiredfps = 300;               //holds desired frames per second
 
-#if 0
-Uint32 starttime, endtime;
-Uint32 desired_frame_time;
+uint32 starttime, endtime;
+uint32 desired_frame_time;
 
 void Init_Timer(void) {
 	desired_frame_time = 1000 / desiredfps;
-	starttime = SDL_GetTicks();
+	starttime = g_system->getMillis();
 }
 
 void Init_Special_Timer(int t) {
 	desired_frame_time = 1000 / t;
-	starttime = SDL_GetTicks();
+	starttime = g_system->getMillis();
 }
 
 void Wait_Frame(void) {
-	static Uint32 addNextTime = 0;
-	Uint32 timetaken;
+	static uint32 addNextTime = 0;
+	uint32 timetaken;
 
 	for (;;) {
-		endtime = SDL_GetTicks();
+		endtime = g_system->getMillis();
 		timetaken = addNextTime + endtime - starttime;
 		if (timetaken >= desired_frame_time) break;
-		SDL_Delay(1);
+		g_system->delayMillis(1);
 	}
 
 	addNextTime = timetaken - desired_frame_time;
@@ -54,7 +56,5 @@ void Wait_Frame(void) {
 
 	starttime = endtime;
 }
-#endif
 
-}
-               // End of namespace Sludge
+} // End of namespace Sludge


Commit: 9a57db6b9c45363605bd7e33a2428fff88d28652
    https://github.com/scummvm/scummvm/commit/9a57db6b9c45363605bd7e33a2428fff88d28652
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: correct text color for png font

Changed paths:
    engines/sludge/sprites.cpp


diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index e31f66d..dc3dc82 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -317,7 +317,7 @@ void pasteSpriteToBackDrop(int x1, int y1, sprite &single, const spritePalette &
 	x1 -= single.xhot;
 	y1 -= single.yhot;
 	Graphics::TransparentSurface tmp(single.surface, false);
-	tmp.blit(backdropSurface, x1, y1);
+	tmp.blit(backdropSurface, x1, y1, Graphics::FLIP_NONE, nullptr, TS_RGB(fontPal.originalRed, fontPal.originalGreen, fontPal.originalBlue));
 #if 0
 	float tx1 = (float)(single.tex_x) / fontPal.tex_w[single.texNum];
 	float ty1 = 0.0;
@@ -530,7 +530,7 @@ void fontSprite(bool flip, int x, int y, sprite &single, const spritePalette &fo
 
 	// Use Transparent surface to scale and blit
 	Graphics::TransparentSurface tmp(single.surface, false);
-	tmp.blit(renderSurface, x1, y1, (flip ? Graphics::FLIP_H : Graphics::FLIP_NONE));
+	tmp.blit(renderSurface, x1, y1, (flip ? Graphics::FLIP_H : Graphics::FLIP_NONE), 0, TS_RGB(fontPal.originalRed, fontPal.originalGreen, fontPal.originalBlue));
 
 	if (single.burnSurface.getPixels() != nullptr) {
 		Graphics::TransparentSurface tmp2(single.burnSurface, false);


Commit: 082bf55b56712715391831b851b5b4aec64c8632
    https://github.com/scummvm/scummvm/commit/082bf55b56712715391831b851b5b4aec64c8632
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: clean debug info

Changed paths:
    engines/sludge/variable.cpp


diff --git a/engines/sludge/variable.cpp b/engines/sludge/variable.cpp
index e811c65..13f6608 100644
--- a/engines/sludge/variable.cpp
+++ b/engines/sludge/variable.cpp
@@ -516,7 +516,7 @@ bool addVarToStack(const variable &va, variableStack *&thisStack) {
 		return false;
 	newStack->next = thisStack;
 	thisStack = newStack;
-	debug(kSludgeDebugStackMachine, "Variable %s was added to stack", getTextFromAnyVar(va));
+	//debug(kSludgeDebugStackMachine, "Variable %s was added to stack", getTextFromAnyVar(va));
 	return true;
 }
 
@@ -532,7 +532,7 @@ bool addVarToStackQuick(variable &va, variableStack *&thisStack) {
 
 	newStack->next = thisStack;
 	thisStack = newStack;
-	debug(kSludgeDebugStackMachine, "Variable %s was added to stack quick", getTextFromAnyVar(va));
+	//debug(kSludgeDebugStackMachine, "Variable %s was added to stack quick", getTextFromAnyVar(va));
 	return true;
 }
 
@@ -605,48 +605,11 @@ void trimStack(variableStack *&stack) {
 	variableStack *killMe = stack;
 	stack = stack->next;
 
-	debug(kSludgeDebugStackMachine, "Variable %s was removed from stack", getTextFromAnyVar(killMe->thisVar));
+	//debug(kSludgeDebugStackMachine, "Variable %s was removed from stack", getTextFromAnyVar(killMe->thisVar));
 
 	// When calling this, we've ALWAYS checked that stack != NULL
 	unlinkVar(killMe->thisVar);
 	delete killMe;
 }
-/*
- void debugVar (FILE * fp, const variable & thisVar) {
- switch (thisVar.varType) {
- case SVT_INT:
- fprintf (fp, "integer value %i", thisVar.varData.intValue);
- break;
-
- case SVT_FUNC:
- fprintf (fp, "pointer to function %i", thisVar.varData.intValue);
- break;
-
- case SVT_BUILT:
- fprintf (fp, "pointer to bif %i", thisVar.varData.intValue);
- break;
-
- case SVT_OBJTYPE:
- fprintf (fp, "object type %i", thisVar.varData.intValue);
- break;
-
- case SVT_STRING:
- fprintf (fp, "\"%s\"", thisVar.varData.theString);
- break;
-
- case SVT_FILE:
- fprintf (fp, "file handle %i", thisVar.varData.intValue);
- break;
-
- case SVT_NULL:
- fprintf (fp, "null");
- break;
-
- default:
- fprintf (fp, "unknown variable type");
- break;
- }
- }
- */
 
 } // End of namespace Sludge


Commit: 91d2b5d31e72f635e0f7d498f632fcd942713a15
    https://github.com/scummvm/scummvm/commit/91d2b5d31e72f635e0f7d498f632fcd942713a15
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: kill a sprite bank

Changed paths:
    engines/sludge/sprites.cpp


diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index dc3dc82..161cb62 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -75,21 +75,6 @@ extern Graphics::Surface backdropSurface;
 unsigned char currentBurnR = 0, currentBurnG = 0, currentBurnB = 0;
 
 void forgetSpriteBank(spriteBank &forgetme) {
-#if 0
-	deleteTextures(forgetme.myPalette.numTextures, forgetme.myPalette.tex_names);
-	if (forgetme.isFont) {
-		deleteTextures(forgetme.myPalette.numTextures, forgetme.myPalette.burnTex_names);
-		delete [] forgetme.myPalette.burnTex_names;
-		forgetme.myPalette.burnTex_names = NULL;
-	}
-
-	delete [] forgetme.myPalette.tex_names;
-	forgetme.myPalette.tex_names = NULL;
-	delete[] forgetme.myPalette.tex_w;
-	forgetme.myPalette.tex_w = NULL;
-	delete[] forgetme.myPalette.tex_h;
-	forgetme.myPalette.tex_h = NULL;
-#endif
 	if (forgetme.myPalette.pal) {
 		delete[] forgetme.myPalette.pal;
 		forgetme.myPalette.pal = NULL;
@@ -101,7 +86,12 @@ void forgetSpriteBank(spriteBank &forgetme) {
 		forgetme.myPalette.b = NULL;
 	}
 
-	delete forgetme.sprites;
+	for (int i = 0; i < forgetme.total; ++i) {
+		forgetme.sprites[i].surface.free();
+		forgetme.sprites[i].burnSurface.free();
+	}
+
+	delete []forgetme.sprites;
 	forgetme.sprites = NULL;
 
 	// TODO: also remove sprite bank from allLoadedBanks


Commit: b5a77c93930cac9532eab4bb7a777424c7639e21
    https://github.com/scummvm/scummvm/commit/b5a77c93930cac9532eab4bb7a777424c7639e21
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: check point to non transparent part of a character

Changed paths:
    engines/sludge/sprites.cpp


diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index 161cb62..6d51b8f 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -609,8 +609,6 @@ void setDrawMode(onScreenPerson *thisPerson) {
 extern GLuint backdropTextureName;
 #endif
 
-bool checkColourChange(bool reset);
-
 bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *thisPerson, bool mirror) {
 	float x = thisPerson->x;
 	float y = thisPerson->y;
@@ -660,7 +658,15 @@ bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *t
 	if (input.mouseX >= x1 && input.mouseX <= x2 && input.mouseY >= y1 && input.mouseY <= y2) {
 		if (thisPerson->extra & EXTRA_RECTANGULAR)
 			return true;
-		return true;
+
+		// check if point to non transparent part
+		int pixelx = (int)(single.surface.w * (input.mouseX - x1) / (x2 - x1));
+		int pixely = (int)(single.surface.h * (input.mouseY - y1) / (y2 - y1));
+		uint32 *colorPtr = (uint32 *)single.surface.getBasePtr(pixelx, pixely);
+
+		uint8 a, r, g, b;
+		g_sludge->getScreenPixelFormat()->colorToARGB(*colorPtr, a, r, g, b);
+		return a != 0;
 	}
 	return false;
 


Commit: 0e8db2bf0d5cd03b23694440fbb05d51f1a02879
    https://github.com/scummvm/scummvm/commit/0e8db2bf0d5cd03b23694440fbb05d51f1a02879
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: add blankscreen effect

Changed paths:
    engines/sludge/backdrop.cpp
    engines/sludge/builtin.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index 9bd8cbf..93a1e0f 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -72,9 +72,7 @@ int cameraPX = 0, cameraPY = 0;
 
 unsigned int sceneWidth, sceneHeight;
 int lightMapNumber;
-#if 0
-unsigned int currentBlankColour = g_sludge->getOrigPixelFormat()->RGBToColor(0, 0, 0);
-#endif
+unsigned int currentBlankColour = TS_ARGB(255, 0, 0, 0);
 
 extern int cameraX, cameraY;
 extern float cameraZoom;
@@ -344,6 +342,10 @@ void mixBackDrop(int fileNum, int x, int y) {
 }
 
 void blankScreen(int x1, int y1, int x2, int y2) {
+	// in case of no backdrop added at all
+	if (!backdropSurface.getPixels()) {
+		return;
+	}
 
 	if (y1 < 0)
 		y1 = 0;
@@ -354,8 +356,8 @@ void blankScreen(int x1, int y1, int x2, int y2) {
 	if (y2 > (int)sceneHeight)
 		y2 = (int)sceneHeight;
 
-	int picWidth = x2 - x1;
-	int picHeight = y2 - y1;
+	backdropSurface.fillRect(Common::Rect(x1, y1, x2, y2), currentBlankColour);
+
 #if 0
 	setPixelCoords(true);
 
@@ -473,6 +475,8 @@ inline int sortOutPCamera(int cX, int fX, int sceneMax, int boxMax) {
 }
 
 void drawBackDrop() {
+	if (!backdropExists)
+		return;
 	renderSurface.copyRectToSurface(backdropSurface, 0, 0, Common::Rect(0, 0, backdropSurface.w, backdropSurface.h));
 #if 0
 	setPrimaryColor(1.0, 1.0, 1.0, 1.0);
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 3ac316d..6af0eaf 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -91,9 +91,7 @@ extern unsigned char brightnessLevel;
 extern unsigned char fadeMode;
 extern unsigned short saveEncoding;
 extern frozenStuffStruct *frozenStuff;
-#if 0
 extern unsigned int currentBlankColour;
-#endif
 extern unsigned int languageID;
 extern unsigned char currentBurnR, currentBurnG, currentBurnB;
 
@@ -850,9 +848,8 @@ builtIn(setBlankColour) {
 
 	if (!getRGBParams(red, green, blue, fun))
 		return BR_ERROR;
-#if 0
+
 	currentBlankColour = g_sludge->getOrigPixelFormat()->RGBToColor(red & 255, green & 255, blue & 255);
-#endif
 	setVariable(fun->reg, SVT_INT, 1);
 	return BR_CONTINUE;
 }


Commit: 874d03f79be2df77db72767e05bc7b019a8a961e
    https://github.com/scummvm/scummvm/commit/874d03f79be2df77db72767e05bc7b019a8a961e
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: stop a sound by file number

SLUDGE: stop a sound by

Changed paths:
    engines/sludge/sound.cpp


diff --git a/engines/sludge/sound.cpp b/engines/sludge/sound.cpp
index 56a28d8..745c3a2 100644
--- a/engines/sludge/sound.cpp
+++ b/engines/sludge/sound.cpp
@@ -189,21 +189,16 @@ void stopMOD(int i) {
 void huntKillSound(int filenum) {
 	if (!soundOK)
 		return;
-#if 0
-	// Clear OpenAL errors to make sure they don't block anything:
-	alGetError();
 
 	int gotSlot = findInSoundCache(filenum);
 	if (gotSlot == -1) return;
 
 	SilenceIKillYou = true;
 
-	if (soundCache[gotSlot].playing) {
-		if (! alureStopSource(soundCache[gotSlot].playingOnSource, AL_TRUE)) {
-			debugOut("Failed to stop source: %s\n", alureGetErrorString());
-		}
+	if (g_sludge->_mixer->isSoundHandleActive(soundCache[gotSlot].handle)) {
+		g_sludge->_mixer->stopHandle(soundCache[gotSlot].handle);
 	}
-#endif
+
 	SilenceIKillYou = false;
 }
 


Commit: 791aedf7a5c347fdfad901ae2054a4c81ef72ca5
    https://github.com/scummvm/scummvm/commit/791aedf7a5c347fdfad901ae2054a4c81ef72ca5
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
Image: extend writePng for 4-byte pixelFormat

Changed paths:
    image/png.cpp


diff --git a/image/png.cpp b/image/png.cpp
index e11f045..fc0daf9 100644
--- a/image/png.cpp
+++ b/image/png.cpp
@@ -249,13 +249,35 @@ bool PNGDecoder::loadStream(Common::SeekableReadStream &stream) {
 
 bool writePNG(Common::WriteStream &out, const Graphics::Surface &input, const bool bottomUp) {
 #ifdef USE_PNG
-	const Graphics::PixelFormat requiredFormat(3, 8, 8, 8, 0, 16, 8, 0, 0);
+	const Graphics::PixelFormat requiredFormat_3byte(3, 8, 8, 8, 0, 16, 8, 0, 0);
+	const Graphics::PixelFormat requiredFormat_4byte(4, 8, 8, 8, 8, 16, 8, 0, 24);
 
-	if (input.format != requiredFormat) {
-		warning("Cannot currently write PNG with pixel format other than %s", requiredFormat.toString().c_str());
+	if (input.format.bytesPerPixel == 3) {
+		if (input.format != requiredFormat_3byte) {
+			warning("Cannot currently write PNG with 3-byte pixel format other than %s", requiredFormat_3byte.toString().c_str());
+			return false;
+		}
+	} else if (input.format.bytesPerPixel != 4) {
+		warning("Cannot currently write PNG with pixel format of bpp other than 3, 4");
 		return false;
 	}
 
+	int colorType;
+	Graphics::Surface *tmp = NULL;
+	const Graphics::Surface *surface;
+
+	if (input.format == requiredFormat_3byte) {
+		surface = &input;
+		colorType = PNG_COLOR_TYPE_RGB;
+	} else {
+		if (input.format == requiredFormat_4byte) {
+			surface = &input;
+		} else {
+			surface = tmp = input.convertTo(requiredFormat_4byte);
+		}
+		colorType = PNG_COLOR_TYPE_RGB_ALPHA;
+	}
+
 	png_structp pngPtr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
 	if (!pngPtr) {
 		return false;
@@ -276,23 +298,30 @@ bool writePNG(Common::WriteStream &out, const Graphics::Surface &input, const bo
 
 	png_set_write_fn(pngPtr, &out, pngWriteToStream, pngFlushStream);
 
-	png_set_IHDR(pngPtr, infoPtr, input.w, input.h, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
+	png_set_IHDR(pngPtr, infoPtr, surface->w, surface->h, 8, colorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
 
 	Common::Array<const uint8 *> rows;
-	rows.reserve(input.h);
+	rows.reserve(surface->h);
 	if (bottomUp) {
-		for (uint y = input.h; y-- > 0;) {
-			rows.push_back((const uint8 *)input.getBasePtr(0, y));
+		for (uint y = surface->h; y-- > 0;) {
+			rows.push_back((const uint8 *)surface->getBasePtr(0, y));
 		}
 	} else {
-		for (uint y = 0; y < input.h; ++y) {
-			rows.push_back((const uint8 *)input.getBasePtr(0, y));
+		for (uint y = 0; y < surface->h; ++y) {
+			rows.push_back((const uint8 *)surface->getBasePtr(0, y));
 		}
 	}
 
 	png_set_rows(pngPtr, infoPtr, const_cast<uint8 **>(&rows.front()));
 	png_write_png(pngPtr, infoPtr, 0, NULL);
 	png_destroy_write_struct(&pngPtr, &infoPtr);
+
+	// free tmp surface
+	if (tmp) {
+		tmp->free();
+		delete tmp;
+	}
+
 	return true;
 #else
 	return false;


Commit: 8152793d09a8a776213a31f457fed897e62cc4b0
    https://github.com/scummvm/scummvm/commit/8152793d09a8a776213a31f457fed897e62cc4b0
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: save&load system (without thumbnail and snapshot)

Changed paths:
    engines/sludge/backdrop.cpp
    engines/sludge/builtin.cpp
    engines/sludge/loadsave.cpp
    engines/sludge/talk.cpp
    engines/sludge/thumbnail.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index 93a1e0f..8ab4c6f 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -1009,108 +1009,7 @@ bool mixHSI(Common::SeekableReadStream *stream, int x, int y) {
 #endif
 	return true;
 }
-#if 0
-void saveCorePNG(Common::WriteStream *stream, GLuint texture, int w, int h) {
-	GLint tw, th;
-
-	glBindTexture(GL_TEXTURE_2D, texture);
-
-	getTextureDimensions(texture, &tw, &th);
-
-	GLubyte *image = new GLubyte [tw * th * 4];
-	if (!checkNew(image)) return;
-
-	glPixelStorei(GL_PACK_ALIGNMENT, 1);
-//	glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
-
-#ifdef HAVE_GLES2
-	GLuint old_fbo, new_fbo;
-	GLint old_vp[4];
-	glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint *)&old_fbo);
-	glGetIntegerv(GL_VIEWPORT, old_vp);
-	glGenFramebuffers(1, &new_fbo);
-	glBindFramebuffer(GL_FRAMEBUFFER, new_fbo);
-	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
-	glViewport(0, 0, tw, th);
-	glReadPixels(0, 0, tw, th, GL_RGBA, GL_UNSIGNED_BYTE, image);
-	glBindFramebuffer(GL_FRAMEBUFFER, old_fbo);
-	glViewport(old_vp[0], old_vp[1], old_vp[2], old_vp[3]);
-	glDeleteFramebuffers(1, &new_fbo);
-#else
-	setPixelCoords(true);
-	const GLfloat texCoords[] = {
-		0.0f, 0.0f,
-		1.0f, 0.0f,
-		0.0f, 1.0f,
-		1.0f, 1.0f
-	};
 
-	int xoffset = 0;
-	while (xoffset < tw) {
-		int w = (tw - xoffset < viewportWidth) ? tw - xoffset : viewportWidth;
-
-		int yoffset = 0;
-		while (yoffset < th) {
-			int h = (th - yoffset < viewportHeight) ? th - yoffset : viewportHeight;
-
-			glClear(GL_COLOR_BUFFER_BIT);   // Clear The Screen
-			const GLfloat vertices[] = {
-				(GLfloat) - xoffset, (GLfloat) - yoffset, 0.,
-				(GLfloat)tw - xoffset, (GLfloat) - yoffset, 0.,
-				(GLfloat) - xoffset, (GLfloat) - yoffset + th, 0.,
-				(GLfloat)tw - xoffset, (GLfloat) - yoffset + th, 0.
-			};
-
-			glUseProgram(shader.texture);
-
-			setPMVMatrix(shader.texture);
-
-			drawQuad(shader.texture, vertices, 1, texCoords);
-
-			glUseProgram(0);
-
-			for (int i = 0; i < h; i++) {
-				glReadPixels(viewportOffsetX, viewportOffsetY + i, w, 1, GL_RGBA, GL_UNSIGNED_BYTE, image + xoffset * 4 + (yoffset + i) * 4 * tw);
-			}
-			yoffset += viewportHeight;
-		}
-
-		xoffset += viewportWidth;
-	}
-	setPixelCoords(false);
-
-	png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
-	if (!png_ptr) {
-		fatal("Error saving image!");
-		return;
-	}
-
-	png_infop info_ptr = png_create_info_struct(png_ptr);
-	if (!info_ptr) {
-		png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
-		fatal("Error saving image!");
-		return;
-	}
-
-	png_init_io(png_ptr, writer);
-
-	png_set_IHDR(png_ptr, info_ptr, w, h,
-			8, PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
-
-	unsigned char *row_pointers[h];
-
-	for (int i = 0; i < h; i++) {
-		row_pointers[i] = image + 4 * i * tw;
-	}
-
-	png_set_rows(png_ptr, info_ptr, row_pointers);
-	png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
-
-	delete [] image;
-	image = NULL;
-#endif
-}
-#endif
 #if 0
 void saveCoreHSI(Common::WriteStream *stream, GLuint texture, int w, int h) {
 	GLint tw, th;
@@ -1188,11 +1087,9 @@ void saveCoreHSI(Common::WriteStream *stream, GLuint texture, int w, int h) {
 }
 #endif
 
-#if 0
 void saveHSI(Common::WriteStream *stream) {
-	saveCorePNG(stream, backdropTextureName, sceneWidth, sceneHeight);
+	Image::writePNG(*stream, backdropSurface);
 }
-#endif
 
 void saveParallaxRecursive(parallaxLayer *me, Common::WriteStream *stream) {
 	if (me) {
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 6af0eaf..21818b9 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -347,7 +347,7 @@ builtIn(loadGame) {
 	char *aaaaa = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
 	loadNow = encodeFilename(aaaaa);
-	delete aaaaa;
+	delete []aaaaa;
 
 	if (frozenStuff) {
 		fatal("Can't load a saved game while the engine is frozen");
@@ -359,9 +359,10 @@ builtIn(loadGame) {
 		fd.close();
 		return BR_KEEP_AND_PAUSE;
 	}
-	delete loadNow;
+	delete []loadNow;
 	loadNow = NULL;
 
+	debug("not find sav file");
 	return BR_CONTINUE;
 }
 
diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index fb668b5..d397092 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -20,6 +20,8 @@
  *
  */
 
+#include "common/savefile.h"
+
 #include "sludge/allfiles.h"
 #include "sludge/sprites.h"
 #include "sludge/fonttext.h"
@@ -41,6 +43,8 @@
 #include "sludge/fileset.h"
 #include "sludge/debug.h"
 #include "sludge/loadsave.h"
+#include "sludge/bg_effects.h"
+#include "sludge/thumbnail.h"
 #include "sludge/CommonCode/version.h"
 
 namespace Sludge {
@@ -74,9 +78,7 @@ extern bool captureAllKeys;
 extern bool allowAnyFilename;
 extern unsigned short saveEncoding;                 // in savedata.cpp
 extern unsigned char currentBurnR, currentBurnG, currentBurnB;
-#if 0
 extern unsigned int currentBlankColour;             // in backdrop.cpp
-#endif
 extern parallaxLayer *parallaxStuff;                //      "
 extern int lightMapMode;                    //      "
 extern int languageNum;
@@ -383,28 +385,28 @@ loadedFunction *loadFunction(Common::SeekableReadStream *stream) {
 //----------------------------------------------------------------------
 
 bool saveGame(char *fname) {
-#if 0
-	int a;
+	Common::OutSaveFile *fp = g_system->getSavefileManager()->openForSaving(fname);
 
-	FILE *fp = fopen(fname, "wb");
-	if (fp == NULL) return false;
+	if (fp == NULL)
+		return false;
 
-	fprintf(fp, "SLUDSA");
-	fputc(0, fp);
-	fputc(0, fp);
-	fputc(MAJOR_VERSION, fp);
-	fputc(MINOR_VERSION, fp);
+	fp->writeString("SLUDSA");
+	fp->writeByte(0);
+	fp->writeByte(0);
+	fp->writeByte(MAJOR_VERSION);
+	fp->writeByte(MINOR_VERSION);
 
-	if (! saveThumbnail(fp)) return false;
+	if (!saveThumbnail(fp))
+		return false;
 
-	fwrite(&fileTime, sizeof(FILETIME), 1, fp);
+	fp->write(&fileTime, sizeof(FILETIME));
 
 	// DON'T ADD ANYTHING NEW BEFORE THIS POINT!
 
-	fputc(allowAnyFilename, fp);
-	fputc(captureAllKeys, fp);
-	fputc(true, fp);// updateDisplay
-	fputc(fontTableSize > 0, fp);
+	fp->writeByte(allowAnyFilename);
+	fp->writeByte(captureAllKeys);
+	fp->writeByte(true);
+	fp->writeByte(fontTableSize > 0);
 
 	if (fontTableSize > 0) {
 		fp->writeUint16BE(loadedFontNum);
@@ -418,7 +420,7 @@ bool saveGame(char *fname) {
 	fp->writeUint16BE(cameraY);
 	putFloat(cameraZoom, fp);
 
-	fputc(brightnessLevel, fp);
+	fp->writeByte(brightnessLevel);
 	saveHSI(fp);
 
 	// Save event handlers
@@ -434,7 +436,7 @@ bool saveGame(char *fname) {
 	loadedFunction *thisFunction = allRunningFunctions;
 	int countFunctions = 0;
 	while (thisFunction) {
-		countFunctions ++;
+		countFunctions++;
 		thisFunction = thisFunction->next;
 	}
 	fp->writeUint16BE(countFunctions);
@@ -445,30 +447,36 @@ bool saveGame(char *fname) {
 		thisFunction = thisFunction->next;
 	}
 
-	for (a = 0; a < numGlobals; a++) {
+	for (int a = 0; a < numGlobals; a++) {
 		saveVariable(&globalVars[a], fp);
 	}
 
 	savePeople(fp);
 
 	if (currentFloor->numPolygons) {
-		fputc(1, fp);
+		fp->writeByte(1);
 		fp->writeUint16BE(currentFloor->originalNum);
-	} else fputc(0, fp);
+	} else {
+		fp->writeByte(0);
+	}
 
-	if (zBuffer.tex) {
-		fputc(1, fp);
+	if (zBuffer.numPanels > 0) {
+		fp->writeByte(1);
 		fp->writeUint16BE(zBuffer.originalNum);
-	} else fputc(0, fp);
+	} else {
+		fp->writeByte(0);
+	}
 
-	if (lightMap.data) {
-		fputc(1, fp);
+	if (lightMap.getPixels()) {
+		fp->writeByte(1);
 		fp->writeUint16BE(lightMapNumber);
-	} else fputc(0, fp);
+	} else {
+		fp->writeByte(0);
+	}
 
-	fputc(lightMapMode, fp);
-	fputc(speechMode, fp);
-	fputc(fadeMode, fp);
+	fp->writeByte(lightMapMode);
+	fp->writeByte(speechMode);
+	fp->writeByte(fadeMode);
 	saveSpeech(speech, fp);
 	saveStatusBars(fp);
 	saveSounds(fp);
@@ -478,19 +486,21 @@ bool saveGame(char *fname) {
 	blur_saveSettings(fp);
 
 	fp->writeUint16BE(currentBlankColour);
-	fputc(currentBurnR, fp);
-	fputc(currentBurnG, fp);
-	fputc(currentBurnB, fp);
+	fp->writeByte(currentBurnR);
+	fp->writeByte(currentBurnG);
+	fp->writeByte(currentBurnB);
 
 	saveParallaxRecursive(parallaxStuff, fp);
-	fputc(0, fp);
+	fp->writeByte(0);
 
-	fputc(languageNum, fp);     // Selected language
+	fp->writeByte(languageNum); // Selected language
 
 	saveSnapshot(fp);
 
-	fclose(fp);
-#endif
+	fp->flush();
+	fp->finalize();
+	delete fp;
+
 	clearStackLib();
 	return true;
 }
@@ -502,39 +512,65 @@ bool saveGame(char *fname) {
 int ssgVersion;
 
 bool loadGame(char *fname) {
-#if 0
-	FILE *fp;
+	Common::InSaveFile *fp = g_system->getSavefileManager()->openForLoading(fname);
 	FILETIME savedGameTime;
-	int a;
 
-	while (allRunningFunctions) finishFunction(allRunningFunctions);
+	while (allRunningFunctions)
+		finishFunction(allRunningFunctions);
+
+	if (fp == NULL)
+		return false;
+
+	bool headerBad = false;
+	if (fp->readByte() != 'S')
+		headerBad = true;
+	if (fp->readByte() != 'L')
+		headerBad = true;
+	if (fp->readByte() != 'U')
+		headerBad = true;
+	if (fp->readByte() != 'D')
+		headerBad = true;
+	if (fp->readByte() != 'S')
+		headerBad = true;
+	if (fp->readByte() != 'A')
+		headerBad = true;
+	if (headerBad) {
+		fatal(ERROR_GAME_LOAD_NO, fname);
+		return NULL;
+	}
+	char c;
+	c = fp->readByte();
+	while ((c = fp->readByte()))
+		;
+
+	int majVersion = fp->readByte();
+	int minVersion = fp->readByte();
+	ssgVersion = majVersion * 256 + minVersion;
 
-	fp = openAndVerify(fname, 'S', 'A', ERROR_GAME_LOAD_NO, ssgVersion);
-	if (fp == NULL) return false;
 
 	if (ssgVersion >= VERSION(1, 4)) {
-		if (! skipThumbnail(fp)) return fatal(ERROR_GAME_LOAD_CORRUPT, fname);
+		if (!skipThumbnail(fp))
+			return fatal(ERROR_GAME_LOAD_CORRUPT, fname);
 	}
 
-	size_t bytes_read = fread(&savedGameTime, sizeof(FILETIME), 1, fp);
-	if (bytes_read != sizeof(FILETIME) && ferror(fp)) {
+	uint32 bytes_read = fp->read(&savedGameTime, sizeof(FILETIME));
+	if (bytes_read != sizeof(FILETIME) && fp->err()) {
 		debugOut("Reading error in loadGame.\n");
 	}
 
-	if (savedGameTime.dwLowDateTime != fileTime.dwLowDateTime ||
-			savedGameTime.dwHighDateTime != fileTime.dwHighDateTime) {
+	if (savedGameTime.dwLowDateTime != fileTime.dwLowDateTime || savedGameTime.dwHighDateTime != fileTime.dwHighDateTime) {
 		return fatal(ERROR_GAME_LOAD_WRONG, fname);
 	}
 
 	// DON'T ADD ANYTHING NEW BEFORE THIS POINT!
 
 	if (ssgVersion >= VERSION(1, 4)) {
-		allowAnyFilename = fgetc(fp);
+		allowAnyFilename = fp->readByte();
 	}
-	captureAllKeys = fgetc(fp);
-	fgetc(fp);  // updateDisplay (part of movie playing)
+	captureAllKeys = fp->readByte();
+	fp->readByte();  // updateDisplay (part of movie playing)
 
-	bool fontLoaded = fgetc(fp);
+	bool fontLoaded = fp->readByte();
 	int fontNum;
 	char *charOrder;
 	if (fontLoaded) {
@@ -544,10 +580,11 @@ bool loadGame(char *fname) {
 		if (ssgVersion < VERSION(2, 2)) {
 			int x;
 			charOrder = new char[257];
-			if (! checkNew(charOrder)) return false;
+			if (!checkNew(charOrder))
+				return false;
 
 			for (int a = 0; a < 256; a++) {
-				x = fgetc(fp);
+				x = fp->readByte();
 				charOrder[x] = a;
 			}
 			charOrder[256] = 0;
@@ -556,7 +593,7 @@ bool loadGame(char *fname) {
 		}
 	}
 	loadFont(fontNum, charOrder, fontHeight);
-	delete [] charOrder;
+	delete []charOrder;
 
 	fontSpace = getSigned(fp);
 
@@ -572,53 +609,59 @@ bool loadGame(char *fname) {
 		camerZ = 1.0;
 	}
 
-	brightnessLevel = fgetc(fp);
+	brightnessLevel = fp->readByte();
 
 	loadHSI(fp, 0, 0, true);
 	loadHandlers(fp);
 	loadRegions(fp);
 
 	mouseCursorAnim = new personaAnimation;
-	if (! checkNew(mouseCursorAnim)) return false;
-	if (! loadAnim(mouseCursorAnim, fp)) return false;
+	if (!checkNew(mouseCursorAnim))
+		return false;
+	if (!loadAnim(mouseCursorAnim, fp))
+		return false;
 	mouseCursorFrameNum = fp->readUint16BE();
 
 	loadedFunction *rFunc;
-	loadedFunction * * buildList = &allRunningFunctions;
+	loadedFunction **buildList = &allRunningFunctions;
 
 	int countFunctions = fp->readUint16BE();
-	while (countFunctions --) {
+	while (countFunctions--) {
 		rFunc = loadFunction(fp);
 		rFunc->next = NULL;
-		(* buildList) = rFunc;
+		(*buildList) = rFunc;
 		buildList = &(rFunc->next);
 	}
 
-	for (a = 0; a < numGlobals; a++) {
+	for (int a = 0; a < numGlobals; a++) {
 		unlinkVar(globalVars[a]);
 		loadVariable(&globalVars[a], fp);
 	}
 
 	loadPeople(fp);
 
-	if (fgetc(fp)) {
-		if (! setFloor(fp->readUint16BE())) return false;
-	} else setFloorNull();
+	if (fp->readByte()) {
+		if (!setFloor(fp->readUint16BE()))
+			return false;
+	} else
+		setFloorNull();
 
-	if (fgetc(fp)) {
-		if (! setZBuffer(fp->readUint16BE())) return false;
+	if (fp->readByte()) {
+		if (!setZBuffer(fp->readUint16BE()))
+			return false;
 	}
 
-	if (fgetc(fp)) {
-		if (! loadLightMap(fp->readUint16BE())) return false;
+	if (fp->readByte()) {
+		if (!loadLightMap(fp->readUint16BE()))
+			return false;
 	}
 
 	if (ssgVersion >= VERSION(1, 4)) {
-		lightMapMode = fgetc(fp) % 3;
+		lightMapMode = fp->readByte() % 3;
 	}
 
-	speechMode = fgetc(fp);
-	fadeMode = fgetc(fp);
+	speechMode = fp->readByte();
+	fadeMode = fp->readByte();
 	loadSpeech(speech, fp);
 	loadStatusBars(fp);
 	loadSounds(fp);
@@ -628,7 +671,7 @@ bool loadGame(char *fname) {
 	if (ssgVersion >= VERSION(1, 6)) {
 		if (ssgVersion < VERSION(2, 0)) {
 			// aaLoad
-			fgetc(fp);
+			fp->readByte();
 			getFloat(fp);
 			getFloat(fp);
 		}
@@ -638,20 +681,21 @@ bool loadGame(char *fname) {
 
 	if (ssgVersion >= VERSION(1, 3)) {
 		currentBlankColour = fp->readUint16BE();
-		currentBurnR = fgetc(fp);
-		currentBurnG = fgetc(fp);
-		currentBurnB = fgetc(fp);
+		currentBurnR = fp->readByte();
+		currentBurnG = fp->readByte();
+		currentBurnB = fp->readByte();
 
 		// Read parallax layers
-		while (fgetc(fp)) {
+		while (fp->readByte()) {
 			int im = fp->readUint16BE();
 			int fx = fp->readUint16BE();
 			int fy = fp->readUint16BE();
 
-			if (! loadParallax(im, fx, fy)) return false;
+			if (!loadParallax(im, fx, fy))
+				return false;
 		}
 
-		int selectedLanguage = fgetc(fp);
+		int selectedLanguage = fp->readByte();
 		if (selectedLanguage != languageNum) {
 			// Load the saved language!
 			languageNum = selectedLanguage;
@@ -661,17 +705,17 @@ bool loadGame(char *fname) {
 
 	nosnapshot();
 	if (ssgVersion >= VERSION(1, 4)) {
-		if (fgetc(fp)) {
-			if (! restoreSnapshot(fp)) return false;
+		if (fp->readByte()) {
+			if (!restoreSnapshot(fp))
+				return false;
 		}
 	}
 
-	fclose(fp);
+	delete fp;
 
 	cameraX = camerX;
 	cameraY = camerY;
 	cameraZoom = camerZ;
-#endif
 
 	clearStackLib();
 	return true;
diff --git a/engines/sludge/talk.cpp b/engines/sludge/talk.cpp
index 7663d39..ce9bd0b 100644
--- a/engines/sludge/talk.cpp
+++ b/engines/sludge/talk.cpp
@@ -213,7 +213,6 @@ void viewSpeech() {
 }
 
 void saveSpeech(speechStruct *sS, Common::WriteStream *stream) {
-#if 0
 	speechLine *viewLine = sS->allSpeech;
 
 	stream->writeByte(sS->talkCol.originalRed);
@@ -242,11 +241,9 @@ void saveSpeech(speechStruct *sS, Common::WriteStream *stream) {
 		viewLine = viewLine->next;
 	}
 	stream->writeByte(0);
-#endif
 }
 
 bool loadSpeech(speechStruct *sS, Common::SeekableReadStream *stream) {
-#if 0
 	speech->currentTalker = NULL;
 	killAllSpeech();
 	byte r = stream->readByte();
@@ -281,7 +278,6 @@ bool loadSpeech(speechStruct *sS, Common::SeekableReadStream *stream) {
 		(* viewLine) = newOne;
 		viewLine = &(newOne->next);
 	}
-#endif
 	return true;
 }
 
diff --git a/engines/sludge/thumbnail.cpp b/engines/sludge/thumbnail.cpp
index 8e238f7..b628f0b 100644
--- a/engines/sludge/thumbnail.cpp
+++ b/engines/sludge/thumbnail.cpp
@@ -132,8 +132,8 @@ bool saveThumbnail(Common::WriteStream *stream) {
 		unfreeze(true);
 	}
 	fputc('!', fp);
-	return true;
 #endif
+	return true;
 }
 
 void showThumbnail(char *filename, int atX, int atY) {
@@ -252,12 +252,15 @@ void showThumbnail(char *filename, int atX, int atY) {
 }
 
 bool skipThumbnail(Common::SeekableReadStream *stream) {
+#if 0
 	thumbWidth = stream->readUint32LE();
 	thumbHeight = stream->readUint32LE();
 	uint32 skippy = thumbWidth;
 	skippy *= thumbHeight << 1;
 	stream->seek(skippy, 1);
 	return (stream->readByte() == '!');
+#endif
+	return true;
 }
 
 } // End of namespace Sludge


Commit: fe773c1bebf353bdba2a4a279b19a85ea4d7be5a
    https://github.com/scummvm/scummvm/commit/fe773c1bebf353bdba2a4a279b19a85ea4d7be5a
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: replace char* by Common::String for error messages

Changed paths:
    engines/sludge/builtin.cpp
    engines/sludge/newfatal.cpp
    engines/sludge/newfatal.h
    engines/sludge/variable.cpp


diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 21818b9..1f19fc3 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -2569,8 +2569,7 @@ builtIn(setThumbnailSize) {
 		return BR_ERROR;
 	trimStack(fun->stack);
 	if (thumbWidth < 0 || thumbHeight < 0 || thumbWidth > winWidth || thumbHeight > winHeight) {
-		char buff[50];
-		sprintf(buff, "%d x %d", thumbWidth, thumbHeight);
+		Common::String buff = thumbWidth + " x " + thumbHeight;
 		fatal("Invalid thumbnail size", buff);
 		return BR_ERROR;
 	}
diff --git a/engines/sludge/newfatal.cpp b/engines/sludge/newfatal.cpp
index 8bafd1f..bbb0f8c 100644
--- a/engines/sludge/newfatal.cpp
+++ b/engines/sludge/newfatal.cpp
@@ -19,12 +19,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#if 0
-#include <SDL/SDL.h>
-
-#include <string.h>
-#include <stdlib.h>
-#endif
 
 #include "common/debug.h"
 
@@ -41,8 +35,8 @@ namespace Sludge {
 
 const char emergencyMemoryMessage[] = "Out of memory displaying error message!";
 
-static char *fatalMessage = NULL;
-static char *fatalInfo = joinStrings("Initialisation error! Something went wrong before we even got started!", "");
+static Common::String fatalMessage;
+static Common::String fatalInfo = "Initialisation error! Something went wrong before we even got started!";
 
 extern int numResourceNames /* = 0*/;
 extern char * *allResourceNames /*= NULL*/;
@@ -60,20 +54,20 @@ const char *resourceNameFromNum(int i) {
 }
 
 bool hasFatal() {
-	if (fatalMessage)
+	if (!fatalMessage.empty())
 		return true;
 	return false;
 }
 
 void displayFatal() {
-	if (fatalMessage) {
+	if (!fatalMessage.empty()) {
 #if 0
 		msgBox("SLUDGE v" TEXT_VERSION " fatal error!", fatalMessage);
 #endif
 	}
 }
 
-void warning(const char *l) {
+void warning(const Common::String &l) {
 #if 0
 	setGraphicsWindow(false);
 	msgBox("SLUDGE v" TEXT_VERSION " non-fatal indigestion report", l);
@@ -81,40 +75,12 @@ void warning(const char *l) {
 }
 
 void registerWindowForFatal() {
-	delete[] fatalInfo;
-	fatalInfo =
-			joinStrings("There's an error with this SLUDGE game! If you're designing this game, please turn on verbose error messages in the project manager and recompile. If not, please contact the author saying where and how this problem occured.", "");
+	fatalInfo = "There's an error with this SLUDGE game! If you're designing this game, please turn on verbose error messages in the project manager and recompile. If not, please contact the author saying where and how this problem occured.";
 }
 
-#if 0
-extern SDL_Event quit_event;
-#endif
-
-int inFatal(const char *str) {
-	error(str);
-	delete []str;
-#if 0
-	FILE *fatFile = fopen("fatal.txt", "wt");
-	if (fatFile) {
-		fprintf(fatFile, "FATAL:\n%s\n", str);
-		fclose(fatFile);
-	}
-
-	fatalMessage = copyString(str);
-	if (fatalMessage == NULL)
-		fatalMessage = copyString("Out of memory");
-
+int inFatal(const Common::String &str) {
 	killSoundStuff();
-
-#if defined(HAVE_GLES2)
-	EGL_Close();
-#endif
-
-	SDL_Quit();
-
-	atexit(displayFatal);
-	exit(1);
-#endif
+	error(str.c_str());
 	return true;
 }
 
@@ -126,45 +92,30 @@ int checkNew(const void *mem) {
 	return 1;
 }
 
-void setFatalInfo(const char *userFunc, const char *BIF) {
-	delete[] fatalInfo;
-	fatalInfo = new char[strlen(userFunc) + strlen(BIF) + 38];
-	if (fatalInfo)
-		sprintf(fatalInfo, "Currently in this sub: %s\nCalling: %s", userFunc, BIF);
-	debug(kSludgeDebugFatal, "%s", fatalInfo);
+void setFatalInfo(const Common::String &userFunc, const Common::String &BIF) {
+	fatalInfo = "Currently in this sub: " + userFunc + "\nCalling: " + BIF;
+	debug(kSludgeDebugFatal, "%s", fatalInfo.c_str());
 }
 
 void setResourceForFatal(int n) {
 	resourceForFatal = n;
 }
 
-int fatal(const char *str1) {
+int fatal(const Common::String &str1) {
 	if (numResourceNames && resourceForFatal != -1) {
-		const char *r = resourceNameFromNum(resourceForFatal);
-		char *newStr = new char[strlen(str1) + strlen(r) + strlen(fatalInfo) + 14];
-		if (checkNew(newStr)) {
-			sprintf(newStr, "%s\nResource: %s\n\n%s", fatalInfo, r, str1);
-			inFatal(newStr);
-		} else
-			fatal(emergencyMemoryMessage);
+		Common::String r = resourceNameFromNum(resourceForFatal);
+		Common::String newStr = fatalInfo + "\nResource: " + r + "\n\n" + str1;
+		inFatal(newStr);
 	} else {
-		char *newStr = new char[strlen(str1) + strlen(fatalInfo) + 3];
-		if (checkNew(newStr)) {
-			sprintf(newStr, "%s\n\n%s", fatalInfo, str1);
-			inFatal(newStr);
-		} else
-			fatal(emergencyMemoryMessage);
+		Common::String newStr = fatalInfo + "\n\n" + str1;
+		inFatal(newStr);
 	}
 	return 0;
 }
 
-int fatal(const char *str1, const char *str2) {
-	char *newStr = new char[strlen(str1) + strlen(str2) + 2];
-	if (checkNew(newStr)) {
-		sprintf(newStr, "%s %s", str1, str2);
-		fatal(newStr);
-	} else
-		fatal(emergencyMemoryMessage);
+int fatal(const Common::String &str1, const Common::String &str2) {
+	Common::String newStr = str1 + " " + str2;
+	fatal(newStr);
 	return 0;
 }
 
diff --git a/engines/sludge/newfatal.h b/engines/sludge/newfatal.h
index 089b053..bb22227 100644
--- a/engines/sludge/newfatal.h
+++ b/engines/sludge/newfatal.h
@@ -22,21 +22,23 @@
 #ifndef SLUDGE_NEWFATAL_H
 #define SLUDGE_NEWFATAL_H
 
+#include "common/str.h"
+
 #include "sludge/errors.h"
 
 namespace Sludge {
 
 bool hasFatal();
 
-int fatal(const char *str);
-int fatal(const char *str1, const char *str2);
+int fatal(const Common::String &str);
+int fatal(const Common::String &str1, const Common::String &str2);
 int checkNew(const void *mem);
 void displayFatal();
 void registerWindowForFatal();
-void setFatalInfo(const char *userFunc, const char *BIF);
-void warning(const char *l);
+void setFatalInfo(const Common::String &userFunc, const Common::String &BIF);
+void warning(const Common::String &l);
 void setResourceForFatal(int n);
-char *resourceNameFromNum(int i);
+const char *resourceNameFromNum(int i);
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/variable.cpp b/engines/sludge/variable.cpp
index 13f6608..a9f91d5 100644
--- a/engines/sludge/variable.cpp
+++ b/engines/sludge/variable.cpp
@@ -591,8 +591,10 @@ variableStack *stackFindLast(variableStack *hunt) {
 bool getValueType(int &toHere, variableType vT, const variable &v) {
 	//if (! v) return false;
 	if (v.varType != vT) {
-		char *e1 = joinStrings("Can only perform specified operation on a value which is of type ", typeName[vT]);
-		char *e2 = joinStrings("... value supplied was of type ", typeName[v.varType]);
+		Common::String e1 = "Can only perform specified operation on a value which is of type ";
+		e1 += typeName[vT];
+		Common::String e2 = "... value supplied was of type ";
+		e2 += typeName[v.varType];
 		fatal(e1, e2);
 
 		return false;


Commit: 302c94627930e9965f7607497a01201fff3551e3
    https://github.com/scummvm/scummvm/commit/302c94627930e9965f7607497a01201fff3551e3
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: use U32String to replace sludge utf8 library

Changed paths:
  A engines/sludge/utf8.cpp
  A engines/sludge/utf8.h
  R engines/sludge/CommonCode/utf8.cpp
  R engines/sludge/CommonCode/utf8.h
    engines/sludge/builtin.cpp
    engines/sludge/fonttext.cpp
    engines/sludge/fonttext.h
    engines/sludge/module.mk


diff --git a/engines/sludge/CommonCode/utf8.cpp b/engines/sludge/CommonCode/utf8.cpp
deleted file mode 100644
index 291bef4..0000000
--- a/engines/sludge/CommonCode/utf8.cpp
+++ /dev/null
@@ -1,555 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-/*
-  Basic UTF-8 manipulation routines
-  by Jeff Bezanson
-  placed in the public domain Fall 2005
-
-  This code is designed to provide the utilities you need to manipulate
-  UTF-8 as an internal string encoding. These functions do not perform the
-  error checking normally needed when handling UTF-8 data, so if you happen
-  to be from the Unicode Consortium you will want to flay me alive.
-  I do this because error checking can be performed at the boundaries (I/O),
-  with these routines reserved for higher performance on data known to be
-  valid.
-*/
-
-#include "common/debug.h"
-
-#include "sludge/CommonCode/utf8.h"
-
-static const uint32 offsetsFromUTF8[6] = {
-    0x00000000UL, 0x00003080UL, 0x000E2080UL,
-    0x03C82080UL, 0xFA082080UL, 0x82082080UL
-};
-
-static const char trailingBytesForUTF8[256] = {
-    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
-};
-
-/* returns length of next utf-8 sequence */
-int u8_seqlen(char *s)
-{
-    return trailingBytesForUTF8[(unsigned int)(unsigned char)s[0]] + 1;
-}
-
-/* conversions without error checking
-   only works for valid UTF-8, i.e. no 5- or 6-byte sequences
-   srcsz = source size in bytes, or -1 if 0-terminated
-   sz = dest size in # of wide characters
-
-   returns # characters converted
-   dest will always be L'\0'-terminated, even if there isn't enough room
-   for all the characters.
-   if sz = srcsz+1 (i.e. 4*srcsz+4 bytes), there will always be enough space.
-*/
-int u8_toucs(uint32 *dest, int sz, char *src, int srcsz)
-{
-    uint32 ch;
-    char *src_end = src + srcsz;
-    int nb;
-    int i=0;
-
-    while (i < sz-1) {
-        nb = trailingBytesForUTF8[(unsigned char)*src];
-        if (srcsz == -1) {
-            if (*src == 0)
-                goto done_toucs;
-        }
-        else {
-            if (src + nb >= src_end)
-                goto done_toucs;
-        }
-        ch = 0;
-        switch (nb) {
-            /* these fall through deliberately */
-        case 3: ch += (unsigned char)*src++; ch <<= 6;
-        case 2: ch += (unsigned char)*src++; ch <<= 6;
-        case 1: ch += (unsigned char)*src++; ch <<= 6;
-        case 0: ch += (unsigned char)*src++;
-        }
-        ch -= offsetsFromUTF8[nb];
-        dest[i++] = ch;
-    }
- done_toucs:
-    dest[i] = 0;
-    return i;
-}
-
-/* srcsz = number of source characters, or -1 if 0-terminated
-   sz = size of dest buffer in bytes
-
-   returns # characters converted
-   dest will only be '\0'-terminated if there is enough space. this is
-   for consistency; imagine there are 2 bytes of space left, but the next
-   character requires 3 bytes. in this case we could NUL-terminate, but in
-   general we can't when there's insufficient space. therefore this function
-   only NUL-terminates if all the characters fit, and there's space for
-   the NUL as well.
-   the destination string will never be bigger than the source string.
-*/
-int u8_toutf8(char *dest, int sz, uint32 *src, int srcsz)
-{
-    uint32 ch;
-    int i = 0;
-    char *dest_end = dest + sz;
-
-    while (srcsz<0 ? src[i]!=0 : i < srcsz) {
-        ch = src[i];
-        if (ch < 0x80) {
-            if (dest >= dest_end)
-                return i;
-            *dest++ = (char)ch;
-        }
-        else if (ch < 0x800) {
-            if (dest >= dest_end-1)
-                return i;
-            *dest++ = (ch>>6) | 0xC0;
-            *dest++ = (ch & 0x3F) | 0x80;
-        }
-        else if (ch < 0x10000) {
-            if (dest >= dest_end-2)
-                return i;
-            *dest++ = (ch>>12) | 0xE0;
-            *dest++ = ((ch>>6) & 0x3F) | 0x80;
-            *dest++ = (ch & 0x3F) | 0x80;
-        }
-        else if (ch < 0x110000) {
-            if (dest >= dest_end-3)
-                return i;
-            *dest++ = (ch>>18) | 0xF0;
-            *dest++ = ((ch>>12) & 0x3F) | 0x80;
-            *dest++ = ((ch>>6) & 0x3F) | 0x80;
-            *dest++ = (ch & 0x3F) | 0x80;
-        }
-        i++;
-    }
-    if (dest < dest_end)
-        *dest = '\0';
-    return i;
-}
-
-int u8_wc_toutf8(char *dest, uint32 ch)
-{
-    if (ch < 0x80) {
-        dest[0] = (char)ch;
-        return 1;
-    }
-    if (ch < 0x800) {
-        dest[0] = (ch>>6) | 0xC0;
-        dest[1] = (ch & 0x3F) | 0x80;
-        return 2;
-    }
-    if (ch < 0x10000) {
-        dest[0] = (ch>>12) | 0xE0;
-        dest[1] = ((ch>>6) & 0x3F) | 0x80;
-        dest[2] = (ch & 0x3F) | 0x80;
-        return 3;
-    }
-    if (ch < 0x110000) {
-        dest[0] = (ch>>18) | 0xF0;
-        dest[1] = ((ch>>12) & 0x3F) | 0x80;
-        dest[2] = ((ch>>6) & 0x3F) | 0x80;
-        dest[3] = (ch & 0x3F) | 0x80;
-        return 4;
-    }
-    return 0;
-}
-
-/* charnum => byte offset */
-int u8_offset(char *str, int charnum)
-{
-    int offs=0;
-
-    while (charnum > 0 && str[offs]) {
-        (void)(isutf(str[++offs]) || isutf(str[++offs]) ||
-               isutf(str[++offs]) || ++offs);
-        charnum--;
-    }
-    return offs;
-}
-
-/* byte offset => charnum */
-int u8_charnum(char *s, int offset)
-{
-    int charnum = 0, offs=0;
-
-    while (offs < offset && s[offs]) {
-        (void)(isutf(s[++offs]) || isutf(s[++offs]) ||
-               isutf(s[++offs]) || ++offs);
-        charnum++;
-    }
-    return charnum;
-}
-
-/* number of characters */
-int u8_strlen(char *s)
-{
-    int count = 0;
-    int i = 0;
-
-    while (u8_nextchar(s, &i) != 0)
-        count++;
-
-    return count;
-}
-
-/* reads the next utf-8 sequence out of a string, updating an index */
-uint32 u8_nextchar(const char *s, int *i)
-{
-    uint32 ch = 0;
-    int sz = 0;
-
-    do {
-        ch <<= 6;
-        ch += (unsigned char)s[(*i)++];
-        sz++;
-    } while (s[*i] && !isutf(s[*i]));
-    ch -= offsetsFromUTF8[sz-1];
-
-    return ch;
-}
-
-void u8_inc(char *s, int *i)
-{
-    (void)(isutf(s[++(*i)]) || isutf(s[++(*i)]) ||
-           isutf(s[++(*i)]) || ++(*i));
-}
-
-void u8_dec(char *s, int *i)
-{
-    (void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) ||
-           isutf(s[--(*i)]) || --(*i));
-}
-
-int octal_digit(char c)
-{
-    return (c >= '0' && c <= '7');
-}
-
-int hex_digit(char c)
-{
-    return ((c >= '0' && c <= '9') ||
-            (c >= 'A' && c <= 'F') ||
-            (c >= 'a' && c <= 'f'));
-}
-
-/* assumes that src points to the character after a backslash
-   returns number of input characters processed */
-int u8_read_escape_sequence(char *str, uint32 *dest)
-{
-    uint32 ch;
-    char digs[9]="\0\0\0\0\0\0\0\0";
-    int dno=0, i=1;
-
-    ch = (uint32)str[0];    /* take literal character */
-    if (str[0] == 'n')
-        ch = L'\n';
-    else if (str[0] == 't')
-        ch = L'\t';
-    else if (str[0] == 'r')
-        ch = L'\r';
-    else if (str[0] == 'b')
-        ch = L'\b';
-    else if (str[0] == 'f')
-        ch = L'\f';
-    else if (str[0] == 'v')
-        ch = L'\v';
-    else if (str[0] == 'a')
-        ch = L'\a';
-    else if (octal_digit(str[0])) {
-        i = 0;
-        do {
-            digs[dno++] = str[i++];
-        } while (octal_digit(str[i]) && dno < 3);
-        ch = strtol(digs, NULL, 8);
-    }
-    else if (str[0] == 'x') {
-        while (hex_digit(str[i]) && dno < 2) {
-            digs[dno++] = str[i++];
-        }
-        if (dno > 0)
-            ch = strtol(digs, NULL, 16);
-    }
-    else if (str[0] == 'u') {
-        while (hex_digit(str[i]) && dno < 4) {
-            digs[dno++] = str[i++];
-        }
-        if (dno > 0)
-            ch = strtol(digs, NULL, 16);
-    }
-    else if (str[0] == 'U') {
-        while (hex_digit(str[i]) && dno < 8) {
-            digs[dno++] = str[i++];
-        }
-        if (dno > 0)
-            ch = strtol(digs, NULL, 16);
-    }
-    *dest = ch;
-
-    return i;
-}
-
-/* convert a string with literal \uxxxx or \Uxxxxxxxx characters to UTF-8
-   example: u8_unescape(mybuf, 256, "hello\\u220e")
-   note the double backslash is needed if called on a C string literal */
-int u8_unescape(char *buf, int sz, char *src)
-{
-    int c=0, amt;
-    uint32 ch;
-    char temp[4];
-
-    while (*src && c < sz) {
-        if (*src == '\\') {
-            src++;
-            amt = u8_read_escape_sequence(src, &ch);
-        }
-        else {
-            ch = (uint32)*src;
-            amt = 1;
-        }
-        src += amt;
-        amt = u8_wc_toutf8(temp, ch);
-        if (amt > sz-c)
-            break;
-        memcpy(&buf[c], temp, amt);
-        c += amt;
-    }
-    if (c < sz)
-        buf[c] = '\0';
-    return c;
-}
-
-int u8_escape_wchar(char *buf, int sz, uint32 ch)
-{
-    if (ch == L'\n')
-        return snprintf(buf, sz, "\\n");
-    else if (ch == L'\t')
-        return snprintf(buf, sz, "\\t");
-    else if (ch == L'\r')
-        return snprintf(buf, sz, "\\r");
-    else if (ch == L'\b')
-        return snprintf(buf, sz, "\\b");
-    else if (ch == L'\f')
-        return snprintf(buf, sz, "\\f");
-    else if (ch == L'\v')
-        return snprintf(buf, sz, "\\v");
-    else if (ch == L'\a')
-        return snprintf(buf, sz, "\\a");
-    else if (ch == L'\\')
-        return snprintf(buf, sz, "\\\\");
-    else if (ch < 32 || ch == 0x7f)
-        return snprintf(buf, sz, "\\x%hhX", (unsigned char)ch);
-    else if (ch > 0xFFFF)
-        return snprintf(buf, sz, "\\U%.8X", (uint32)ch);
-    else if (ch >= 0x80 && ch <= 0xFFFF)
-        return snprintf(buf, sz, "\\u%.4hX", (unsigned short)ch);
-
-    return snprintf(buf, sz, "%c", (char)ch);
-}
-
-int u8_escape(char *buf, int sz, char *src, int escape_quotes)
-{
-    int c=0, i=0, amt;
-
-    while (src[i] && c < sz) {
-        if (escape_quotes && src[i] == '"') {
-            amt = snprintf(buf, sz - c, "\\\"");
-            i++;
-        }
-        else {
-            amt = u8_escape_wchar(buf, sz - c, u8_nextchar(src, &i));
-        }
-        c += amt;
-        buf += amt;
-    }
-    if (c < sz)
-        *buf = '\0';
-    return c;
-}
-
-char *u8_strchr(char *s, uint32 ch, int *charn)
-{
-    int i = 0, lasti=0;
-    uint32 c;
-
-    *charn = 0;
-    while (s[i]) {
-        c = u8_nextchar(s, &i);
-        if (c == ch) {
-            return &s[lasti];
-        }
-        lasti = i;
-        (*charn)++;
-    }
-    return NULL;
-}
-
-char *u8_memchr(char *s, uint32 ch, size_t sz, int *charn)
-{
-    int i = 0, lasti=0;
-    uint32 c;
-    int csz;
-
-    *charn = 0;
-    while (i < sz) {
-        c = csz = 0;
-        do {
-            c <<= 6;
-            c += (unsigned char)s[i++];
-            csz++;
-        } while (i < sz && !isutf(s[i]));
-        c -= offsetsFromUTF8[csz-1];
-
-        if (c == ch) {
-            return &s[lasti];
-        }
-        lasti = i;
-        (*charn)++;
-    }
-    return NULL;
-}
-
-int u8_is_locale_utf8(char *locale)
-{
-    /* this code based on libutf8 */
-    const char* cp = locale;
-
-    for (; *cp != '\0' && *cp != '@' && *cp != '+' && *cp != ','; cp++) {
-        if (*cp == '.') {
-            const char* encoding = ++cp;
-            for (; *cp != '\0' && *cp != '@' && *cp != '+' && *cp != ','; cp++)
-                ;
-            if ((cp-encoding == 5 && !strncmp(encoding, "UTF-8", 5))
-                || (cp-encoding == 4 && !strncmp(encoding, "utf8", 4)))
-                return 1; /* it's UTF-8 */
-            break;
-        }
-    }
-    return 0;
-}
-
-int u8_vprintf(char *fmt, va_list ap)
-{
-    int cnt, sz=0;
-    char *buf;
-    uint32 *wcs;
-
-    sz = 512;
-    buf = (char*)alloca(sz);
- try_print:
-    cnt = vsnprintf(buf, sz, fmt, ap);
-    if (cnt >= sz) {
-        buf = (char*)alloca(cnt - sz + 1);
-        sz = cnt + 1;
-        goto try_print;
-    }
-    wcs = (uint32*)alloca((cnt+1) * sizeof(uint32));
-    cnt = u8_toucs(wcs, cnt+1, buf, cnt);
-    debug("%ls", (wchar_t*)wcs);
-    return cnt;
-}
-
-int u8_printf(char *fmt, ...)
-{
-    int cnt;
-    va_list args;
-
-    va_start(args, fmt);
-
-    cnt = u8_vprintf(fmt, args);
-
-    va_end(args);
-    return cnt;
-}
-
-
-// This function checks a string to see if it's valid UTF-8
-// It returns true if the string is valid.
-//
-// based on the valid_utf8 routine from the PCRE library by Philip Hazel
-
-int u8_isvalid(const char *str)
-{
-    const unsigned char *p;
-    unsigned char c;
-    int ab;
-	
-    for (p = (unsigned char*)str; *p; p++) {
-        c = *p;
-        if (c < 128)
-            continue;
-        if ((c & 0xc0) != 0xc0)
-            return 0;
-        ab = trailingBytesForUTF8[c];
-		
-        p++;
-        /* Check top bits in the second byte */
-        if ((*p & 0xc0) != 0x80)
-            return 0;
-		
-        /* Check for overlong sequences for each different length */
-        switch (ab) {
-				/* Check for xx00 000x */
-			case 1:
-				if ((c & 0x3e) == 0) return 0;
-				continue;   /* We know there aren't any more bytes to check */
-				
-				/* Check for 1110 0000, xx0x xxxx */
-			case 2:
-				if (c == 0xe0 && (*p & 0x20) == 0) return 0;
-				break;
-				
-				/* Check for 1111 0000, xx00 xxxx */
-			case 3:
-				if (c == 0xf0 && (*p & 0x30) == 0) return 0;
-				break;
-				
-				/* Check for 1111 1000, xx00 0xxx */
-			case 4:
-				if (c == 0xf8 && (*p & 0x38) == 0) return 0;
-				break;
-				
-				/* Check for leading 0xfe or 0xff,
-				 and then for 1111 1100, xx00 00xx */
-			case 5:
-				if (c == 0xfe || c == 0xff ||
-					(c == 0xfc && (*p & 0x3c) == 0)) return 0;
-				break;
-        }
-		
-        /* Check for valid bytes after the 2nd, if any; all must start 10 */
-        while (--ab > 0) {
-            if ((*(++p) & 0xc0) != 0x80) return 0;
-        }
-    }
-	
-    return 1;
-}
-
diff --git a/engines/sludge/CommonCode/utf8.h b/engines/sludge/CommonCode/utf8.h
deleted file mode 100644
index c9af92e..0000000
--- a/engines/sludge/CommonCode/utf8.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-
-#include "common/system.h"
-
-/* is c the start of a utf8 sequence? */
-#define isutf(c) (((c)&0xC0)!=0x80)
-
-/* convert UTF-8 data to wide character */
-int u8_toucs(uint32 *dest, int sz, char *src, int srcsz);
-
-/* the opposite conversion */
-int u8_toutf8(char *dest, int sz, uint32 *src, int srcsz);
-
-/* single character to UTF-8 */
-int u8_wc_toutf8(char *dest, uint32 ch);
-
-/* character number to byte offset */
-int u8_offset(char *str, int charnum);
-
-/* byte offset to character number */
-int u8_charnum(char *s, int offset);
-
-/* return next character, updating an index variable */
-uint32 u8_nextchar(const char *s, int *i);
-
-/* move to next character */
-void u8_inc(char *s, int *i);
-
-/* move to previous character */
-void u8_dec(char *s, int *i);
-
-/* returns length of next utf-8 sequence */
-int u8_seqlen(char *s);
-
-/* assuming src points to the character after a backslash, read an
-   escape sequence, storing the result in dest and returning the number of
-   input characters processed */
-int u8_read_escape_sequence(char *src, uint32 *dest);
-
-/* given a wide character, convert it to an ASCII escape sequence stored in
-   buf, where buf is "sz" bytes. returns the number of characters output. */
-int u8_escape_wchar(char *buf, int sz, uint32 ch);
-
-/* convert a string "src" containing escape sequences to UTF-8 */
-int u8_unescape(char *buf, int sz, char *src);
-
-/* convert UTF-8 "src" to ASCII with escape sequences.
-   if escape_quotes is nonzero, quote characters will be preceded by
-   backslashes as well. */
-int u8_escape(char *buf, int sz, char *src, int escape_quotes);
-
-/* utility predicates used by the above */
-int octal_digit(char c);
-int hex_digit(char c);
-
-/* return a pointer to the first occurrence of ch in s, or NULL if not
-   found. character index of found character returned in *charn. */
-char *u8_strchr(char *s, uint32 ch, int *charn);
-
-/* same as the above, but searches a buffer of a given size instead of
-   a NUL-terminated string. */
-char *u8_memchr(char *s, uint32 ch, size_t sz, int *charn);
-
-/* count the number of characters in a UTF-8 string */
-int u8_strlen(char *s);
-
-int u8_is_locale_utf8(char *locale);
-
-/* printf where the format string and arguments may be in UTF-8.
-   you can avoid this function and just use ordinary printf() if the current
-   locale is UTF-8. */
-int u8_vprintf(char *fmt, va_list ap);
-int u8_printf(char *fmt, ...);
-
-
-int u8_isvalid(const char *input);
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 1f19fc3..fc92161 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -50,7 +50,7 @@
 #include "sludge/thumbnail.h"
 #include "sludge/graphics.h"
 #include "sludge/sludge.h"
-#include "sludge/CommonCode/utf8.h"
+#include "sludge/utf8.h"
 
 namespace Sludge {
 
@@ -558,9 +558,12 @@ builtIn(substring) {
 	wholeString = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
 
-	if (u8_strlen(wholeString) < start + length) {
-		length = u8_strlen(wholeString) - start;
-		if (u8_strlen(wholeString) < start) {
+	UTF8Converter convert(wholeString);
+	Common::U32String str32 = convert.getU32String();
+
+	if (str32.size() < start + length) {
+		length = str32.size() - start;
+		if (str32.size() < start) {
 			start = 0;
 		}
 	}
@@ -568,8 +571,8 @@ builtIn(substring) {
 		length = 0;
 	}
 
-	int startoffset = u8_offset(wholeString, start);
-	int endoffset = u8_offset(wholeString, start + length);
+	int startoffset = convert.getOriginOffset(start);
+	int endoffset = convert.getOriginOffset(start + length);
 
 	newString = new char[endoffset - startoffset + 1];
 	if (!checkNew(newString)) {
@@ -580,7 +583,7 @@ builtIn(substring) {
 	newString[endoffset - startoffset] = 0;
 
 	makeTextVar(fun->reg, newString);
-	delete newString;
+	delete []newString;
 	return BR_CONTINUE;
 }
 
diff --git a/engines/sludge/fonttext.cpp b/engines/sludge/fonttext.cpp
index c3c877c..a35c51b 100644
--- a/engines/sludge/fonttext.cpp
+++ b/engines/sludge/fonttext.cpp
@@ -28,17 +28,17 @@
 #include "sludge/newfatal.h"
 #include "sludge/moreio.h"
 #include "sludge/platform-dependent.h"
-#include "sludge/CommonCode/utf8.h"
+#include "sludge/utf8.h"
 
 namespace Sludge {
 
 spriteBank theFont;
 int fontHeight = 0, numFontColours, loadedFontNum;
-char *fontOrderString = NULL;
+Common::U32String fontOrderString;
 short fontSpace = -1;
 
 uint32 *fontTable = NULL;
-unsigned int fontTableSize = 0;
+uint fontTableSize = 0;
 
 #define fontInTable(x) ((x<fontTableSize) ? fontTable[(uint32) x] : 0)
 
@@ -50,30 +50,33 @@ bool isInFont(char *theText) {
 	if (!theText[0])
 		return 0;
 
+	Common::U32String str32 = UTF8Converter::convertUtf8ToUtf32(theText);
+
 	// We don't want to compare strings. Only single characters allowed!
-	if (u8_strlen(theText) > 1)
+	if (str32.size() > 1)
 		return false;
 
-	int i = 0;
-	uint32 c = u8_nextchar(theText, &i);
+	uint32 c = str32[0];
 
-	return u8_strchr(fontOrderString, c, &i);
+	// check if font order contains the utf8 char
+	return fontOrderString.contains(c);
 }
 
 int stringLength(char *theText) {
-	return u8_strlen(theText);
+	Common::U32String str32 = UTF8Converter::convertUtf8ToUtf32(theText);
+	return str32.size();
 }
 
 int stringWidth(char *theText) {
-	int a = 0;
-	uint32 c;
 	int xOff = 0;
 
 	if (!fontTableSize)
 		return 0;
 
-	while (theText[a]) {
-		c = u8_nextchar(theText, &a);
+	Common::U32String str32 = UTF8Converter::convertUtf8ToUtf32(theText);
+
+	for (uint i = 0; i < str32.size(); ++i) {
+		uint32 c = str32[i];
 		xOff += theFont.sprites[fontInTable(c)].surface.w + fontSpace;
 	}
 
@@ -81,51 +84,46 @@ int stringWidth(char *theText) {
 }
 
 void pasteString(char *theText, int xOff, int y, spritePalette &thePal) {
-	sprite *mySprite;
-	int a = 0;
-	uint32 c;
-
 	if (!fontTableSize)
 		return;
 
 	xOff += (int)((float)(fontSpace >> 1) / cameraZoom);
-	while (theText[a]) {
-		c = u8_nextchar(theText, &a);
-		mySprite = &theFont.sprites[fontInTable(c)];
+
+	Common::U32String str32 = UTF8Converter::convertUtf8ToUtf32(theText);
+
+	for (uint32 i = 0; i < str32.size(); ++i) {
+		uint32 c = str32[i];
+		sprite *mySprite = &theFont.sprites[fontInTable(c)];
 		fontSprite(xOff, y, *mySprite, thePal);
 		xOff += (int)((double)(mySprite->surface.w + fontSpace) / cameraZoom);
 	}
 }
 
 void pasteStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal) {
-	sprite *mySprite;
-	int a = 0;
-	uint32 c;
-
 	if (!fontTableSize)
 		return;
 
+	Common::U32String str32 = UTF8Converter::convertUtf8ToUtf32(theText);
+
 	xOff += fontSpace >> 1;
-	while (theText[a]) {
-		c = u8_nextchar(theText, &a);
-		mySprite = &theFont.sprites[fontInTable(c)];
+	for (uint32 i = 0; i < str32.size(); ++i) {
+		uint32 c = str32[i];
+		sprite *mySprite = &theFont.sprites[fontInTable(c)];
 		pasteSpriteToBackDrop(xOff, y, *mySprite, thePal);
 		xOff += mySprite->surface.w + fontSpace;
 	}
 }
 
 void burnStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal) {
-	sprite *mySprite;
-	int a = 0;
-	uint32 c;
-
 	if (!fontTableSize)
 		return;
 
+	Common::U32String str32 = UTF8Converter::convertUtf8ToUtf32(theText);
+
 	xOff += fontSpace >> 1;
-	while (theText[a]) {
-		c = u8_nextchar(theText, &a);
-		mySprite = &theFont.sprites[fontInTable(c)];
+	for (uint i = 0; i < str32.size(); ++i) {
+		uint32 c = str32[i];
+		sprite *mySprite = &theFont.sprites[fontInTable(c)];
 		burnSpriteToBackDrop(xOff, y, *mySprite, thePal);
 		xOff += mySprite->surface.w + fontSpace;
 	}
@@ -165,38 +163,35 @@ void setFontColour(spritePalette &sP, byte r, byte g, byte b) {
 }
 
 bool loadFont(int filenum, const char *charOrder, int h) {
-	int a = 0;
-	uint32 c;
-
-	delete[] fontOrderString;
-	fontOrderString = copyString(charOrder);
+	fontOrderString.clear();
+	fontOrderString = UTF8Converter::convertUtf8ToUtf32(charOrder);
 
 	forgetSpriteBank(theFont);
 
 	loadedFontNum = filenum;
 
+	// get max value among all utf8 chars
 	fontTableSize = 0;
-	while (charOrder[a]) {
-		c = u8_nextchar(charOrder, &a);
+	for (uint32 i = 0; i < fontOrderString.size(); ++i) {
+		uint32 c = fontOrderString[i];
 		if (c > fontTableSize)
 			fontTableSize = c;
 	}
 	fontTableSize++;
 
+	// create an index table from utf8 char to the index
 	delete[] fontTable;
 	fontTable = new uint32[fontTableSize];
 	if (!checkNew(fontTable))
 		return false;
 
-	for (a = 0; a < fontTableSize; a++) {
-		fontTable[a] = 0;
+	for (uint i = 0; i < fontTableSize; i++) {
+		fontTable[i] = 0;
 	}
-	a = 0;
-	int i = 0;
-	while (charOrder[a]) {
-		c = u8_nextchar(charOrder, &a);
+
+	for (uint i = 0; i < fontOrderString.size(); ++i) {
+		uint32 c = fontOrderString[i];
 		fontTable[c] = i;
-		i++;
 	}
 
 	if (!loadSpriteBank(filenum, theFont, true)) {
diff --git a/engines/sludge/fonttext.h b/engines/sludge/fonttext.h
index 92520a0..cabb52d 100644
--- a/engines/sludge/fonttext.h
+++ b/engines/sludge/fonttext.h
@@ -22,6 +22,8 @@
 #ifndef SLUDGE_FONTTEXT_H
 #define SLUDGE_FONTTEXT_H
 
+#include "common/ustr.h"
+
 namespace Sludge {
 
 bool loadFont(int filenum, const char *charOrder, int);
diff --git a/engines/sludge/module.mk b/engines/sludge/module.mk
index f1e4cad..afe1d88 100644
--- a/engines/sludge/module.mk
+++ b/engines/sludge/module.mk
@@ -39,9 +39,9 @@ MODULE_OBJS := \
 	thumbnail.o \
 	timing.o \
 	transition.o \
+	utf8.o \
 	variable.o \
 	zbuffer.o \
-	CommonCode/utf8.o \
 #	shaders.o \
 #	libwebm/mkvparser.o \
 #	libwebm/mkvreader.o \
diff --git a/engines/sludge/utf8.cpp b/engines/sludge/utf8.cpp
new file mode 100644
index 0000000..95f9e91
--- /dev/null
+++ b/engines/sludge/utf8.cpp
@@ -0,0 +1,101 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+/*
+ Basic UTF-8 manipulation routines
+ by Jeff Bezanson
+ placed in the public domain Fall 2005
+
+ This code is designed to provide the utilities you need to manipulate
+ UTF-8 as an internal string encoding. These functions do not perform the
+ error checking normally needed when handling UTF-8 data, so if you happen
+ to be from the Unicode Consortium you will want to flay me alive.
+ I do this because error checking can be performed at the boundaries (I/O),
+ with these routines reserved for higher performance on data known to be
+ valid.
+ */
+
+#include "common/debug.h"
+
+#include "sludge/utf8.h"
+
+namespace Sludge {
+
+const uint32 UTF8Converter::offsetsFromUTF8[6] = {
+		0x00000000UL, 0x00003080UL,
+		0x000E2080UL, 0x03C82080UL,
+		0xFA082080UL, 0x82082080UL };
+
+/* reads the next utf-8 sequence out of a string, updating an index */
+uint32 UTF8Converter::nextchar(const char *s, int *i) {
+	uint32 ch = 0;
+	int sz = 0;
+
+	do {
+		ch <<= 6;
+		ch += (unsigned char)s[(*i)++];
+		sz++;
+	} while (s[*i] && !isutf(s[*i]));
+	ch -= offsetsFromUTF8[sz - 1];
+
+	return ch;
+}
+
+Common::U32String UTF8Converter::convertUtf8ToUtf32(const Common::String &str) {
+	// we assume one character in a Common::String is one byte
+	// but in this case it's actually an UTF-8 string
+	// with up to 4 bytes per character. To work around this,
+	// convert it to an U32String before any further operation
+	Common::U32String u32str;
+	int i = 0;
+	while (i < (int)str.size()) {
+		uint32 chr = nextchar(str.c_str(), &i);
+		u32str += chr;
+	}
+	return u32str;
+}
+
+/* utf32 index => original byte offset */
+int UTF8Converter::getOriginOffset(int origIdx) {
+	int offs = 0;
+
+	while (origIdx > 0 && _str[offs]) {
+		// increment if it's not the start of a utf8 sequence
+		(void)(isutf(_str[++offs]) || isutf(_str[++offs]) || isutf(_str[++offs]) || ++offs);
+		origIdx--;
+	}
+	return offs;
+}
+
+/** Construct a UTF8String with original char array to convert */
+UTF8Converter::UTF8Converter(const char *str) {
+	setUTF8String(str);
+}
+
+/** set a utf8 string to convert */
+void UTF8Converter::setUTF8String(Common::String str) {
+	_str32.clear();
+	_str32 = convertUtf8ToUtf32(str);
+	_str.clear();
+	_str = str;
+}
+
+} // End of namespace Sludge
diff --git a/engines/sludge/utf8.h b/engines/sludge/utf8.h
new file mode 100644
index 0000000..4595a6b
--- /dev/null
+++ b/engines/sludge/utf8.h
@@ -0,0 +1,82 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#ifndef SLUDGE_UTF8_H
+#define SLUDGE_UTF8_H
+
+#include "common/system.h"
+#include "common/ustr.h"
+
+namespace Sludge {
+
+class UTF8Converter {
+private:
+	static const uint32 offsetsFromUTF8[6];
+
+	/**
+	 * we assume one character in a Common::String is one byte
+	 * but in this case it's actually an UTF-8 string
+	 */
+	Common::String _str;
+
+	/**
+	 * wrap a converted U32String
+	 */
+	Common::U32String _str32;
+
+	/** A tool function for string conversion
+	 * return next character, updating an index variable
+	 */
+	static uint32 nextchar(const char *s, int *i);
+
+	/** A tool function for string conversion
+	 * is this byte the start of a utf8 sequence?
+	 */
+	static inline bool isutf(char c) { return (((c)&0xC0)!=0x80); }
+
+public:
+	/** Construct a new empty string. */
+	UTF8Converter() {};
+
+	/** Construct a UTF8String with original char array to convert */
+	UTF8Converter(const char *data);
+
+	/** U32 character index to origin char offset */
+	int getOriginOffset(int origIdx);
+
+	/**
+	 * set a char array to this UTF8String
+	 */
+	void setUTF8String(Common::String str);
+
+	/**
+	 * get converted U32String
+	 */
+	Common::U32String getU32String() { return _str32; };
+
+	/** Convert UTF8 String to UTF32 String
+	 */
+	static Common::U32String convertUtf8ToUtf32(const Common::String &str);
+};
+
+} // End of namespace Sludge
+
+#endif


Commit: 53572c8e587a3207581aedf15507779f8e1cf23e
    https://github.com/scummvm/scummvm/commit/53572c8e587a3207581aedf15507779f8e1cf23e
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: not to build sludge by default

Changed paths:
    engines/sludge/configure.engine


diff --git a/engines/sludge/configure.engine b/engines/sludge/configure.engine
index 7101729..7f1d9e9 100644
--- a/engines/sludge/configure.engine
+++ b/engines/sludge/configure.engine
@@ -1,3 +1,3 @@
 # This file is included from the main "configure" script
 # add_engine [name] [desc] [build-by-default] [subengines] [base games] [deps]
-add_engine sludge "Sludge" yes "" "" "png"
+add_engine sludge "Sludge" no "" "" "png"


Commit: 9560969ea8cf2e6f1d97210f819fe8df550af494
    https://github.com/scummvm/scummvm/commit/9560969ea8cf2e6f1d97210f819fe8df550af494
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove shader-related files

Changed paths:
  R engines/sludge/color.frag
  R engines/sludge/color.vert
  R engines/sludge/fixScaleSprite.frag
  R engines/sludge/fixScaleSprite.vert
  R engines/sludge/scale.frag
  R engines/sludge/scale.vert
  R engines/sludge/scale_noaa.frag
  R engines/sludge/shaders.cpp
  R engines/sludge/shaders.h
  R engines/sludge/texture.frag
  R engines/sludge/texture.vert
  R engines/sludge/yuv.frag
  R engines/sludge/yuv.vert
    engines/sludge/module.mk
    engines/sludge/movie.cpp
    engines/sludge/sprites.cpp


diff --git a/engines/sludge/color.frag b/engines/sludge/color.frag
deleted file mode 100644
index 1f3e45a..0000000
--- a/engines/sludge/color.frag
+++ /dev/null
@@ -1,7 +0,0 @@
-varying vec4 color;
-
-void main(void)
-{
-	gl_FragColor = color;
-}
-
diff --git a/engines/sludge/color.vert b/engines/sludge/color.vert
deleted file mode 100644
index 819d377..0000000
--- a/engines/sludge/color.vert
+++ /dev/null
@@ -1,13 +0,0 @@
-attribute vec4 myVertex;
-
-uniform mat4 myPMVMatrix;
-uniform vec4 myColor;
-
-varying vec4 color;
-
-void main(void)
-{
-	gl_Position = myPMVMatrix * myVertex;
-	color = myColor;
-}
-
diff --git a/engines/sludge/fixScaleSprite.frag b/engines/sludge/fixScaleSprite.frag
deleted file mode 100644
index ed9f6cf..0000000
--- a/engines/sludge/fixScaleSprite.frag
+++ /dev/null
@@ -1,29 +0,0 @@
-uniform sampler2D tex0;
-uniform sampler2D tex1;
-uniform sampler2D tex2;
-uniform bool useLightTexture;
-
-varying vec2 varCoord0;
-varying vec2 varCoord1;
-varying vec2 varCoord2;
-
-varying vec4 color;
-varying vec4 secondaryColor;
-
-void main()
-{
-	vec4 texture = texture2D (tex0, varCoord0);
-	vec4 texture2 = texture2D (tex2, varCoord2);
-	vec3 col;
-	if (useLightTexture) {
-		vec4 texture1 = texture2D (tex1, varCoord1);
-		col = texture1.rgb * texture.rgb;
-	} else {
-		col = color.rgb * texture.rgb;
-	}
-	col += vec3(secondaryColor);
-	vec4 color = vec4 (col, color.a * texture.a);
-	col = mix (texture2.rgb, color.rgb, color.a);
-	gl_FragColor = vec4 (col, max(texture.a, texture2.a));
-}
-
diff --git a/engines/sludge/fixScaleSprite.vert b/engines/sludge/fixScaleSprite.vert
deleted file mode 100644
index d9f4e51..0000000
--- a/engines/sludge/fixScaleSprite.vert
+++ /dev/null
@@ -1,25 +0,0 @@
-attribute vec4 myVertex;
-attribute vec2 myUV0;
-attribute vec2 myUV1;
-attribute vec2 myUV2;
-
-uniform mat4 myPMVMatrix;
-uniform vec4 myColor;
-uniform vec4 mySecondaryColor;
-
-varying vec2 varCoord0;
-varying vec2 varCoord1;
-varying vec2 varCoord2;
-
-varying vec4 color;
-varying vec4 secondaryColor;
-
-void main() {
-	varCoord0 = myUV0.st;
-	varCoord1 = myUV1.st;
-	varCoord2 = myUV2.st;
-	gl_Position = myPMVMatrix * myVertex;
-
-	color = myColor;
-	secondaryColor = mySecondaryColor;
-}
diff --git a/engines/sludge/module.mk b/engines/sludge/module.mk
index afe1d88..2e321ea 100644
--- a/engines/sludge/module.mk
+++ b/engines/sludge/module.mk
@@ -42,7 +42,6 @@ MODULE_OBJS := \
 	utf8.o \
 	variable.o \
 	zbuffer.o \
-#	shaders.o \
 #	libwebm/mkvparser.o \
 #	libwebm/mkvreader.o \
  
diff --git a/engines/sludge/movie.cpp b/engines/sludge/movie.cpp
index dc49cc4..df9031b 100644
--- a/engines/sludge/movie.cpp
+++ b/engines/sludge/movie.cpp
@@ -43,7 +43,6 @@
 #include "sludge/timing.h"
 #include "sludge/graphics.h"
 #include "sludge/movie.h"
-#include "sludge/shaders.h"
 #include "sludge/sound.h"
 
 namespace Sludge {
diff --git a/engines/sludge/scale.frag b/engines/sludge/scale.frag
deleted file mode 100644
index 1355871..0000000
--- a/engines/sludge/scale.frag
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
-   Inspired by a shader by guest(r) - guest.r at gmail.com - that was found at
-   http://www.razyboard.com/system/morethread-smart-texture-mag-filter-for-ogl2-and-dosbox-pete_bernert-266904-5689051-0.html
-*/
-
-uniform sampler2D Texture;
-uniform sampler2D lightTexture;
-uniform bool antialias;
-uniform bool useLightTexture;
-uniform float scale;
-
-varying vec2 varCoord0;
-varying vec2 varCoord1;
-
-varying vec4 color;
-varying vec4 secondaryColor;
-
-void main()
-{
-	vec4 c11 = texture2D(Texture, varCoord0.xy);
-
-	if (antialias) {
-		vec2 fw = fwidth(varCoord0.xy)*scale;
-
-		vec2 sd1 = vec2( fw.x,fw.y);
-		vec2 sd2 = vec2(-fw.x,fw.y);
-
-		vec4 s00 = texture2D(Texture, varCoord0.xy-sd1);
-		vec4 s20 = texture2D(Texture, varCoord0.xy-sd2);
-		vec4 s22 = texture2D(Texture, varCoord0.xy+sd1);
-		vec4 s02 = texture2D(Texture, varCoord0.xy+sd2);   
-
-		vec4 dt = vec4(1.0,1.0,1.0,1.0);
-		
-		float m1=dot(abs(s00-s22),dt)+0.0001;
-		float m2=dot(abs(s02-s20),dt)+0.0001;
-
-		vec4 temp1 = m2*(s00 + s22) + m1*(s02 + s20);
-
-	//	gl_FragColor = (temp1/(m1+m2)) * 0.5;
-		c11 = c11*0.333333 + (temp1/(m1+m2)) * 0.333333;
-	} 
-	/*
-	else {
-		gl_FragColor = c11;
-	}*/
-
-	//if (gl_FragColor.a<0.001) discard;
-	
-	vec3 col;
-	if (useLightTexture) {
-		vec4 texture1 = texture2D (lightTexture, varCoord1.xy);
-		col = texture1.rgb * c11.rgb;
-	} else {
-		col = color.rgb * c11.rgb;
-	}
-	col += vec3(secondaryColor);
-	gl_FragColor = vec4 (col, color.a * c11.a);
-}
-
diff --git a/engines/sludge/scale.vert b/engines/sludge/scale.vert
deleted file mode 100644
index ff6aa05..0000000
--- a/engines/sludge/scale.vert
+++ /dev/null
@@ -1,25 +0,0 @@
-attribute vec4 myVertex;
-attribute vec2 myUV0;
-attribute vec2 myUV1;
-
-uniform mat4 myPMVMatrix;
-uniform vec4 myColor;
-uniform vec4 mySecondaryColor;
-
-varying vec2 varCoord0;
-varying vec2 varCoord1;
-
-varying vec4 color;
-varying vec4 secondaryColor;
-
-void main()
-{
-	gl_Position = myPMVMatrix * myVertex;
-	varCoord0 = myUV0.st;
-
-	// Light
-	varCoord1 = myUV1.st;
-
-	color = myColor;
-	secondaryColor = mySecondaryColor;
-}
diff --git a/engines/sludge/scale_noaa.frag b/engines/sludge/scale_noaa.frag
deleted file mode 100644
index bf7aad7..0000000
--- a/engines/sludge/scale_noaa.frag
+++ /dev/null
@@ -1,31 +0,0 @@
-uniform sampler2D Texture;
-uniform sampler2D lightTexture;
-uniform bool antialias;
-uniform bool useLightTexture;
-uniform float scale;
-
-varying vec2 varCoord0;
-varying vec2 varCoord1;
-
-varying vec4 color;
-varying vec4 secondaryColor;
-
-void main()
-{
-	vec4 c11 = texture2D(Texture, varCoord0.xy);
-
-	//gl_FragColor = c11;
-
-	//if (gl_FragColor.a<0.001) discard;
-	
-	vec3 col;
-	if (useLightTexture) {
-		vec4 texture1 = texture2D (lightTexture, varCoord1.xy);
-		col = texture1.rgb * c11.rgb;
-	} else {
-		col = color.rgb * c11.rgb;
-	}
-	col += vec3(secondaryColor);
-	gl_FragColor = vec4 (col, color.a * c11.a);
-}
-
diff --git a/engines/sludge/shaders.cpp b/engines/sludge/shaders.cpp
deleted file mode 100644
index 69c3f99..0000000
--- a/engines/sludge/shaders.cpp
+++ /dev/null
@@ -1,178 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-
-#include "sludge/allfiles.h"
-#include "sludge/debug.h"
-#include "sludge/stringy.h"
-#include "sludge/shaders.h"
-#include "sludge/graphics.h"
-
-namespace Sludge {
-
-extern char *bundleFolder;
-
-//Function from: http://www.evl.uic.edu/aej/594/code/ogl.cpp
-//Read in a textfile (GLSL program)
-// we need to pass it as a string to the GLSL driver
-char *shaderFileRead(const char *name) {
-	Common::File fd;
-	char *content = NULL;
-	char *fn = joinStrings(bundleFolder, name);
-
-	int count = 0;
-
-	if (fn != NULL) {
-		if (fd.open(fn)) {
-
-			fd.seek(0, SEEK_END);
-			count = fd.pos();
-			fd.seek(0);
-
-			if (count > 0) {
-				content = (char *)malloc(sizeof(char) * (count + 1));
-				count = fd.read(content, sizeof(char) * count);
-				content[count] = '\0';
-			}
-			fd.close();
-		}
-	}
-	delete fn;
-	return content;
-}
-
-#if 0
-static void
-printShaderInfoLog(GLuint shader) {
-	GLint     infologLength = 0;
-	GLint     charsWritten  = 0;
-	char *infoLog;
-
-#if 0
-	printOpenGLError();   // Check for OpenGL errors
-	glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infologLength);
-	printOpenGLError();   // Check for OpenGL errors
-#endif
-
-	if (infologLength > 0) {
-		infoLog = new char [infologLength];
-		if (infoLog == NULL) {
-			debugOut("ERROR: Could not allocate InfoLog buffer");
-			return;
-		}
-#if 0
-		glGetShaderInfoLog(shader, infologLength, &charsWritten, infoLog);
-		debugOut("Shader InfoLog:\n%s\n\n", infoLog);
-#endif
-		delete[] infoLog;
-	}
-	printOpenGLError();  // Check for OpenGL errors
-}
-
-/* Print out the information log for a program object */
-static void
-printProgramInfoLog(GLuint program) {
-	GLint     infologLength = 0;
-	GLint     charsWritten  = 0;
-	char *infoLog;
-#if 0
-	printOpenGLError();   // Check for OpenGL errors
-	glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infologLength);
-	printOpenGLError();   // Check for OpenGL errors
-#endif
-	if (infologLength > 0) {
-		infoLog = new char [infologLength];
-		if (infoLog == NULL) {
-			debugOut("ERROR: Could not allocate InfoLog buffer");
-			return;
-		}
-#if 0
-		glGetProgramInfoLog(program, infologLength, &charsWritten, infoLog);
-		debugOut("Program InfoLog:\n%s\n\n", infoLog);
-#endif
-		delete[] infoLog;
-	}
-	printOpenGLError();   // Check for OpenGL errors
-}
-#endif
-
-int buildShaders(const char *vertexShader, const char *fragmentShader) {
-#if 0
-	GLuint VS, FS, prog;
-	GLint vertCompiled, fragCompiled;
-	GLint linked;
-
-	// Create Shader Objects
-	VS = glCreateShader(GL_VERTEX_SHADER);
-	FS = glCreateShader(GL_FRAGMENT_SHADER);
-
-	// Load source code strings into shaders
-	glShaderSource(VS, 1, &vertexShader, NULL);
-	glShaderSource(FS, 1, &fragmentShader, NULL);
-#endif
-	debugOut("Compiling vertex shader... \n");
-#if 0
-	// Compile vertex shader and print log
-	glCompileShader(VS);
-	printOpenGLError();
-	glGetShaderiv(VS, GL_COMPILE_STATUS, &vertCompiled);
-	printShaderInfoLog(VS);
-#endif
-	debugOut("\nCompiling fragment shader... \n");
-#if 0
-	// Compile fragment shader and print log
-	glCompileShader(FS);
-	printOpenGLError();
-	glGetShaderiv(FS, GL_COMPILE_STATUS, &fragCompiled);
-	printShaderInfoLog(FS);
-
-	if (!vertCompiled || !fragCompiled)
-		return 0;
-#endif
-	debugOut("\nShaders compiled. \n");
-
-#if 0
-	// Create a program object and attach the two compiled shaders
-	prog = glCreateProgram();
-	glAttachShader(prog, VS);
-	glAttachShader(prog, FS);
-
-	// Clean up
-	glDeleteShader(VS);
-	glDeleteShader(FS);
-
-	// Link the program and print log
-	glLinkProgram(prog);
-	printOpenGLError();
-	glGetProgramiv(prog, GL_LINK_STATUS, &linked);
-	printProgramInfoLog(prog);
-
-	if (!linked)
-		return 0;
-
-	debugOut("Shader program linked. \n");
-
-	return prog;
-#endif
-	return 0; //TODO: false value
-}
-
-} // End of namespace Sludge
diff --git a/engines/sludge/shaders.h b/engines/sludge/shaders.h
deleted file mode 100644
index fe31e19..0000000
--- a/engines/sludge/shaders.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-#ifndef SLUDGE_SHADERS_H
-#define SLUDGE_SHADERS_H
-
-namespace Sludge {
-
-char *shaderFileRead(const char *fn);
-int buildShaders(const char *vertexShader, const char *fragmentShader);
-
-} // End of namespace Sludge
-
-#endif
-
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index 6d51b8f..a89d37d 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -35,7 +35,6 @@
 #include "sludge/debug.h"
 #include "sludge/graphics.h"
 #include "sludge/imgloader.h"
-#include "sludge/shaders.h"
 #include "sludge/sludge.h"
 
 namespace Sludge {
diff --git a/engines/sludge/texture.frag b/engines/sludge/texture.frag
deleted file mode 100644
index 3de427b..0000000
--- a/engines/sludge/texture.frag
+++ /dev/null
@@ -1,22 +0,0 @@
-uniform sampler2D sampler2d;
-uniform bool zBuffer;
-uniform float zBufferLayer;
-uniform bool modulateColor;
-
-varying vec2 varCoord;
-varying vec4 color;
-
-void main(void)
-{
-	vec4 col = texture2D(sampler2d, varCoord);
-	if (zBuffer && col.a < 0.0625*zBufferLayer-0.03)
-	{
-		discard;
-	}
-	if (modulateColor)
-	{
-		col = col * color;
-	}
-	gl_FragColor = col;
-}
-
diff --git a/engines/sludge/texture.vert b/engines/sludge/texture.vert
deleted file mode 100644
index 40099af..0000000
--- a/engines/sludge/texture.vert
+++ /dev/null
@@ -1,16 +0,0 @@
-attribute vec4 myVertex;
-attribute vec2 myUV0;
-
-uniform mat4 myPMVMatrix;
-uniform vec4 myColor;
-
-varying vec2 varCoord;
-varying vec4 color;
-
-void main(void)
-{
-	gl_Position = myPMVMatrix * myVertex;
-	varCoord = myUV0.st;
-	color = myColor;
-}
-
diff --git a/engines/sludge/yuv.frag b/engines/sludge/yuv.frag
deleted file mode 100644
index 42db4fe..0000000
--- a/engines/sludge/yuv.frag
+++ /dev/null
@@ -1,25 +0,0 @@
-uniform sampler2D Ytex;
-uniform sampler2D Utex;
-uniform sampler2D Vtex;
-
-varying vec2 varCoord;
-
-void main()
-{
-	float y, u, v, r, g, b;
-
-	y=texture2D(Ytex, varCoord).a;
-	u=texture2D(Utex, varCoord).a;
-	v=texture2D(Vtex, varCoord).a;
-	
-	y=1.1643*(y-0.0625);
-	u=u-0.5;
-	v=v-0.5;
-
-	r=y+1.5958*v;
-	g=y-0.39173*u-0.81290*v;
-	b=y+2.017*u;
-
-	gl_FragColor=vec4(r,g,b,1.0);
-}
-
diff --git a/engines/sludge/yuv.vert b/engines/sludge/yuv.vert
deleted file mode 100644
index 28613b6..0000000
--- a/engines/sludge/yuv.vert
+++ /dev/null
@@ -1,12 +0,0 @@
-attribute vec4 myVertex;
-attribute vec2 myUV0;
-
-uniform mat4 myPMVMatrix;
-
-varying vec2 varCoord;
-
-void main()
-{
-	gl_Position = myPMVMatrix * myVertex;
-	varCoord = myUV0.st;
-}


Commit: 1e261d6cd3e40e67249d9036ae78cdb7e9d9e275
    https://github.com/scummvm/scummvm/commit/1e261d6cd3e40e67249d9036ae78cdb7e9d9e275
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove unused libs

Changed paths:
  R engines/sludge/eglport/eglport.cpp
  R engines/sludge/eglport/eglport.h
  R engines/sludge/libvorbis/COPYING
  R engines/sludge/libvorbis/vorbis_misc.h
  R engines/sludge/libvorbis/vorbis_os.h
  R engines/sludge/libwebm/AUTHORS.TXT
  R engines/sludge/libwebm/LICENSE.TXT
  R engines/sludge/libwebm/PATENTS.TXT
  R engines/sludge/libwebm/mkvparser.cpp
  R engines/sludge/libwebm/mkvparser.hpp
  R engines/sludge/libwebm/mkvreader.cpp
  R engines/sludge/libwebm/mkvreader.hpp
    engines/sludge/module.mk
    engines/sludge/movie.cpp


diff --git a/engines/sludge/eglport/eglport.cpp b/engines/sludge/eglport/eglport.cpp
deleted file mode 100755
index 8414383..0000000
--- a/engines/sludge/eglport/eglport.cpp
+++ /dev/null
@@ -1,712 +0,0 @@
-/**
- *
- *  EGLPORT.C
- *  Copyright (C) 2011-2013 Scott R. Smith
- *
- *  Permission is hereby granted, free of charge, to any person obtaining a copy
- *  of this software and associated documentation files (the "Software"), to deal
- *  in the Software without restriction, including without limitation the rights
- *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- *  copies of the Software, and to permit persons to whom the Software is
- *  furnished to do so, subject to the following conditions:
- *
- *  The above copyright notice and this permission notice shall be included in
- *  all copies or substantial portions of the Software.
- *
- *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- *  THE SOFTWARE.
- *
- */
-
-#include "eglport.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-
-//#define USE_EGL_SDL 1
-//#define USE_GLES1	1
-
-#if defined(USE_EGL_SDL)
-#include "SDL.h"
-#include "SDL_syswm.h"
-SDL_SysWMinfo sysWmInfo;      /** Holds our X Display/Window information */
-#endif /* USE_EGL_SDL */
-
-#if defined(PANDORA) /* Pandora VSync Support */
-#include <unistd.h>
-#include <fcntl.h>
-#include <sys/ioctl.h>
-#include <linux/fb.h>
-
-#ifndef FBIO_WAITFORVSYNC
-#define FBIO_WAITFORVSYNC _IOW('F', 0x20, __u32)
-#endif
-int fbdev = -1;
-
-#elif defined(RPI)
-#include "bcm_host.h"
-#endif /* PANDORA */
-
-enum EGL_RENDER_T {
-    RENDER_RAW=0,           /** Sets render mode to raw or framebuffer mode. */
-    RENDER_SDL,             /** Sets render mode to X11/SDL mode. */
-    RENDER_TOTAL
-};
-
-enum EGL_SETTINGS_T {
-    CFG_MODE=0,             /** Render mode for EGL 0=RAW 1=SDL. */
-    CFG_VSYNC,              /** Controls system vsync if available. */
-    CFG_FSAA,               /** Number of samples for full screen AA. 0 is off, 2/4 samples. */
-    CFG_FPS,                /** Calculate and report frame per second. */
-    CFG_RED_SIZE,           /** Number of bits of Red in the color buffer. */
-    CFG_GREEN_SIZE,         /** Number of bits of Green in the color buffer. */
-    CFG_BLUE_SIZE,          /** Number of bits of Blue in the color buffer. */
-    CFG_ALPHA_SIZE,         /** Number of bits of Alpha in the color buffer. */
-    CFG_DEPTH_SIZE,         /** Number of bits of Z in the depth buffer. */
-    CFG_BUFFER_SIZE,        /** The total color component bits in the color buffer. */
-    CFG_STENCIL_SIZE,       /** Number of bits of Stencil in the stencil buffer. */
-    CFG_TOTAL               /** Total number of settings. */
-};
-
-NativeDisplayType   nativeDisplay = 0;      /** Reference to the systems native display */
-NativeWindowType    nativeWindow  = 0;      /** Reference to the systems native window */
-EGLint              eglSettings[CFG_TOTAL]; /** Stores setting values. */
-EGLDisplay          eglDisplay    = NULL;   /** Reference to the EGL display */
-EGLConfig           eglConfig     = NULL;   /** Reference to the EGL config */
-EGLContext          eglContext    = NULL;   /** Reference to the EGL context */
-EGLSurface          eglSurface    = NULL;   /** Reference to the EGL surface */
-
-#define     totalConfigsIn 5                /** Total number of configurations to request */
-EGLint      totalConfigsFound = 0;          /** Total number of configurations matching attributes */
-EGLConfig   eglConfigs[totalConfigsIn];     /** Structure containing references to matching configurations */
-
-uint32_t    fpsCount    = 0;                /** Total number of frames counted */
-uint32_t    fpsTime     = 0;                /** Start time of frame count measurment */
-
-int8_t	eglColorbits 	= 0;
-int8_t	eglDepthbits	= 0;
-int8_t	eglStencilbits	= 0;
-
-
-/** Private API */
-void        OpenCfg                 ( const char* file );
-int8_t      ConfigureEGL            ( EGLConfig config );
-int8_t      FindEGLConfigs          ( void );
-int8_t      CheckEGLErrors          ( const char* file, uint16_t line );
-
-int8_t      GetNativeDisplay        ( void );
-int8_t      GetNativeWindow         ( uint16_t width, uint16_t height );
-void        FreeNativeDisplay       ( void );
-void        FreeNativeWindow        ( void );
-
-void        Platform_Open           ( void );
-void        Platform_Close          ( void );
-void        Platform_VSync          ( void );
-uint32_t    Platform_GetTicks       ( void );
-
-void EGL_Init( void )
-{
-  //nothing...
-  return;
-}
-/** @brief Release all EGL and system resources
- */
-void EGL_Close( void )
-{
-    /* Release EGL resources */
-    if (eglDisplay != NULL)
-    {
-        peglMakeCurrent( eglDisplay, NULL, NULL, EGL_NO_CONTEXT );
-        if (eglContext != NULL) {
-            peglDestroyContext( eglDisplay, eglContext );
-        }
-        if (eglSurface != NULL) {
-            peglDestroySurface( eglDisplay, eglSurface );
-        }
-        peglTerminate( eglDisplay );
-    }
-
-    eglSurface = NULL;
-    eglContext = NULL;
-    eglDisplay = NULL;
-	
-	eglColorbits = 0;
-	eglDepthbits = 0;
-	eglStencilbits = 0;
-
-    /* Release platform resources */
-    FreeNativeWindow();
-    FreeNativeDisplay();
-    Platform_Close();
-
-    CheckEGLErrors( __FILE__, __LINE__ );
-
-    printf( "EGLport: Closed\n" );
-}
-
-/** @brief Swap the surface buffer onto the display
- */
-void EGL_SwapBuffers( void )
-{
-    if (eglSettings[CFG_VSYNC] != 0) {
-        Platform_VSync();
-    }
-
-    peglSwapBuffers( eglDisplay, eglSurface );
-
-    if (eglSettings[CFG_FPS] != 0) {
-        fpsCount++;
-
-        if (fpsTime - Platform_GetTicks() >= 1000)
-        {
-            printf( "EGLport: %d fps\n", fpsCount );
-            fpsTime = Platform_GetTicks();
-            fpsCount = 0;
-        }
-    }
-}
-
-/** @brief Obtain the system display and initialize EGL
- * @param width : desired pixel width of the window (not used by all platforms)
- * @param height : desired pixel height of the window (not used by all platforms)
- * @return : 0 if the function passed, else 1
- */
-int8_t EGL_Open( /*uint16_t width, uint16_t height*/ )
-{
-    EGLint eglMajorVer, eglMinorVer;
-    EGLBoolean result;
-    uint32_t configIndex = 0;
-    const char* output;
-
-    static const EGLint contextAttribs[] =
-    {
-#if defined(USE_GLES2)
-          EGL_CONTEXT_CLIENT_VERSION,     2,
-#endif
-          EGL_NONE
-    };
-
-#if defined(DEBUG)
-    printf( "EGLport Warning: DEBUG is enabled which may effect performance\n" );
-#endif
-
-    /* Check that system is not open */
-    if (eglDisplay != NULL || eglContext != NULL || eglSurface != NULL)
-    {
-        printf( "EGLport ERROR: EGL system is already open!\n" );
-        return 1;
-    }
-
-    /* Check for the cfg file to alternative settings */
-    OpenCfg( "eglport.cfg" );
-
-    /* Setup any platform specific bits */
-    Platform_Open();
-
-    printf( "EGLport: Opening EGL display\n" );
-    if (GetNativeDisplay() != 0)
-    {
-        printf( "EGLport ERROR: Unable to obtain native display!\n" );
-        return 1;
-    }
-
-    eglDisplay = peglGetDisplay( nativeDisplay );
-    if (eglDisplay == EGL_NO_DISPLAY)
-    {
-        CheckEGLErrors( __FILE__, __LINE__ );
-        printf( "EGLport ERROR: Unable to create EGL display.\n" );
-        return 1;
-    }
-
-    printf( "EGLport: Initializing\n" );
-    result = peglInitialize( eglDisplay, &eglMajorVer, &eglMinorVer );
-    if (result != EGL_TRUE )
-    {
-        CheckEGLErrors( __FILE__, __LINE__ );
-        printf( "EGLport ERROR: Unable to initialize EGL display.\n" );
-        return 1;
-    }
-
-    /* Get EGL Library Information */
-    printf( "EGL Implementation Version: Major %d Minor %d\n", eglMajorVer, eglMinorVer );
-    output = peglQueryString( eglDisplay, EGL_VENDOR );
-    printf( "EGL_VENDOR: %s\n", output );
-    output = peglQueryString( eglDisplay, EGL_VERSION );
-    printf( "EGL_VERSION: %s\n", output );
-    output = peglQueryString( eglDisplay, EGL_EXTENSIONS );
-    printf( "EGL_EXTENSIONS: %s\n", output );
-
-    if (FindEGLConfigs() != 0)
-    {
-        printf( "EGLport ERROR: Unable to configure EGL. See previous error.\n" );
-        return 1;
-    }
-
-    printf( "EGLport: Using Config %d\n", configIndex );
-#if defined(EGL_VERSION_1_2)
-    /* Bind GLES and create the context */
-    printf( "EGLport: Binding API\n" );
-    result = peglBindAPI( EGL_OPENGL_ES_API );
-    if ( result == EGL_FALSE )
-    {
-        CheckEGLErrors( __FILE__, __LINE__ );
-        printf( "EGLport ERROR: Could not bind EGL API.\n" );
-        return 1;
-    }
-#endif /* EGL_VERSION_1_2 */
-
-    printf( "EGLport: Creating Context\n" );
-    eglContext = peglCreateContext( eglDisplay, eglConfigs[configIndex], NULL, contextAttribs );
-    if (eglContext == EGL_NO_CONTEXT)
-    {
-        CheckEGLErrors( __FILE__, __LINE__ );
-        printf( "EGLport ERROR: Unable to create GLES context!\n");
-        return 1;
-    }
-
-    printf( "EGLport: Creating window surface\n" );
-    if (GetNativeWindow( 800, 480/*width, height*/ ) != 0)
-    {
-        printf( "EGLport ERROR: Unable to obtain native window!\n" );
-        return 1;
-    }
-
-    eglSurface = peglCreateWindowSurface( eglDisplay, eglConfigs[configIndex], nativeWindow, 0 );
-    if (eglSurface == EGL_NO_SURFACE)
-    {
-        CheckEGLErrors( __FILE__, __LINE__ );
-        printf( "EGLport ERROR: Unable to create EGL surface!\n" );
-        return 1;
-    }
-
-    printf( "EGLport: Making Current\n" );
-    result = peglMakeCurrent( eglDisplay,  eglSurface,  eglSurface, eglContext );
-    if (result != EGL_TRUE)
-    {
-        CheckEGLErrors( __FILE__, __LINE__ );
-        printf( "EGLport ERROR: Unable to make GLES context current\n" );
-        return 1;
-    }
-
-	{
-	  EGLint color, depth, stencil;
-	  eglGetConfigAttrib(eglDisplay, eglConfigs[configIndex], EGL_BUFFER_SIZE, &color);
-	  eglGetConfigAttrib(eglDisplay, eglConfigs[configIndex], EGL_DEPTH_SIZE, &depth);
-	  eglGetConfigAttrib(eglDisplay, eglConfigs[configIndex], EGL_STENCIL_SIZE, &stencil);
-	  eglColorbits = (color==16)?5:8; //quick hack
-	  eglDepthbits = depth;
-	  eglStencilbits = stencil;
-	}
-
-    printf( "EGLport: Setting swap interval\n" );
-    peglSwapInterval( eglDisplay, (eglSettings[CFG_VSYNC] > 0) ? 1 : 0 );
-
-    printf( "EGLport: Complete\n" );
-
-    CheckEGLErrors( __FILE__, __LINE__ );
-	
-    return 0;
-}
-
-/** @brief Read settings that configure how to use EGL
- * @param file : name of the config file
- */
-void OpenCfg ( const char* file )
-{
-    #define MAX_STRING 20
-    #define MAX_SIZE 100
-    uint8_t i;
-    FILE* fp = NULL;
-    char* location = NULL;
-    char eglStrings[CFG_TOTAL][MAX_STRING];
-    char buffer[MAX_SIZE];
-
-    strncpy( eglStrings[CFG_MODE], "egl_mode=", MAX_STRING );
-    strncpy( eglStrings[CFG_VSYNC], "use_vsync=", MAX_STRING );
-    strncpy( eglStrings[CFG_FSAA], "use_fsaa=", MAX_STRING );
-    strncpy( eglStrings[CFG_RED_SIZE], "size_red=", MAX_STRING );
-    strncpy( eglStrings[CFG_GREEN_SIZE], "size_green=", MAX_STRING );
-    strncpy( eglStrings[CFG_BLUE_SIZE], "size_blue=", MAX_STRING );
-    strncpy( eglStrings[CFG_ALPHA_SIZE], "size_alpha=", MAX_STRING );
-    strncpy( eglStrings[CFG_DEPTH_SIZE], "size_depth=", MAX_STRING );
-    strncpy( eglStrings[CFG_BUFFER_SIZE], "size_buffer=", MAX_STRING );
-    strncpy( eglStrings[CFG_STENCIL_SIZE], "size_stencil=", MAX_STRING );
-
-    /* Set defaults */
-#if defined(USE_EGL_SDL) && !defined(PANDORA)
-    eglSettings[CFG_MODE]           = RENDER_SDL;
-#else
-    eglSettings[CFG_MODE]           = RENDER_RAW;
-#endif
-    eglSettings[CFG_VSYNC]          = 0;
-    eglSettings[CFG_FSAA]           = 0;
-    eglSettings[CFG_FPS]            = 0;
-    eglSettings[CFG_RED_SIZE]       = 5;
-    eglSettings[CFG_GREEN_SIZE]     = 6;
-    eglSettings[CFG_BLUE_SIZE]      = 5;
-    eglSettings[CFG_ALPHA_SIZE]     = 0;
-    eglSettings[CFG_DEPTH_SIZE]     = 16;
-    eglSettings[CFG_BUFFER_SIZE]    = 16;
-    eglSettings[CFG_STENCIL_SIZE]   = 0;
-
-    /* Parse INI file */
-    fp = fopen( file, "r");
-    if (fp != NULL)
-    {
-        while (fgets( buffer, MAX_SIZE, fp ) != NULL)
-        {
-            for (i=0; i<CFG_TOTAL; i++)
-            {
-                location = strstr( buffer, eglStrings[i] );
-                if (location != NULL)
-                {
-                    eglSettings[i] = atol( location+strlen( eglStrings[i] ) );
-                    printf( "EGLport: %s set to %d.\n", eglStrings[i], eglSettings[i] );
-                    break;
-                }
-            }
-        }
-
-        fclose( fp );
-    }
-    else
-    {
-        printf( "EGL NOTICE: Unable to read ini settings from file '%s'. Using defaults\n", file );
-    }
-}
-
-/** @brief Find a EGL configuration tht matches the defined attributes
- * @return : 0 if the function passed, else 1
- */
-int8_t FindEGLConfigs( void )
-{
-    EGLBoolean result;
-    int attrib = 0;
-    EGLint ConfigAttribs[23];
-
-    ConfigAttribs[attrib++] = EGL_RED_SIZE;                         /* 1 */
-    ConfigAttribs[attrib++] = eglSettings[CFG_RED_SIZE];            /* 2 */
-    ConfigAttribs[attrib++] = EGL_GREEN_SIZE;                       /* 3 */
-    ConfigAttribs[attrib++] = eglSettings[CFG_GREEN_SIZE];          /* 4 */
-    ConfigAttribs[attrib++] = EGL_BLUE_SIZE;                        /* 5 */
-    ConfigAttribs[attrib++] = eglSettings[CFG_BLUE_SIZE];           /* 6 */
-    ConfigAttribs[attrib++] = EGL_ALPHA_SIZE;                       /* 7 */
-    ConfigAttribs[attrib++] = eglSettings[CFG_ALPHA_SIZE];          /* 8 */
-    ConfigAttribs[attrib++] = EGL_DEPTH_SIZE;                       /* 9 */
-    ConfigAttribs[attrib++] = eglSettings[CFG_DEPTH_SIZE];          /* 10 */
-    ConfigAttribs[attrib++] = EGL_BUFFER_SIZE;                      /* 11 */
-    ConfigAttribs[attrib++] = eglSettings[CFG_BUFFER_SIZE];         /* 12 */
-    ConfigAttribs[attrib++] = EGL_STENCIL_SIZE;                     /* 13 */
-    ConfigAttribs[attrib++] = eglSettings[CFG_STENCIL_SIZE];        /* 14 */
-    ConfigAttribs[attrib++] = EGL_SURFACE_TYPE;                     /* 15 */
-    ConfigAttribs[attrib++] = EGL_WINDOW_BIT;                       /* 16 */
-#if defined(EGL_VERSION_1_2)
-    ConfigAttribs[attrib++] = EGL_RENDERABLE_TYPE;                  /* 17 */
-#if defined(USE_GLES1)
-    ConfigAttribs[attrib++] = EGL_OPENGL_ES_BIT;
-#elif defined(USE_GLES2)
-    ConfigAttribs[attrib++] = EGL_OPENGL_ES2_BIT;                   /* 18 */
-#endif /* USE_GLES1 */
-#endif /* EGL_VERSION_1_2 */
-    ConfigAttribs[attrib++] = EGL_SAMPLE_BUFFERS;                   /* 19 */
-    ConfigAttribs[attrib++] = (eglSettings[CFG_FSAA] > 0) ? 1 : 0;  /* 20 */
-    ConfigAttribs[attrib++] = EGL_SAMPLES;                          /* 21 */
-    ConfigAttribs[attrib++] = eglSettings[CFG_FSAA];                /* 22 */
-    ConfigAttribs[attrib++] = EGL_NONE;                             /* 23 */
-
-    result = peglChooseConfig( eglDisplay, ConfigAttribs, eglConfigs, totalConfigsIn, &totalConfigsFound );
-    if (result != EGL_TRUE || totalConfigsFound == 0)
-    {
-        CheckEGLErrors( __FILE__, __LINE__ );
-        printf( "EGLport ERROR: Unable to query for available configs, found %d.\n", totalConfigsFound );
-        return 1;
-    }
-    printf( "EGLport: Found %d available configs\n", totalConfigsFound );
-
-    return 0;
-}
-
-/** @brief Error checking function
- * @param file : string reference that contains the source file that the check is occuring in
- * @param line : numeric reference that contains the line number that the check is occuring in
- * @return : 0 if the function passed, else 1
- */
-int8_t CheckEGLErrors( const char* file, uint16_t line )
-{
-    EGLenum error;
-    const char* errortext;
-    const char* description;
-
-    error = eglGetError();
-
-    if (error != EGL_SUCCESS && error != 0)
-    {
-        switch (error)
-        {
-            case EGL_NOT_INITIALIZED:
-                errortext   = "EGL_NOT_INITIALIZED.";
-                description = "EGL is not or could not be initialized, for the specified display.";
-                break;
-            case EGL_BAD_ACCESS:
-                errortext   = "EGL_BAD_ACCESS EGL";
-                description = "cannot access a requested resource (for example, a context is bound in another thread).";
-                break;
-            case EGL_BAD_ALLOC:
-                errortext   = "EGL_BAD_ALLOC EGL";
-                description = "failed to allocate resources for the requested operation.";
-                break;
-            case EGL_BAD_ATTRIBUTE:
-                errortext   = "EGL_BAD_ATTRIBUTE";
-                description = "An unrecognized attribute or attribute value was passed in anattribute list.";
-                break;
-            case EGL_BAD_CONFIG:
-                errortext   = "EGL_BAD_CONFIG";
-                description = "An EGLConfig argument does not name a valid EGLConfig.";
-                break;
-            case EGL_BAD_CONTEXT:
-                errortext   = "EGL_BAD_CONTEXT";
-                description = "An EGLContext argument does not name a valid EGLContext.";
-                break;
-            case EGL_BAD_CURRENT_SURFACE:
-                errortext   = "EGL_BAD_CURRENT_SURFACE";
-                description = "The current surface of the calling thread is a window, pbuffer,or pixmap that is no longer valid.";
-                break;
-            case EGL_BAD_DISPLAY:
-                errortext   = "EGL_BAD_DISPLAY";
-                description = "An EGLDisplay argument does not name a valid EGLDisplay.";
-                break;
-            case EGL_BAD_MATCH:
-                errortext   = "EGL_BAD_MATCH";
-                description = "Arguments are inconsistent; for example, an otherwise valid context requires buffers (e.g. depth or stencil) not allocated by an otherwise valid surface.";
-                break;
-            case EGL_BAD_NATIVE_PIXMAP:
-                errortext   = "EGL_BAD_NATIVE_PIXMAP";
-                description = "An EGLNativePixmapType argument does not refer to a validnative pixmap.";
-                break;
-            case EGL_BAD_NATIVE_WINDOW:
-                errortext   = "EGL_BAD_NATIVE_WINDOW";
-                description = "An EGLNativeWindowType argument does not refer to a validnative window.";
-                break;
-            case EGL_BAD_PARAMETER:
-                errortext   = "EGL_BAD_PARAMETER";
-                description = "One or more argument values are invalid.";
-                break;
-            case EGL_BAD_SURFACE:
-                errortext   = "EGL_BAD_SURFACE";
-                description = "An EGLSurface argument does not name a valid surface (window,pbuffer, or pixmap) configured for rendering";
-                break;
-            case EGL_CONTEXT_LOST:
-                errortext   = "EGL_CONTEXT_LOST";
-                description = "A power management event has occurred. The application mustdestroy all contexts and reinitialise client API state and objects to continue rendering.";
-                break;
-            default:
-                errortext   = "Unknown EGL Error";
-                description = "";
-                break;
-        }
-
-        printf( "EGLport ERROR: EGL Error detected in file %s at line %d: %s (0x%X)\n  Description: %s\n", file, line, errortext, error, description );
-        return 1;
-    }
-
-    return 0;
-}
-
-/** @brief Obtain a reference to the system's native display
- * @param window : pointer to save the display reference
- * @return : 0 if the function passed, else 1
- */
-int8_t GetNativeDisplay( void )
-{
-    if (eglSettings[CFG_MODE] == RENDER_RAW)        /* RAW FB mode */
-    {
-        printf( "EGLport: Using EGL_DEFAULT_DISPLAY\n" );
-        nativeDisplay = EGL_DEFAULT_DISPLAY;
-    }
-    else if (eglSettings[CFG_MODE] == RENDER_SDL)   /* SDL/X11 mode */
-    {
-#if defined(USE_EGL_SDL)
-        printf( "EGLport: Opening SDL/X11 display\n" );
-        SDL_VERSION(&sysWmInfo.version);
-        SDL_GetWMInfo(&sysWmInfo);
-        nativeDisplay = (EGLNativeDisplayType)sysWmInfo.info.x11.display;
-
-        if (nativeDisplay == 0)
-        {
-            printf( "EGLport ERROR: unable to get display!\n" );
-            return 1;
-        }
-#else
-        printf( "EGLport ERROR: SDL mode was not enabled in this compile!\n" );
-#endif
-    }
-
-    return 0;
-}
-
-/** @brief Obtain a reference to the system's native window
- * @param width : desired pixel width of the window (not used by all platforms)
- * @param height : desired pixel height of the window (not used by all platforms)
- * @return : 0 if the function passed, else 1
- */
-int8_t GetNativeWindow( uint16_t width, uint16_t height )
-{
-    nativeWindow = 0;
-
-#if defined(WIZ) || defined(CAANOO)
-
-    nativeWindow = (NativeWindowType)malloc(16*1024);
-
-    if(nativeWindow == NULL) {
-        printf( "EGLport ERROR: Memory for window Failed\n" );
-        return 1;
-    }
-
-#elif defined(RPI)
-
-    EGLBoolean result;
-    uint32_t screen_width, screen_height;
-    static EGL_DISPMANX_WINDOW_T nativewindow;
-    DISPMANX_ELEMENT_HANDLE_T dispman_element;
-    DISPMANX_DISPLAY_HANDLE_T dispman_display;
-    DISPMANX_UPDATE_HANDLE_T dispman_update;
-    VC_RECT_T dst_rect;
-    VC_RECT_T src_rect;
-
-    /* create an EGL window surface */
-    result = graphics_get_display_size(0 /* LCD */, &screen_width, &screen_height);
-    if(result < 0) {
-        printf( "EGLport ERROR: RPi graphicget_display_size failed\n" );
-        return 1;
-    }
-
-    dst_rect.x = 0;
-    dst_rect.y = 0;
-    dst_rect.width = screen_width;
-    dst_rect.height = screen_height;
-
-    src_rect.x = 0;
-    src_rect.y = 0;
-    src_rect.width = width << 16;
-    src_rect.height = height << 16;
-
-    dispman_display = vc_dispmanx_display_open( 0 /* LCD */);
-    dispman_update  = vc_dispmanx_update_start( 0 );
-    dispman_element = vc_dispmanx_element_add ( dispman_update, dispman_display,
-      0 /*layer*/, &dst_rect, 0 /*src*/,
-      &src_rect, DISPMANX_PROTECTION_NONE,  (VC_DISPMANX_ALPHA_T*)0 /*alpha*/,  (DISPMANX_CLAMP_T*)0 /*clamp*/,  (DISPMANX_TRANSFORM_T)0 /*transform*/);
-
-    nativewindow.element = dispman_element;
-    nativewindow.width = screen_width;
-    nativewindow.height = screen_height;
-    vc_dispmanx_update_submit_sync( dispman_update );
-
-    nativeWindow = (NativeWindowType)&nativewindow;
-
-#else /* default */
-
-    if (eglSettings[CFG_MODE] == RENDER_RAW)        /* RAW FB mode */
-    {
-        nativeWindow = 0;
-    }
-    else if(eglSettings[CFG_MODE] == RENDER_SDL)    /* SDL/X11 mode */
-    {
-#if defined(USE_EGL_SDL)
-        /* SDL_GetWMInfo is populated when display was opened */
-        nativeWindow = (NativeWindowType)sysWmInfo.info.x11.window;
-
-        if (nativeWindow == 0)
-        {
-            printf( "EGLport ERROR: unable to get window!\n" );
-            return 1;
-        }
-#else
-        printf( "EGLport ERROR: SDL mode was not enabled in this compile!\n" );
-#endif
-    }
-    else
-    {
-        printf( "EGLport ERROR: Unknown EGL render mode %d!\n", eglSettings[CFG_MODE] );
-        return 1;
-    }
-
-#endif /* WIZ / CAANOO */
-
-    return 0;
-}
-
-/** @brief Release the system's native display
- */
-void FreeNativeDisplay( void )
-{
-}
-
-/** @brief Release the system's native window
- */
-void FreeNativeWindow( void )
-{
-#if defined(WIZ) || defined(CAANOO)
-    if (nativeWindow != NULL) {
-        free( nativeWindow );
-    }
-    nativeWindow = NULL;
-#endif /* WIZ / CAANOO */
-}
-
-/** @brief Open any system specific resources
- */
-void Platform_Open( void )
-{
-#if defined(PANDORA)
-    /* Pandora VSync */
-    fbdev = open( "/dev/fb0", O_RDONLY /* O_RDWR */ );
-    if ( fbdev < 0 ) {
-        printf( "EGLport ERROR: Couldn't open /dev/fb0 for Pandora Vsync\n" );
-    }
-#elif defined(RPI)
-    bcm_host_init();
-#endif /* PANDORA */
-}
-
-/** @brief Release any system specific resources
- */
-void Platform_Close( void )
-{
-#if defined(PANDORA)
-    /* Pandora VSync */
-    close( fbdev );
-    fbdev = -1;
-#endif /* PANDORA */
-}
-
-/** @brief Check the systems vsync state
- */
-void Platform_VSync( void )
-{
-#if defined(PANDORA)
-    /* Pandora VSync */
-    if (fbdev >= 0) {
-        int arg = 0;
-        ioctl( fbdev, FBIO_WAITFORVSYNC, &arg );
-    }
-#endif /* PANDORA */
-}
-
-/** @brief Get the system tick time (ms)
- */
-uint32_t Platform_GetTicks( void )
-{
-    uint32_t ticks = 0;
-#if defined(USE_EGL_SDL)
-    ticks = SDL_GetTicks();
-#else
-    printf( "EGLport ERROR: SDL mode was not enabled in this compile!\n" );
-#endif
-    return ticks;
-}
-
diff --git a/engines/sludge/eglport/eglport.h b/engines/sludge/eglport/eglport.h
deleted file mode 100644
index 20fb979..0000000
--- a/engines/sludge/eglport/eglport.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/**
- *
- *  EGLPORT.H
- *  Copyright (C) 2011-2013 Scott R. Smith
- *
- *  Permission is hereby granted, free of charge, to any person obtaining a copy
- *  of this software and associated documentation files (the "Software"), to deal
- *  in the Software without restriction, including without limitation the rights
- *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- *  copies of the Software, and to permit persons to whom the Software is
- *  furnished to do so, subject to the following conditions:
- *
- *  The above copyright notice and this permission notice shall be included in
- *  all copies or substantial portions of the Software.
- *
- *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- *  THE SOFTWARE.
- *
- */
-
-#ifndef EGLPORT_H
-#define EGLPORT_H
-
-#include <stdint.h>
-#include "EGL/egl.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/** Defines (in every case choose only one) */
-/**     Common: */
-/**         DEBUG : enable additional error monitoring per EGL function call */
-/**     Native display and window system for use with EGL */
-/**         USE_EGL_SDL : used for access to a SDL X11 window */
-/**     Platform: settings that are specific to that device */
-/**         PANDORA (USE_GLES1 or USE_GLES2) */
-/**         WIZ     (USE_GLES1) */
-/**         CAANOO  (USE_GLES1) */
-/**         RPI     (USE_GLES1 or USE_GLES2) */
-/**     GLES Version */
-/**         USE_GLES1 : EGL for use with OpenGL-ES 1.X contexts */
-/**         USE_GLES2 : EGL for use with OpenGL-ES 2.0 contexts */
-
-/** Public API */
-void    EGL_Init                    ( void );
-void    EGL_Close                   ( void );
-int8_t  EGL_Open                    ( /*uint16_t width, uint16_t height*/ );
-void    EGL_SwapBuffers             ( void );
-
-extern int8_t	eglColorbits;
-extern int8_t	eglDepthbits;
-extern int8_t	eglStencilbits;
-
-/** Simple Examples  */
-/**     Raw mode:
-            EGL_Open( window_width, window_height );
-            do while(!quit) {
-                ... run app
-                EGL_SwapBuffers();
-            }
-            EGL_Close();
-*/
-/**     X11/SDL mode:
-            SDL_Init( SDL_INIT_VIDEO );
-            SDL_Surface* screen = SDL_SetVideoMode(640, 480, 16, SDL_SWSURFACE|SDL_FULLSCREEN);
-            EGL_Open( window_width, window_height );
-            do while(!quit) {
-                ... run app
-                EGL_SwapBuffers();
-            }
-            EGL_Close();
-            SDL_Quit();
-*/
-
-#if defined(DEBUG)
-#define GET_EGLERROR(FUNCTION)               \
-    FUNCTION;                                \
-    {                                        \
-        CheckEGLErrors(__FILE__, __LINE__);  \
-    }
-#else
-#define GET_EGLERROR(FUNCTION) FUNCTION;
-#endif
-
-#define peglQueryString(A,B)                    GET_EGLERROR(eglQueryString(A,B))
-#define peglDestroyContext(A,B)                 GET_EGLERROR(eglDestroyContext(A,B))
-#define peglDestroySurface(A,B)                 GET_EGLERROR(eglDestroySurface(A,B))
-#define peglTerminate(A)                        GET_EGLERROR(eglTerminate(A))
-#define peglSwapBuffers(A,B)                    GET_EGLERROR(eglSwapBuffers(A,B))
-#define peglGetDisplay(A)                       GET_EGLERROR(eglGetDisplay(A))
-#define peglBindAPI(A)                          GET_EGLERROR(eglBindAPI(A))
-#define peglCreateContext(A,B,C,D)              GET_EGLERROR(eglCreateContext(A,B,C,D))
-#define peglCreateWindowSurface(A,B,C,D)        GET_EGLERROR(eglCreateWindowSurface(A,B,C,D))
-#define peglInitialize(A,B,C)                   GET_EGLERROR(eglInitialize(A,B,C))
-#define peglMakeCurrent(A,B,C,D)                GET_EGLERROR(eglMakeCurrent(A,B,C,D))
-#define peglChooseConfig(A,B,C,D,E)             GET_EGLERROR(eglChooseConfig(A,B,C,D,E))
-#define peglSwapInterval(A,B)                   GET_EGLERROR(eglSwapInterval(A,B))
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* EGLPORT_H */
diff --git a/engines/sludge/libvorbis/COPYING b/engines/sludge/libvorbis/COPYING
deleted file mode 100644
index 28de72a..0000000
--- a/engines/sludge/libvorbis/COPYING
+++ /dev/null
@@ -1,28 +0,0 @@
-Copyright (c) 2002-2008 Xiph.org Foundation
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions
-are met:
-
-- Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
-
-- Redistributions in binary form must reproduce the above copyright
-notice, this list of conditions and the following disclaimer in the
-documentation and/or other materials provided with the distribution.
-
-- Neither the name of the Xiph.org Foundation nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION
-OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/engines/sludge/libvorbis/vorbis_misc.h b/engines/sludge/libvorbis/vorbis_misc.h
deleted file mode 100644
index 85fe307..0000000
--- a/engines/sludge/libvorbis/vorbis_misc.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/********************************************************************
- *                                                                  *
- * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE.   *
- * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS     *
- * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
- * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING.       *
- *                                                                  *
- * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2009             *
- * by the Xiph.Org Foundation http://www.xiph.org/                  *
- *                                                                  *
- ********************************************************************
-
- function: miscellaneous prototypes
- last mod: $Id: misc.h 16227 2009-07-08 06:58:46Z xiphmont $
-
- ********************************************************************/
-
-#ifndef _V_RANDOM_H_
-#define _V_RANDOM_H_
-#include "vorbis/codec.h"
-
-extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
-extern void _vorbis_block_ripcord(vorbis_block *vb);
-
-#ifdef ANALYSIS
-extern int analysis_noisy;
-extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
-                             ogg_int64_t off);
-extern void _analysis_output_always(char *base,int i,float *v,int n,int bark,int dB,
-                             ogg_int64_t off);
-#endif
-
-#ifdef DEBUG_MALLOC
-
-#define _VDBG_GRAPHFILE "malloc.m"
-#undef _VDBG_GRAPHFILE
-extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
-extern void _VDBG_free(void *ptr,char *file,long line);
-
-#ifndef MISC_C
-#undef _ogg_malloc
-#undef _ogg_calloc
-#undef _ogg_realloc
-#undef _ogg_free
-
-#define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
-#define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
-#define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
-#define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
-#endif
-#endif
-
-#endif
-
-
-
-
diff --git a/engines/sludge/libvorbis/vorbis_os.h b/engines/sludge/libvorbis/vorbis_os.h
deleted file mode 100644
index d12f082..0000000
--- a/engines/sludge/libvorbis/vorbis_os.h
+++ /dev/null
@@ -1,182 +0,0 @@
-#ifndef _OS_H
-#define _OS_H
-/********************************************************************
- *                                                                  *
- * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE.   *
- * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS     *
- * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
- * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING.       *
- *                                                                  *
- * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2009             *
- * by the Xiph.Org Foundation http://www.xiph.org/                  *
- *                                                                  *
- ********************************************************************
-
- function: #ifdef jail to whip a few platforms into the UNIX ideal.
- last mod: $Id: os.h 16227 2009-07-08 06:58:46Z xiphmont $
-
- ********************************************************************/
-
-#include <math.h>
-#include <ogg/os_types.h>
-
-#include "vorbis_misc.h"
-
-#ifndef _V_IFDEFJAIL_H_
-#  define _V_IFDEFJAIL_H_
-
-#  ifdef __GNUC__
-#    define STIN static __inline__
-#  elif _WIN32
-#    define STIN static __inline
-#  else
-#    define STIN static
-#  endif
-
-#ifdef DJGPP
-#  define rint(x)   (floor((x)+0.5f))
-#endif
-
-#ifndef M_PI
-#  define M_PI (3.1415926536f)
-#endif
-
-#if defined(_WIN32) && !defined(__SYMBIAN32__)
-#  include <malloc.h>
-#  define rint(x)   (floor((x)+0.5f))
-#  define NO_FLOAT_MATH_LIB
-#  define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
-#endif
-
-#if defined(__SYMBIAN32__) && defined(__WINS__)
-void *_alloca(size_t size);
-#  define alloca _alloca
-#endif
-
-#ifndef FAST_HYPOT
-#  define FAST_HYPOT hypot
-#endif
-
-#endif
-
-#ifdef HAVE_ALLOCA_H
-#  include <alloca.h>
-#endif
-
-#ifdef USE_MEMORY_H
-#  include <memory.h>
-#endif
-
-#ifndef min
-#  define min(x,y)  ((x)>(y)?(y):(x))
-#endif
-
-#ifndef max
-#  define max(x,y)  ((x)<(y)?(y):(x))
-#endif
-
-
-/* Special i386 GCC implementation */
-#if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
-#  define VORBIS_FPU_CONTROL
-/* both GCC and MSVC are kinda stupid about rounding/casting to int.
-   Because of encapsulation constraints (GCC can't see inside the asm
-   block and so we end up doing stupid things like a store/load that
-   is collectively a noop), we do it this way */
-
-/* we must set up the fpu before this works!! */
-
-typedef ogg_int16_t vorbis_fpu_control;
-
-static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
-  ogg_int16_t ret;
-  ogg_int16_t temp;
-  __asm__ __volatile__("fnstcw %0\n\t"
-          "movw %0,%%dx\n\t"
-          "andw $62463,%%dx\n\t"
-          "movw %%dx,%1\n\t"
-          "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
-  *fpu=ret;
-}
-
-static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
-  __asm__ __volatile__("fldcw %0":: "m"(fpu));
-}
-
-/* assumes the FPU is in round mode! */
-static inline int vorbis_ftoi(double f){  /* yes, double!  Otherwise,
-                                             we get extra fst/fld to
-                                             truncate precision */
-  int i;
-  __asm__("fistl %0": "=m"(i) : "t"(f));
-  return(i);
-}
-#endif /* Special i386 GCC implementation */
-
-
-/* MSVC inline assembly. 32 bit only; inline ASM isn't implemented in the
- * 64 bit compiler */
-#if defined(_MSC_VER) && !defined(_WIN64) && !defined(_WIN32_WCE)
-#  define VORBIS_FPU_CONTROL
-
-typedef ogg_int16_t vorbis_fpu_control;
-
-static __inline int vorbis_ftoi(double f){
-        int i;
-        __asm{
-                fld f
-                fistp i
-        }
-        return i;
-}
-
-static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
-}
-
-static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
-}
-
-#endif /* Special MSVC 32 bit implementation */
-
-
-/* Optimized code path for x86_64 builds. Uses SSE2 intrinsics. This can be
-   done safely because all x86_64 CPUs supports SSE2. */
-#if (defined(_MSC_VER) && defined(_WIN64)) || (defined(__GNUC__) && defined (__x86_64__))
-#  define VORBIS_FPU_CONTROL
-
-typedef ogg_int16_t vorbis_fpu_control;
-
-#include <emmintrin.h>
-static __inline int vorbis_ftoi(double f){
-        return _mm_cvtsd_si32(_mm_load_sd(&f));
-}
-
-static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
-}
-
-static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
-}
-
-#endif /* Special MSVC x64 implementation */
-
-
-/* If no special implementation was found for the current compiler / platform,
-   use the default implementation here: */
-#ifndef VORBIS_FPU_CONTROL
-
-typedef int vorbis_fpu_control;
-
-static int vorbis_ftoi(double f){
-        /* Note: MSVC and GCC (at least on some systems) round towards zero, thus,
-           the floor() call is required to ensure correct roudning of
-           negative numbers */
-        return (int)floor(f+.5);
-}
-
-/* We don't have special code for this compiler/arch, so do it the slow way */
-#  define vorbis_fpu_setround(vorbis_fpu_control) {}
-#  define vorbis_fpu_restore(vorbis_fpu_control) {}
-
-#endif /* default implementation */
-
-#endif /* _OS_H */
diff --git a/engines/sludge/libwebm/AUTHORS.TXT b/engines/sludge/libwebm/AUTHORS.TXT
deleted file mode 100644
index f5f8c11..0000000
--- a/engines/sludge/libwebm/AUTHORS.TXT
+++ /dev/null
@@ -1,5 +0,0 @@
-# Names should be added to this file like so:
-# Name or Organization <email address>
-
-Google Inc.
-Rikard Peterson <info at trumgottist.com>
diff --git a/engines/sludge/libwebm/LICENSE.TXT b/engines/sludge/libwebm/LICENSE.TXT
deleted file mode 100644
index 7a6f995..0000000
--- a/engines/sludge/libwebm/LICENSE.TXT
+++ /dev/null
@@ -1,30 +0,0 @@
-Copyright (c) 2010, Google Inc. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
-  * Redistributions of source code must retain the above copyright
-    notice, this list of conditions and the following disclaimer.
-
-  * Redistributions in binary form must reproduce the above copyright
-    notice, this list of conditions and the following disclaimer in
-    the documentation and/or other materials provided with the
-    distribution.
-
-  * Neither the name of Google nor the names of its contributors may
-    be used to endorse or promote products derived from this software
-    without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
diff --git a/engines/sludge/libwebm/PATENTS.TXT b/engines/sludge/libwebm/PATENTS.TXT
deleted file mode 100644
index 4414d83..0000000
--- a/engines/sludge/libwebm/PATENTS.TXT
+++ /dev/null
@@ -1,22 +0,0 @@
-Additional IP Rights Grant (Patents)
-
-"This implementation" means the copyrightable works distributed by
-Google as part of the WebM Project.
-
-Google hereby grants to you a perpetual, worldwide, non-exclusive,
-no-charge, royalty-free, irrevocable (except as stated in this section)
-patent license to make, have made, use, offer to sell, sell, import,
-transfer, and otherwise run, modify and propagate the contents of this
-implementation of VP8, where such license applies only to those patent
-claims, both currently owned by Google and acquired in the future,
-licensable by Google that are necessarily infringed by this
-implementation of VP8. This grant does not include claims that would be
-infringed only as a consequence of further modification of this
-implementation. If you or your agent or exclusive licensee institute or
-order or agree to the institution of patent litigation against any
-entity (including a cross-claim or counterclaim in a lawsuit) alleging
-that this implementation of VP8 or any code incorporated within this
-implementation of VP8 constitutes direct or contributory patent
-infringement, or inducement of patent infringement, then any patent
-rights granted to you under this License for this implementation of VP8
-shall terminate as of the date such litigation is filed.
diff --git a/engines/sludge/libwebm/mkvparser.cpp b/engines/sludge/libwebm/mkvparser.cpp
deleted file mode 100644
index 8a25af7..0000000
--- a/engines/sludge/libwebm/mkvparser.cpp
+++ /dev/null
@@ -1,7327 +0,0 @@
-// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
-//
-// Use of this source code is governed by a BSD-style license
-// that can be found in the LICENSE file in the root of the source
-// tree. An additional intellectual property rights grant can be found
-// in the file PATENTS.  All contributing project authors may
-// be found in the AUTHORS file in the root of the source tree.
-
-#include "mkvparser.hpp"
-#include <cassert>
-#include <cstring>
-#include <new>
-#include <climits>
-
-mkvparser::IMkvReader::~IMkvReader()
-{
-}
-
-void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision)
-{
-    major = 1;
-    minor = 0;
-    build = 0;
-    revision = 17;
-}
-
-long long mkvparser::ReadUInt(IMkvReader* pReader, long long pos, long& len)
-{
-    assert(pReader);
-    assert(pos >= 0);
-
-    int status;
-
-//#ifdef _DEBUG
-//    long long total, available;
-//    status = pReader->Length(&total, &available);
-//    assert(status >= 0);
-//    assert((total < 0) || (available <= total));
-//    assert(pos < available);
-//    assert((available - pos) >= 1);  //assume here max u-int len is 8
-//#endif
-
-    len = 1;
-
-    unsigned char b;
-
-    status = pReader->Read(pos, 1, &b);
-
-    if (status < 0)  //error or underflow
-        return status;
-
-    if (status > 0)  //interpreted as "underflow"
-        return E_BUFFER_NOT_FULL;
-
-    if (b == 0)  //we can't handle u-int values larger than 8 bytes
-        return E_FILE_FORMAT_INVALID;
-
-    unsigned char m = 0x80;
-
-    while (!(b & m))
-    {
-        m >>= 1;
-        ++len;
-    }
-
-//#ifdef _DEBUG
-//    assert((available - pos) >= len);
-//#endif
-
-    long long result = b & (~m);
-    ++pos;
-
-    for (int i = 1; i < len; ++i)
-    {
-        status = pReader->Read(pos, 1, &b);
-
-        if (status < 0)
-        {
-            len = 1;
-            return status;
-        }
-
-        if (status > 0)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        result <<= 8;
-        result |= b;
-
-        ++pos;
-    }
-
-    return result;
-}
-
-long long mkvparser::GetUIntLength(
-    IMkvReader* pReader,
-    long long pos,
-    long& len)
-{
-    assert(pReader);
-    assert(pos >= 0);
-
-    long long total, available;
-
-    int status = pReader->Length(&total, &available);
-    assert(status >= 0);
-    assert((total < 0) || (available <= total));
-
-    len = 1;
-
-    if (pos >= available)
-        return pos;  //too few bytes available
-
-    unsigned char b;
-
-    status = pReader->Read(pos, 1, &b);
-
-    if (status < 0)
-        return status;
-
-    assert(status == 0);
-
-    if (b == 0)  //we can't handle u-int values larger than 8 bytes
-        return E_FILE_FORMAT_INVALID;
-
-    unsigned char m = 0x80;
-
-    while (!(b & m))
-    {
-        m >>= 1;
-        ++len;
-    }
-
-    return 0;  //success
-}
-
-long long mkvparser::SyncReadUInt(
-    IMkvReader* pReader,
-    long long pos,
-    long long stop,
-    long& len)
-{
-    assert(pReader);
-
-    if (pos >= stop)
-        return E_FILE_FORMAT_INVALID;
-
-    unsigned char b;
-
-    long hr = pReader->Read(pos, 1, &b);
-
-    if (hr < 0)
-        return hr;
-
-    if (hr != 0L)
-        return E_BUFFER_NOT_FULL;
-
-    if (b == 0)  //we can't handle u-int values larger than 8 bytes
-        return E_FILE_FORMAT_INVALID;
-
-    unsigned char m = 0x80;
-    len = 1;
-
-    while (!(b & m))
-    {
-        m >>= 1;
-        ++len;
-    }
-
-    if ((pos + len) > stop)
-        return E_FILE_FORMAT_INVALID;
-
-    long long result = b & (~m);
-    ++pos;
-
-    for (int i = 1; i < len; ++i)
-    {
-        hr = pReader->Read(pos, 1, &b);
-
-        if (hr < 0)
-            return hr;
-
-        if (hr != 0L)
-            return E_BUFFER_NOT_FULL;
-
-        result <<= 8;
-        result |= b;
-
-        ++pos;
-    }
-
-    return result;
-}
-
-
-long long mkvparser::UnserializeUInt(
-    IMkvReader* pReader,
-    long long pos,
-    long long size)
-{
-    assert(pReader);
-    assert(pos >= 0);
-    assert(size > 0);
-    assert(size <= 8);
-
-    long long result = 0;
-
-    for (long long i = 0; i < size; ++i)
-    {
-        unsigned char b;
-
-        const long status = pReader->Read(pos, 1, &b);
-
-        if (status < 0)
-            return status;
-
-        result <<= 8;
-        result |= b;
-
-        ++pos;
-    }
-
-    return result;
-}
-
-
-float mkvparser::Unserialize4Float(
-    IMkvReader* pReader,
-    long long pos)
-{
-    assert(pReader);
-    assert(pos >= 0);
-
-#ifdef _DEBUG
-    {
-        long long total, available;
-
-        const long status = pReader->Length(&total, &available);
-        assert(status >= 0);
-        assert((total < 0) || (available <= total));
-        assert((pos + 4) <= available);
-    }
-#endif
-
-#if 0
-    float result;
-
-    unsigned char* const p = (unsigned char*)&result;
-    unsigned char* q = p + 4;
-
-    for (;;)
-    {
-        hr = pReader->Read(pos, 1, --q);
-        assert(hr == 0L);
-
-        if (q == p)
-            break;
-
-        ++pos;
-    }
-#else
-    union
-    {
-        float result;
-        unsigned long buf;
-    };
-
-    buf = 0;
-
-    for (int i = 0;;)
-    {
-        unsigned char b;
-
-        const int status = pReader->Read(pos++, 1, &b);
-
-        if (status < 0)  //error
-            return static_cast<float>(status);
-
-        buf |= b;
-
-        if (++i >= 4)
-            break;
-
-        buf <<= 8;
-    }
-#endif
-
-    return result;
-}
-
-
-double mkvparser::Unserialize8Double(
-    IMkvReader* pReader,
-    long long pos)
-{
-    assert(pReader);
-    assert(pos >= 0);
-
-#if 0
-    double result;
-
-    unsigned char* const p = (unsigned char*)&result;
-    unsigned char* q = p + 8;
-
-    for (;;)
-    {
-        const long hr = pReader->Read(pos, 1, --q);
-        assert(hr == 0L);
-
-        if (q == p)
-            break;
-
-        ++pos;
-    }
-#else
-    union
-    {
-        double result;
-        long long buf;
-    };
-
-    buf = 0;
-
-    for (int i = 0;;)
-    {
-        unsigned char b;
-
-        const int status = pReader->Read(pos++, 1, &b);
-
-        if (status < 0)  //error
-            return static_cast<double>(status);
-
-        buf |= b;
-
-        if (++i >= 8)
-            break;
-
-        buf <<= 8;
-    }
-#endif
-
-    return result;
-}
-
-signed char mkvparser::Unserialize1SInt(
-    IMkvReader* pReader,
-    long long pos)
-{
-    assert(pReader);
-    assert(pos >= 0);
-
-#ifdef _DEBUG
-    {
-        long long total, available;
-
-        const long status = pReader->Length(&total, &available);
-        assert(status == 0);
-        assert((total < 0) || (available <= total));
-        assert(pos < available);
-    }
-#endif
-
-    signed char result;
-    unsigned char& b = reinterpret_cast<unsigned char&>(result);
-
-    const int status = pReader->Read(pos, 1, &b);
-    assert(status == 0);  //TODO: must be handled somehow
-
-    return result;
-}
-
-short mkvparser::Unserialize2SInt(
-    IMkvReader* pReader,
-    long long pos)
-{
-    assert(pReader);
-    assert(pos >= 0);
-
-#ifdef _DEBUG
-    {
-        long long total, available;
-
-        const long status = pReader->Length(&total, &available);
-        assert(status >= 0);
-        assert((total < 0) || (available <= total));
-        assert((pos + 2) <= available);
-    }
-#endif
-
-#if 0
-    short result;
-
-    unsigned char* const p = (unsigned char*)&result;
-    unsigned char* q = p + 2;
-
-    for (;;)
-    {
-        hr = pReader->Read(pos, 1, --q);
-        assert(hr == 0L);
-
-        if (q == p)
-            break;
-
-        ++pos;
-    }
-#else
-    short result = 0;
-
-    for (int i = 0;;)
-    {
-        unsigned char b;
-
-        const int status = pReader->Read(pos++, 1, &b);
-        assert(status == 0);  //TODO: must be handled somehow
-
-        result |= b;
-
-        if (++i >= 2)
-            break;
-
-        result <<= 8;
-    }
-#endif
-
-    return result;
-}
-
-
-bool mkvparser::Match(
-    IMkvReader* pReader,
-    long long& pos,
-    unsigned long id_,
-    long long& val)
-{
-    assert(pReader);
-    assert(pos >= 0);
-
-    long long total, available;
-
-    const long status = pReader->Length(&total, &available);
-    assert(status >= 0);
-    assert((total < 0) || (available <= total));
-
-    long len;
-
-    const long long id = ReadUInt(pReader, pos, len);
-    assert(id >= 0);
-    assert(len > 0);
-    assert(len <= 8);
-    assert((pos + len) <= available);
-
-    if ((unsigned long)id != id_)
-        return false;
-
-    pos += len;  //consume id
-
-    const long long size = ReadUInt(pReader, pos, len);
-    assert(size >= 0);
-    assert(size <= 8);
-    assert(len > 0);
-    assert(len <= 8);
-    assert((pos + len) <= available);
-
-    pos += len;  //consume length of size of payload
-
-    val = UnserializeUInt(pReader, pos, size);
-    assert(val >= 0);
-
-    pos += size;  //consume size of payload
-
-    return true;
-}
-
-bool mkvparser::Match(
-    IMkvReader* pReader,
-    long long& pos,
-    unsigned long id_,
-    char*& val)
-{
-    assert(pReader);
-    assert(pos >= 0);
-
-    long long total, available;
-
-    long status = pReader->Length(&total, &available);
-    assert(status >= 0);
-    assert((total < 0) || (available <= total));
-
-    long len;
-
-    const long long id = ReadUInt(pReader, pos, len);
-    assert(id >= 0);
-    assert(len > 0);
-    assert(len <= 8);
-    assert((pos + len) <= available);
-
-    if ((unsigned long)id != id_)
-        return false;
-
-    pos += len;  //consume id
-
-    const long long size_ = ReadUInt(pReader, pos, len);
-    assert(size_ >= 0);
-    assert(len > 0);
-    assert(len <= 8);
-    assert((pos + len) <= available);
-
-    pos += len;  //consume length of size of payload
-    assert((pos + size_) <= available);
-
-    const size_t size = static_cast<size_t>(size_);
-    val = new char[size+1];
-
-    for (size_t i = 0; i < size; ++i)
-    {
-        char c;
-
-        status = pReader->Read(pos + i, 1, (unsigned char*)&c);
-        assert(status == 0);  //TODO
-
-        val[i] = c;
-
-        if (c == '\0')
-            break;
-    }
-
-    val[size] = '\0';
-    pos += size_;  //consume size of payload
-
-    return true;
-}
-
-bool mkvparser::Match(
-    IMkvReader* pReader,
-    long long& pos,
-    unsigned long id_,
-    unsigned char*& buf,
-    size_t& buflen)
-{
-    assert(pReader);
-    assert(pos >= 0);
-
-    long long total, available;
-
-    long status = pReader->Length(&total, &available);
-    assert(status >= 0);
-    assert((total < 0) || (available <= total));
-
-    long len;
-    const long long id = ReadUInt(pReader, pos, len);
-    assert(id >= 0);
-    assert(len > 0);
-    assert(len <= 8);
-    assert((pos + len) <= available);
-
-    if ((unsigned long)id != id_)
-        return false;
-
-    pos += len;  //consume id
-
-    const long long size_ = ReadUInt(pReader, pos, len);
-    assert(size_ >= 0);
-    assert(len > 0);
-    assert(len <= 8);
-    assert((pos + len) <= available);
-
-    pos += len;  //consume length of size of payload
-    assert((pos + size_) <= available);
-
-    const long buflen_ = static_cast<long>(size_);
-
-    buf = new (std::nothrow) unsigned char[buflen_];
-    assert(buf);  //TODO
-
-    status = pReader->Read(pos, buflen_, buf);
-    assert(status == 0);  //TODO
-
-    buflen = buflen_;
-
-    pos += size_;  //consume size of payload
-    return true;
-}
-
-
-bool mkvparser::Match(
-    IMkvReader* pReader,
-    long long& pos,
-    unsigned long id_,
-    double& val)
-{
-    assert(pReader);
-    assert(pos >= 0);
-
-    long long total, available;
-
-    const long status = pReader->Length(&total, &available);
-    assert(status >= 0);
-    assert((total < 0) || (available <= total));
-
-    long idlen;
-
-    const long long id = ReadUInt(pReader, pos, idlen);
-    assert(id >= 0);  //TODO
-
-    if ((unsigned long)id != id_)
-        return false;
-
-    long sizelen;
-    const long long size = ReadUInt(pReader, pos + idlen, sizelen);
-
-    switch (size)
-    {
-        case 4:
-        case 8:
-            break;
-        default:
-            return false;
-    }
-
-    pos += idlen + sizelen;  //consume id and size fields
-    assert((pos + size) <= available);
-
-    if (size == 4)
-        val = Unserialize4Float(pReader, pos);
-    else
-    {
-        assert(size == 8);
-        val = Unserialize8Double(pReader, pos);
-    }
-
-    pos += size;  //consume size of payload
-
-    return true;
-}
-
-
-bool mkvparser::Match(
-    IMkvReader* pReader,
-    long long& pos,
-    unsigned long id_,
-    short& val)
-{
-    assert(pReader);
-    assert(pos >= 0);
-
-    long long total, available;
-
-    const long status = pReader->Length(&total, &available);
-    assert(status >= 0);
-    assert((total < 0) || (available <= total));
-
-    long len;
-    const long long id = ReadUInt(pReader, pos, len);
-    assert(id >= 0);
-    assert((pos + len) <= available);
-
-    if ((unsigned long)id != id_)
-        return false;
-
-    pos += len;  //consume id
-
-    const long long size = ReadUInt(pReader, pos, len);
-    assert(size <= 2);
-    assert((pos + len) <= available);
-
-    pos += len;  //consume length of size of payload
-    assert((pos + size) <= available);
-
-    //TODO:
-    // Generalize this to work for any size signed int
-    if (size == 1)
-        val = Unserialize1SInt(pReader, pos);
-    else
-        val = Unserialize2SInt(pReader, pos);
-
-    pos += size;  //consume size of payload
-
-    return true;
-}
-
-
-namespace mkvparser
-{
-
-EBMLHeader::EBMLHeader() :
-    m_docType(NULL)
-{
-    Init();
-}
-
-EBMLHeader::~EBMLHeader()
-{
-    delete[] m_docType;
-}
-
-void EBMLHeader::Init()
-{
-    m_version = 1;
-    m_readVersion = 1;
-    m_maxIdLength = 4;
-    m_maxSizeLength = 8;
-
-    if (m_docType)
-    {
-        delete[] m_docType;
-        m_docType = NULL;
-    }
-
-    m_docTypeVersion = 1;
-    m_docTypeReadVersion = 1;
-}
-
-long long EBMLHeader::Parse(
-    IMkvReader* pReader,
-    long long& pos)
-{
-    assert(pReader);
-
-    long long total, available;
-
-    long status = pReader->Length(&total, &available);
-
-    if (status < 0)  //error
-        return status;
-
-    pos = 0;
-    long long end = (available >= 1024) ? 1024 : available;
-
-    for (;;)
-    {
-        unsigned char b = 0;
-
-        while (pos < end)
-        {
-            status = pReader->Read(pos, 1, &b);
-
-            if (status < 0)  //error
-                return status;
-
-            if (b == 0x1A)
-                break;
-
-            ++pos;
-        }
-
-        if (b != 0x1A)
-        {
-            if (pos >= 1024)
-                return E_FILE_FORMAT_INVALID;  //don't bother looking anymore
-
-            if ((total >= 0) && ((total - available) < 5))
-                return E_FILE_FORMAT_INVALID;
-
-            return available + 5;  //5 = 4-byte ID + 1st byte of size
-        }
-
-        if ((total >= 0) && ((total - pos) < 5))
-            return E_FILE_FORMAT_INVALID;
-
-        if ((available - pos) < 5)
-            return pos + 5;  //try again later
-
-        long len;
-
-        const long long result = ReadUInt(pReader, pos, len);
-
-        if (result < 0)  //error
-            return result;
-
-        if (result == 0x0A45DFA3)  //EBML Header ID
-        {
-            pos += len;  //consume ID
-            break;
-        }
-
-        ++pos;  //throw away just the 0x1A byte, and try again
-    }
-
-    //pos designates start of size field
-
-    //get length of size field
-
-    long len;
-    long long result = GetUIntLength(pReader, pos, len);
-
-    if (result < 0)  //error
-        return result;
-
-    if (result > 0)  //need more data
-        return result;
-
-    assert(len > 0);
-    assert(len <= 8);
-
-    if ((total >= 0) && ((total -  pos) < len))
-        return E_FILE_FORMAT_INVALID;
-
-    if ((available - pos) < len)
-        return pos + len;  //try again later
-
-    //get the EBML header size
-
-    result = ReadUInt(pReader, pos, len);
-
-    if (result < 0)  //error
-        return result;
-
-    pos += len;  //consume size field
-
-    //pos now designates start of payload
-
-    if ((total >= 0) && ((total - pos) < result))
-        return E_FILE_FORMAT_INVALID;
-
-    if ((available - pos) < result)
-        return pos + result;
-
-    end = pos + result;
-
-    Init();
-
-    while (pos < end)
-    {
-        if (Match(pReader, pos, 0x0286, m_version))
-            ;
-        else if (Match(pReader, pos, 0x02F7, m_readVersion))
-            ;
-        else if (Match(pReader, pos, 0x02F2, m_maxIdLength))
-            ;
-        else if (Match(pReader, pos, 0x02F3, m_maxSizeLength))
-            ;
-        else if (Match(pReader, pos, 0x0282, m_docType))
-            ;
-        else if (Match(pReader, pos, 0x0287, m_docTypeVersion))
-            ;
-        else if (Match(pReader, pos, 0x0285, m_docTypeReadVersion))
-            ;
-        else
-        {
-            result = ReadUInt(pReader, pos, len);
-            assert(result > 0);
-            assert(len > 0);
-            assert(len <= 8);
-
-            pos += len;
-            assert(pos < end);
-
-            result = ReadUInt(pReader, pos, len);
-            assert(result >= 0);
-            assert(len > 0);
-            assert(len <= 8);
-
-            pos += len + result;
-            assert(pos <= end);
-        }
-    }
-
-    assert(pos == end);
-    return 0;
-}
-
-
-Segment::Segment(
-    IMkvReader* pReader,
-    long long start,
-    long long size) :
-    m_pReader(pReader),
-    m_start(start),
-    m_size(size),
-    m_pos(start),
-    m_pSeekHead(NULL),
-    m_pInfo(NULL),
-    m_pTracks(NULL),
-    m_pCues(NULL),
-    m_clusters(NULL),
-    m_clusterCount(0),
-    m_clusterPreloadCount(0),
-    m_clusterSize(0)
-{
-}
-
-
-Segment::~Segment()
-{
-    const long count = m_clusterCount + m_clusterPreloadCount;
-
-    Cluster** i = m_clusters;
-    Cluster** j = m_clusters + count;
-
-    while (i != j)
-    {
-        Cluster* const p = *i++;
-        assert(p);
-
-        delete p;
-    }
-
-    delete[] m_clusters;
-
-    delete m_pTracks;
-    delete m_pInfo;
-    delete m_pCues;
-    delete m_pSeekHead;
-}
-
-
-long long Segment::CreateInstance(
-    IMkvReader* pReader,
-    long long pos,
-    Segment*& pSegment)
-{
-    assert(pReader);
-    assert(pos >= 0);
-
-    pSegment = NULL;
-
-    long long total, available;
-
-    const long status = pReader->Length(&total, &available);
-	
-//	fprintf(stderr, "status: %d total: %d available: %d\n", status, total, available);
-
-    if (status < 0) //error
-        return status;
-
-    if (available < 0)
-        return -1;
-
-    if ((total >= 0) && (available > total))
-        return -1;
-
-    const long long end = (total >= 0) ? total : available;
-    //TODO: this might need to be liberalized
-
-    //I would assume that in practice this loop would execute
-    //exactly once, but we allow for other elements (e.g. Void)
-    //to immediately follow the EBML header.  This is fine for
-    //the source filter case (since the entire file is available),
-    //but in the splitter case over a network we should probably
-    //just give up early.  We could for example decide only to
-    //execute this loop a maximum of, say, 10 times.
-    //TODO:
-    //There is an implied "give up early" by only parsing up
-    //to the available limit.  We do do that, but only if the
-    //total file size is unknown.  We could decide to always
-    //use what's available as our limit (irrespective of whether
-    //we happen to know the total file length).  This would have
-    //as its sense "parse this much of the file before giving up",
-    //which a slightly different sense from "try to parse up to
-    //10 EMBL elements before giving up".
-
-    while (pos < end)
-    {
-        //Read ID
-
-        long len;
-        long long result = GetUIntLength(pReader, pos, len);
-
-        if (result)  //error, or too few available bytes
-            return result;
-
-        if ((pos + len) > end)
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > available)
-            return pos + len;
-
-        const long long id = ReadUInt(pReader, pos, len);
-
-        if (id < 0)  //error
-            return id;
-
-        pos += len;  //consume ID
-
-        //Read Size
-
-        result = GetUIntLength(pReader, pos, len);
-
-        if (result)  //error, or too few available bytes
-            return result;
-
-        if ((pos + len) > end)
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > available)
-            return pos + len;
-
-        long long size = ReadUInt(pReader, pos, len);
-
-        if (size < 0)  //error
-            return size;
-
-        pos += len;  //consume length of size of element
-
-        //Pos now points to start of payload
-
-        //Handle "unknown size" for live streaming of webm files.
-        const long long unknown_size = (1LL << (7 * len)) - 1;
-
-        if (id == 0x08538067)  //Segment ID
-        {
-            if (size == unknown_size)
-                size = -1;
-
-            else if (total < 0)
-                size = -1;
-
-            else if ((pos + size) > end)
-                return E_FILE_FORMAT_INVALID;
-
-            pSegment = new (std::nothrow) Segment(pReader, pos, size);
-
-            if (pSegment == 0)
-                return -1;  //generic error
-
-            return 0;    //success
-        }
-
-        if (size == unknown_size)
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + size) > end)
-            return E_FILE_FORMAT_INVALID;
-
-        pos += size;  //consume payload
-    }
-
-    return E_FILE_FORMAT_INVALID;  //there is no segment
-    //TODO: this might need to be liberalized.  See comments above.
-}
-
-
-long long Segment::ParseHeaders()
-{
-    //Outermost (level 0) segment object has been constructed,
-    //and pos designates start of payload.  We need to find the
-    //inner (level 1) elements.
-    long long total, available;
-
-    const int status = m_pReader->Length(&total, &available);
-    assert(status == 0);
-    assert((total < 0) || (available <= total));
-
-    const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
-    assert((segment_stop < 0) || (total < 0) || (segment_stop <= total));
-    assert((segment_stop < 0) || (m_pos <= segment_stop));
-
-    for (;;)
-    {
-        if ((total >= 0) && (m_pos >= total))
-            break;
-
-        if ((segment_stop >= 0) && (m_pos >= segment_stop))
-            break;
-
-        long long pos = m_pos;
-        const long long element_start = pos;
-
-        if ((pos + 1) > available)
-            return (pos + 1);
-
-        long len;
-        long long result = GetUIntLength(m_pReader, pos, len);
-
-        if (result < 0)  //error
-            return result;
-
-        if (result > 0)  //underflow (weird)
-            return (pos + 1);
-
-        if ((segment_stop >= 0) && ((pos + len) > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > available)
-            return pos + len;
-
-        const long long idpos = pos;
-        const long long id = ReadUInt(m_pReader, idpos, len);
-
-        if (id < 0)  //error
-            return id;
-
-        if (id == 0x0F43B675)  //Cluster ID
-            break;
-
-        pos += len;  //consume ID
-
-        if ((pos + 1) > available)
-            return (pos + 1);
-
-        //Read Size
-        result = GetUIntLength(m_pReader, pos, len);
-
-        if (result < 0)  //error
-            return result;
-
-        if (result > 0)  //underflow (weird)
-            return (pos + 1);
-
-        if ((segment_stop >= 0) && ((pos + len) > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > available)
-            return pos + len;
-
-        const long long size = ReadUInt(m_pReader, pos, len);
-
-        if (size < 0)  //error
-            return size;
-
-        pos += len;  //consume length of size of element
-
-        const long long element_size = size + pos - element_start;
-
-        //Pos now points to start of payload
-
-        if ((segment_stop >= 0) && ((pos + size) > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-        //We read EBML elements either in total or nothing at all.
-
-        if ((pos + size) > available)
-            return pos + size;
-
-        if (id == 0x0549A966)  //Segment Info ID
-        {
-            assert(m_pInfo == NULL);
-
-            m_pInfo = new SegmentInfo(this,
-                                      pos,
-                                      size,
-                                      element_start,
-                                      element_size);
-            assert(m_pInfo);  //TODO
-        }
-        else if (id == 0x0654AE6B)  //Tracks ID
-        {
-            assert(m_pTracks == NULL);
-
-            m_pTracks = new Tracks(this,
-                                   pos,
-                                   size,
-                                   element_start,
-                                   element_size);
-            assert(m_pTracks);  //TODO
-        }
-        else if (id == 0x0C53BB6B)  //Cues ID
-        {
-            if (m_pCues == NULL)
-            {
-                m_pCues = new Cues(this,
-                                   pos,
-                                   size,
-                                   element_start,
-                                   element_size);
-                assert(m_pCues);  //TODO
-            }
-        }
-        else if (id == 0x014D9B74)  //SeekHead ID
-        {
-#if 0
-            if (available >= total)
-                ParseSeekHead(pos, size);
-#else
-            if (m_pSeekHead == NULL)
-            {
-                m_pSeekHead = new SeekHead(this,
-                                           pos,
-                                           size,
-                                           element_start,
-                                           element_size);
-
-                assert(m_pSeekHead);  //TODO
-            }
-#endif
-        }
-
-        m_pos = pos + size;  //consume payload
-    }
-
-    assert((segment_stop < 0) || (m_pos <= segment_stop));
-
-    if (m_pInfo == NULL)  //TODO: liberalize this behavior
-        return E_FILE_FORMAT_INVALID;
-
-    if (m_pTracks == NULL)
-        return E_FILE_FORMAT_INVALID;
-
-    return 0;  //success
-}
-
-
-#if 0
-long Segment::FindNextCluster(long long& pos, size& len) const
-{
-    //Outermost (level 0) segment object has been constructed,
-    //and pos designates start of payload.  We need to find the
-    //inner (level 1) elements.
-    long long total, available;
-
-    const int status = m_pReader->Length(&total, &available);
-    assert(status == 0);
-    assert(total >= 0);
-    assert(available <= total);
-
-    const long long stop = m_start + m_size;
-    assert(stop <= total);
-    assert(m_pos <= stop);
-
-    pos = m_pos;
-
-    while (pos < stop)
-    {
-        long long result = GetUIntLength(m_pReader, pos, len);
-
-        if (result < 0)
-            return static_cast<long>(result);
-
-        if (result > 0)
-            return E_BUFFER_NOT_FULL;
-
-        if ((pos + len) > stop)
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > available)
-            return E_BUFFER_NOT_FULL;
-
-        const long long idpos = pos;
-        const long long id = ReadUInt(m_pReader, idpos, len);
-
-        if (id < 0)  //error
-            return static_cast<long>(id);
-
-        pos += len;  //consume ID
-
-        //Read Size
-        result = GetUIntLength(m_pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if (result > 0)
-            return E_BUFFER_NOT_FULL;
-
-        if ((pos + len) > stop)
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > available)
-            return E_BUFFER_NOT_FULL;
-
-        const long long size = ReadUInt(m_pReader, pos, len);
-
-        if (size < 0)  //error
-            return static_cast<long>(size);
-
-        pos += len;  //consume length of size of element
-
-        //Pos now points to start of payload
-
-        if ((pos + size) > stop)
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + size) > available)
-            return E_BUFFER_NOT_FULL;
-
-        if (id == 0x0F43B675)  //Cluster ID
-        {
-            len = static_cast<long>(size);
-            return 0;  //success
-        }
-
-        pos += size;  //consume payload
-    }
-
-    return E_FILE_FORMAT_INVALID;
-}
-#endif
-
-
-#if 0
-long Segment::ParseCluster(long long& off, long long& new_pos) const
-{
-    off = -1;
-    new_pos = -1;
-
-    const long long stop = m_start + m_size;
-    assert(m_pos <= stop);
-
-    long long pos = m_pos;
-
-    while (pos < stop)
-    {
-        long len;
-        const long long idpos = pos;
-
-        const long long id = SyncReadUInt(m_pReader, pos, stop, len);
-
-        if (id < 0)  //error
-            return static_cast<long>(id);
-
-        if (id == 0)
-            return E_FILE_FORMAT_INVALID;
-
-        pos += len;  //consume id
-        assert(pos < stop);
-
-        const long long size = SyncReadUInt(m_pReader, pos, stop, len);
-
-        if (size < 0)  //error
-            return static_cast<long>(size);
-
-        pos += len;  //consume size
-        assert(pos <= stop);
-
-        if (size == 0)  //weird
-            continue;
-
-        //pos now points to start of payload
-
-        pos += size;  //consume payload
-        assert(pos <= stop);
-
-        if (id == 0x0F43B675)  //Cluster ID
-        {
-            const long long off_ = idpos - m_start;
-
-            if (Cluster::HasBlockEntries(this, off_))
-            {
-                off = off_;   // >= 0 means we found a cluster
-                break;
-            }
-        }
-    }
-
-    assert(pos <= stop);
-
-    //Indicate to caller how much of file has been consumed. This is
-    //used later in AddCluster to adjust the current parse position
-    //(the value cached in the segment object itself) to the
-    //file position value just past the cluster we parsed.
-
-    if (off < 0)  //we did not found any more clusters
-    {
-        new_pos = stop;  //pos >= 0 here means EOF (cluster is NULL)
-        return 0;        //TODO: confirm this return value
-    }
-
-    //We found a cluster.  Now read something, to ensure that it is
-    //fully loaded in the network cache.
-
-    if (pos >= stop)  //we parsed the entire segment
-    {
-        //We did find a cluster, but it was very last element in the segment.
-        //Our preference is that the loop above runs 1 1/2 times:
-        //the first pass finds the cluster, and the second pass
-        //finds the element the follows the cluster.  In this case, however,
-        //we reached the end of the file without finding another element,
-        //so we didn't actually read anything yet associated with "end of the
-        //cluster".  And we must perform an actual read, in order
-        //to guarantee that all of the data that belongs to this
-        //cluster has been loaded into the network cache.  So instead
-        //of reading the next element that follows the cluster, we
-        //read the last byte of the cluster (which is also the last
-        //byte in the file).
-
-        //Read the last byte of the file. (Reading 0 bytes at pos
-        //might work too -- it would depend on how the reader is
-        //implemented.  Here we take the more conservative approach,
-        //since this makes fewer assumptions about the network
-        //reader abstraction.)
-
-        unsigned char b;
-
-        const int result = m_pReader->Read(pos - 1, 1, &b);
-        assert(result == 0);
-
-        new_pos = stop;
-    }
-    else
-    {
-        long len;
-        const long long idpos = pos;
-
-        const long long id = SyncReadUInt(m_pReader, pos, stop, len);
-
-        if (id < 0)  //error
-            return static_cast<long>(id);
-
-        if (id == 0)
-            return E_BUFFER_NOT_FULL;
-
-        pos += len;  //consume id
-        assert(pos < stop);
-
-        const long long size = SyncReadUInt(m_pReader, pos, stop, len);
-
-        if (size < 0)  //error
-            return static_cast<long>(size);
-
-        new_pos = idpos;
-    }
-
-    return 0;
-}
-
-
-bool Segment::AddCluster(long long off, long long pos)
-{
-    assert(pos >= m_start);
-
-    const long long stop = m_start + m_size;
-    assert(pos <= stop);
-
-    if (off >= 0)
-    {
-        Cluster* const pCluster = Cluster::Parse(this,
-                                                 m_clusterCount,
-                                                 off,
-                                                 0,
-                                                 0);
-        assert(pCluster);
-
-        AppendCluster(pCluster);
-        assert(m_clusters);
-        assert(m_clusterSize > pCluster->m_index);
-        assert(m_clusters[pCluster->m_index] == pCluster);
-    }
-
-    m_pos = pos;  //m_pos >= stop is now we know we have all clusters
-    return (pos >= stop);
-}
-#endif
-
-
-long Segment::LoadCluster(
-    long long& pos,
-    long& len)
-{
-    long long total, avail;
-
-    long status = m_pReader->Length(&total, &avail);
-
-    if (status < 0)  //error
-        return status;
-
-    assert((total < 0) || (avail <= total));
-
-    const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
-
-    for (;;)
-    {
-        if ((total >= 0) && (m_pos >= total))
-            return 1;  //no more clusters
-
-        if ((segment_stop >= 0) && (m_pos >= segment_stop))
-            return 1;  //no more clusters
-
-        pos = m_pos;
-
-        //Read ID
-
-        if ((pos + 1) > avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        long long result = GetUIntLength(m_pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if (result > 0)  //weird
-            return E_BUFFER_NOT_FULL;
-
-        if ((segment_stop >= 0) && ((pos + len) > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > avail)
-            return E_BUFFER_NOT_FULL;
-
-        const long long idpos = pos;
-        const long long id = ReadUInt(m_pReader, idpos, len);
-
-        if (id < 0)  //error (or underflow)
-            return static_cast<long>(id);
-
-        pos += len;  //consume ID
-
-        //Read Size
-
-        if ((pos + 1) > avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        result = GetUIntLength(m_pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if (result > 0)  //weird
-            return E_BUFFER_NOT_FULL;
-
-        if ((segment_stop >= 0) && ((pos + len) > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > avail)
-            return E_BUFFER_NOT_FULL;
-
-        const long long size = ReadUInt(m_pReader, pos, len);
-
-        if (size < 0)  //error
-            return static_cast<long>(size);
-
-        const long long unknown_size = (1LL << (7 * len)) - 1;
-
-        if (size == unknown_size)
-            return E_FILE_FORMAT_INVALID;  //TODO: allow this
-
-        pos += len;  //consume length of size of element
-
-        const long long element_size = size + pos - idpos;
-
-        if (size == 0)  //weird
-        {
-            m_pos = pos;
-            continue;
-        }
-
-        //Pos now points to start of payload
-
-        if ((segment_stop >= 0) && ((pos + size) > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-#if 0
-        len = static_cast<long>(size);
-
-        if ((pos + size) > avail)
-            return E_BUFFER_NOT_FULL;
-#endif
-
-        if (id == 0x0C53BB6B)  //Cues ID
-        {
-            if (m_pCues == NULL)
-            {
-                m_pCues = new Cues(this,
-                                   pos,
-                                   size,
-                                   idpos,
-                                   element_size);
-                assert(m_pCues);  //TODO
-            }
-
-            m_pos = pos + size;  //consume payload
-            continue;
-        }
-
-        if (id != 0x0F43B675)  //Cluster ID
-        {
-            m_pos = pos + size;  //consume payload
-            continue;
-        }
-
-        const long idx = m_clusterCount;
-        const long long idoff = idpos - m_start;
-
-        long long pos_;
-        long len_;
-
-        status = Cluster::HasBlockEntries(this, idoff, pos_, len_);
-
-        if (status < 0) //error, or underflow
-        {
-            pos = pos_;
-            len = len_;
-
-            return status;
-        }
-
-        if (m_clusterPreloadCount > 0)
-        {
-            assert(idx < m_clusterSize);
-
-            Cluster* const pCluster = m_clusters[idx];
-            assert(pCluster);
-            assert(pCluster->m_index < 0);
-
-            //const long long off_ = pCluster->m_pos;
-            //assert(off_);
-            //const long long off = off_ * ((off_ >= 0) ? 1 : -1);
-            //assert(idoff <= off);
-
-            const long long off = pCluster->GetPosition();
-            assert(off >= 0);
-
-            if (idoff == off)  //preloaded already
-            {
-                if (status == 0)  //no block entries
-                    return E_FILE_FORMAT_INVALID;
-
-                pCluster->m_index = idx;  //move from preloaded to loaded
-                ++m_clusterCount;
-                --m_clusterPreloadCount;
-
-                m_pos = pos + size;  //consume payload
-                assert((segment_stop < 0) || (m_pos <= segment_stop));
-#if 0
-                status = pCluster->Load(pos, len);  //set size and timecode
-                assert(status == 0);  //TODO
-#endif
-                return 0;  //success
-            }
-        }
-
-        m_pos = pos + size;  //consume payload
-        assert((segment_stop < 0) || (m_pos <= segment_stop));
-
-        if (status == 0)  //no block entries
-            continue;
-
-        Cluster* const pCluster = Cluster::Create(this,
-                                                  idx,
-                                                  idoff,
-                                                  element_size);
-        assert(pCluster);
-
-        AppendCluster(pCluster);
-        assert(m_clusters);
-        assert(idx < m_clusterSize);
-        assert(m_clusters[idx] == pCluster);
-#if 0
-        status = pCluster->Load(pos, len);
-        assert(status == 0);  //TODO
-#endif
-        return 0;
-    }
-}
-
-
-void Segment::AppendCluster(Cluster* pCluster)
-{
-    assert(pCluster);
-    assert(pCluster->m_index >= 0);
-
-    const long count = m_clusterCount + m_clusterPreloadCount;
-
-    long& size = m_clusterSize;
-    assert(size >= count);
-
-    const long idx = pCluster->m_index;
-    assert(idx == m_clusterCount);
-
-    if (count >= size)
-    {
-        long n;
-
-        if (size > 0)
-            n = 2 * size;
-        else if (m_pInfo == 0)
-            n = 2048;
-        else
-        {
-            const long long ns = m_pInfo->GetDuration();
-
-            if (ns <= 0)
-                n = 2048;
-            else
-            {
-                const long long sec = (ns + 999999999LL) / 1000000000LL;
-                n = static_cast<long>(sec);
-            }
-        }
-
-        Cluster** const qq = new Cluster*[n];
-        Cluster** q = qq;
-
-        Cluster** p = m_clusters;
-        Cluster** const pp = p + count;
-
-        while (p != pp)
-            *q++ = *p++;
-
-        delete[] m_clusters;
-
-        m_clusters = qq;
-        size = n;
-    }
-
-    if (m_clusterPreloadCount > 0)
-    {
-        assert(m_clusters);
-
-        Cluster** const p = m_clusters + m_clusterCount;
-        assert(*p);
-        assert((*p)->m_index < 0);
-
-        Cluster** q = p + m_clusterPreloadCount;
-        assert(q < (m_clusters + size));
-
-        for (;;)
-        {
-            Cluster** const qq = q - 1;
-            assert((*qq)->m_index < 0);
-
-            *q = *qq;
-            q = qq;
-
-            if (q == p)
-                break;
-        }
-    }
-
-    m_clusters[idx] = pCluster;
-    ++m_clusterCount;
-}
-
-
-void Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx)
-{
-    assert(pCluster);
-    assert(pCluster->m_index < 0);
-    assert(idx >= m_clusterCount);
-
-    const long count = m_clusterCount + m_clusterPreloadCount;
-
-    long& size = m_clusterSize;
-    assert(size >= count);
-
-    if (count >= size)
-    {
-        long n;
-
-        if (size > 0)
-            n = 2 * size;
-        else if (m_pInfo == 0)
-            n = 2048;
-        else
-        {
-            const long long ns = m_pInfo->GetDuration();
-
-            if (ns <= 0)
-                n = 2048;
-            else
-            {
-                const long long sec = (ns + 999999999LL) / 1000000000LL;
-                n = static_cast<long>(sec);
-            }
-        }
-
-        Cluster** const qq = new Cluster*[n];
-        Cluster** q = qq;
-
-        Cluster** p = m_clusters;
-        Cluster** const pp = p + count;
-
-        while (p != pp)
-            *q++ = *p++;
-
-        delete[] m_clusters;
-
-        m_clusters = qq;
-        size = n;
-    }
-
-    assert(m_clusters);
-
-    Cluster** const p = m_clusters + idx;
-
-    Cluster** q = m_clusters + count;
-    assert(q >= p);
-    assert(q < (m_clusters + size));
-
-    while (q > p)
-    {
-        Cluster** const qq = q - 1;
-        assert((*qq)->m_index < 0);
-
-        *q = *qq;
-        q = qq;
-    }
-
-    m_clusters[idx] = pCluster;
-    ++m_clusterPreloadCount;
-}
-
-
-long Segment::Load()
-{
-    assert(m_clusters == NULL);
-    assert(m_clusterSize == 0);
-    assert(m_clusterCount == 0);
-    //assert(m_size >= 0);
-
-    //Outermost (level 0) segment object has been constructed,
-    //and pos designates start of payload.  We need to find the
-    //inner (level 1) elements.
-
-    long long total, avail;
-
-    long status = m_pReader->Length(&total, &avail);
-
-    if (status < 0)  //error
-        return status;
-
-    assert((total < 0) || (avail <= total));
-
-    const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
-
-    for (;;)
-    {
-        long long pos = m_pos;
-
-        if ((total >= 0) && (pos >= total))
-            break;
-
-        if ((segment_stop >= 0) && (pos >= segment_stop))
-            break;
-
-        const long long element_start = pos;
-
-        long len;
-
-        long long result = GetUIntLength(m_pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if ((segment_stop >= 0) && ((pos + len) > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-        const long long idpos = pos;
-        const long long id = ReadUInt(m_pReader, idpos, len);
-
-        if (id < 0)  //error
-            return static_cast<long>(id);
-
-        pos += len;  //consume ID
-
-        //Read Size
-        result = GetUIntLength(m_pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if ((segment_stop >= 0) && ((pos + len) > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-        const long long size = ReadUInt(m_pReader, pos, len);
-
-        if (size < 0)  //error
-            return static_cast<long>(size);
-
-        const long long unknown_size = (1LL << (7 * len)) - 1;
-
-        if (size == unknown_size)
-            return E_FILE_FORMAT_INVALID;
-
-        pos += len;  //consume length of size of element
-
-        //Pos now points to start of payload
-
-        const long long element_size = (pos - element_start) + size;
-
-        if ((segment_stop >= 0) && ((pos + size) > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-        if (id == 0x0F43B675)  //Cluster ID
-        {
-            const long idx = m_clusterCount;
-            const long long off = idpos - m_start;
-
-            long long pos_;
-            long len_;
-
-            status = Cluster::HasBlockEntries(this, off, pos_, len_);
-
-            if (status < 0)  //weird: error or underflow
-                return status;
-
-            if (status > 0)  //have block entries
-            {
-                Cluster* const pCluster = Cluster::Create(this,
-                                                         idx,
-                                                         off,
-                                                         element_size);
-                assert(pCluster);
-
-                AppendCluster(pCluster);
-                assert(m_clusters);
-                assert(m_clusterSize > idx);
-                assert(m_clusters[idx] == pCluster);
-            }
-        }
-        else if (id == 0x0C53BB6B)  //Cues ID
-        {
-            assert(m_pCues == NULL);
-
-            m_pCues = new Cues(this, pos, size, element_start, element_size);
-            assert(m_pCues);  //TODO
-        }
-        else if (id == 0x0549A966)  //SegmentInfo ID
-        {
-            assert(m_pInfo == NULL);
-
-            m_pInfo = new SegmentInfo(this,
-                                      pos,
-                                      size,
-                                      element_start,
-                                      element_size);
-            assert(m_pInfo);
-        }
-        else if (id == 0x0654AE6B)  //Tracks ID
-        {
-            assert(m_pTracks == NULL);
-
-            m_pTracks = new Tracks(this,
-                                   pos,
-                                   size,
-                                   element_start,
-                                   element_size);
-            assert(m_pTracks);  //TODO
-        }
-
-        m_pos = pos + size;  //consume payload
-    }
-
-    if (m_pInfo == NULL)
-        return E_FILE_FORMAT_INVALID;  //TODO: ignore this case?
-
-    if (m_pTracks == NULL)
-        return E_FILE_FORMAT_INVALID;
-
-    if (m_clusters == NULL)  //TODO: ignore this case?
-        return E_FILE_FORMAT_INVALID;
-
-    return 0;
-}
-
-
-#if 0
-void Segment::ParseSeekHead(long long start, long long size_)
-{
-    long long pos = start;
-    const long long stop = start + size_;
-
-    while (pos < stop)
-    {
-        long len;
-
-        const long long id = ReadUInt(m_pReader, pos, len);
-        assert(id >= 0);  //TODO
-        assert((pos + len) <= stop);
-
-        pos += len;  //consume ID
-
-        const long long size = ReadUInt(m_pReader, pos, len);
-        assert(size >= 0);
-        assert((pos + len) <= stop);
-
-        pos += len;  //consume Size field
-        assert((pos + size) <= stop);
-
-        if (id == 0x0DBB)  //SeekEntry ID
-            ParseSeekEntry(pos, size);
-
-        pos += size;  //consume payload
-        assert(pos <= stop);
-    }
-
-    assert(pos == stop);
-}
-#else
-SeekHead::SeekHead(
-    Segment* pSegment,
-    long long start,
-    long long size_,
-    long long element_start,
-    long long element_size) :
-    m_pSegment(pSegment),
-    m_start(start),
-    m_size(size_),
-    m_element_start(element_start),
-    m_element_size(element_size),
-    m_entries(0),
-    m_count(0)
-{
-    long long pos = start;
-    const long long stop = start + size_;
-
-    IMkvReader* const pReader = m_pSegment->m_pReader;
-
-    //first count the seek head entries
-
-    int count = 0;
-
-    while (pos < stop)
-    {
-        long len;
-
-        const long long id = ReadUInt(pReader, pos, len);
-        assert(id >= 0);  //TODO
-        assert((pos + len) <= stop);
-
-        pos += len;  //consume ID
-
-        const long long size = ReadUInt(pReader, pos, len);
-        assert(size >= 0);
-        assert((pos + len) <= stop);
-
-        pos += len;  //consume Size field
-        assert((pos + size) <= stop);
-
-        if (id == 0x0DBB)  //SeekEntry ID
-            ++count;
-
-        pos += size;  //consume payload
-        assert(pos <= stop);
-    }
-
-    assert(pos == stop);
-
-    if (count <= 0)
-        return;  //nothing else for us to do
-
-    m_entries = new (std::nothrow) Entry[count];
-    assert(m_entries);  //TODO
-
-    //now parse the entries
-
-    Entry* pEntry = m_entries;
-    pos = start;
-
-    while (pos < stop)
-    {
-        long len;
-
-        const long long id = ReadUInt(pReader, pos, len);
-        assert(id >= 0);  //TODO
-        assert((pos + len) <= stop);
-
-        pos += len;  //consume ID
-
-        const long long size = ReadUInt(pReader, pos, len);
-        assert(size >= 0);
-        assert((pos + len) <= stop);
-
-        pos += len;  //consume Size field
-        assert((pos + size) <= stop);
-
-        if (id == 0x0DBB)  //SeekEntry ID
-            ParseEntry(pReader, pos, size, pEntry);
-
-        pos += size;  //consume payload
-        assert(pos <= stop);
-    }
-
-    assert(pos == stop);
-
-    const ptrdiff_t count_ = ptrdiff_t(pEntry - m_entries);
-    assert(count_ >= 0);
-    assert(count_ <= count);
-
-    m_count = static_cast<int>(count_);
-}
-
-SeekHead::~SeekHead()
-{
-    delete[] m_entries;
-}
-
-int SeekHead::GetCount() const
-{
-    return m_count;
-}
-
-const SeekHead::Entry* SeekHead::GetEntry(int idx) const
-{
-    if (idx < 0)
-        return 0;
-
-    if (idx >= m_count)
-        return 0;
-
-    return m_entries + idx;
-}
-#endif
-
-
-#if 0
-void Segment::ParseCues(long long off)
-{
-    if (m_pCues)
-        return;
-
-    //odbgstream os;
-    //os << "Segment::ParseCues (begin)" << endl;
-
-    long long pos = m_start + off;
-    const long long element_start = pos;
-    const long long stop = m_start + m_size;
-
-    long len;
-
-    long long result = GetUIntLength(m_pReader, pos, len);
-    assert(result == 0);
-    assert((pos + len) <= stop);
-
-    const long long idpos = pos;
-
-    const long long id = ReadUInt(m_pReader, idpos, len);
-    assert(id == 0x0C53BB6B);  //Cues ID
-
-    pos += len;  //consume ID
-    assert(pos < stop);
-
-    //Read Size
-
-    result = GetUIntLength(m_pReader, pos, len);
-    assert(result == 0);
-    assert((pos + len) <= stop);
-
-    const long long size = ReadUInt(m_pReader, pos, len);
-    assert(size >= 0);
-
-    pos += len;  //consume length of size of element
-    assert((pos + size) <= stop);
-
-    const long long element_size = size + pos - element_start;
-
-    //Pos now points to start of payload
-
-    m_pCues = new Cues(this, pos, size, element_start, element_size);
-    assert(m_pCues);  //TODO
-
-    //os << "Segment::ParseCues (end)" << endl;
-}
-#else
-long Segment::ParseCues(
-    long long off,
-    long long& pos,
-    long& len)
-{
-    if (m_pCues)
-        return 0;  //success
-
-    if (off < 0)
-        return -1;
-
-    long long total, avail;
-
-    const int status = m_pReader->Length(&total, &avail);
-
-    if (status < 0)  //error
-        return status;
-
-    assert((total < 0) || (avail <= total));
-
-    pos = m_start + off;
-
-    const long long element_start = pos;
-    const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
-
-    if ((pos + 1) > avail)
-    {
-        len = 1;
-        return E_BUFFER_NOT_FULL;
-    }
-
-    long long result = GetUIntLength(m_pReader, pos, len);
-
-    if (result < 0)  //error
-        return static_cast<long>(result);
-
-    if (result > 0) //underflow (weird)
-    {
-        len = 1;
-        return E_BUFFER_NOT_FULL;
-    }
-
-    if ((segment_stop >= 0) && ((pos + len) > segment_stop))
-        return E_FILE_FORMAT_INVALID;
-
-    if ((pos + len) > avail)
-        return E_BUFFER_NOT_FULL;
-
-    const long long idpos = pos;
-
-    const long long id = ReadUInt(m_pReader, idpos, len);
-
-    if (id != 0x0C53BB6B)  //Cues ID
-        return E_FILE_FORMAT_INVALID;
-
-    pos += len;  //consume ID
-    assert((segment_stop < 0) || (pos <= segment_stop));
-
-    //Read Size
-
-    if ((pos + 1) > avail)
-    {
-        len = 1;
-        return E_BUFFER_NOT_FULL;
-    }
-
-    result = GetUIntLength(m_pReader, pos, len);
-
-    if (result < 0)  //error
-        return static_cast<long>(result);
-
-    if (result > 0) //underflow (weird)
-    {
-        len = 1;
-        return E_BUFFER_NOT_FULL;
-    }
-
-    if ((segment_stop >= 0) && ((pos + len) > segment_stop))
-        return E_FILE_FORMAT_INVALID;
-
-    if ((pos + len) > avail)
-        return E_BUFFER_NOT_FULL;
-
-    const long long size = ReadUInt(m_pReader, pos, len);
-
-    if (size < 0)  //error
-        return static_cast<long>(size);
-
-    if (size == 0)  //weird, although technically not illegal
-        return 1;   //done
-
-    pos += len;  //consume length of size of element
-    assert((segment_stop < 0) || (pos <= segment_stop));
-
-    //Pos now points to start of payload
-
-    const long long element_stop = pos + size;
-
-    if ((segment_stop >= 0) && (element_stop > segment_stop))
-        return E_FILE_FORMAT_INVALID;
-
-    len = static_cast<long>(size);
-
-    if (element_stop > avail)
-        return E_BUFFER_NOT_FULL;
-
-    const long long element_size = element_stop - element_start;
-
-    m_pCues = new (std::nothrow) Cues(
-                                    this,
-                                    pos,
-                                    size,
-                                    element_start,
-                                    element_size);
-    assert(m_pCues);  //TODO
-
-    return 0;  //success
-}
-#endif
-
-
-#if 0
-void Segment::ParseSeekEntry(
-    long long start,
-    long long size_)
-{
-    long long pos = start;
-
-    const long long stop = start + size_;
-
-    long len;
-
-    const long long seekIdId = ReadUInt(m_pReader, pos, len);
-    //seekIdId;
-    assert(seekIdId == 0x13AB);  //SeekID ID
-    assert((pos + len) <= stop);
-
-    pos += len;  //consume id
-
-    const long long seekIdSize = ReadUInt(m_pReader, pos, len);
-    assert(seekIdSize >= 0);
-    assert((pos + len) <= stop);
-
-    pos += len;  //consume size
-
-    const long long seekId = ReadUInt(m_pReader, pos, len);  //payload
-    assert(seekId >= 0);
-    assert(len == seekIdSize);
-    assert((pos + len) <= stop);
-
-    pos += seekIdSize;  //consume payload
-
-    const long long seekPosId = ReadUInt(m_pReader, pos, len);
-    //seekPosId;
-    assert(seekPosId == 0x13AC);  //SeekPos ID
-    assert((pos + len) <= stop);
-
-    pos += len;  //consume id
-
-    const long long seekPosSize = ReadUInt(m_pReader, pos, len);
-    assert(seekPosSize >= 0);
-    assert((pos + len) <= stop);
-
-    pos += len;  //consume size
-    assert((pos + seekPosSize) <= stop);
-
-    const long long seekOff = UnserializeUInt(m_pReader, pos, seekPosSize);
-    assert(seekOff >= 0);
-    assert(seekOff < m_size);
-
-    pos += seekPosSize;  //consume payload
-    assert(pos == stop);
-
-    const long long seekPos = m_start + seekOff;
-    assert(seekPos < (m_start + m_size));
-
-    if (seekId == 0x0C53BB6B)  //Cues ID
-        ParseCues(seekOff);
-}
-#else
-void SeekHead::ParseEntry(
-    IMkvReader* pReader,
-    long long start,
-    long long size_,
-    Entry*& pEntry)
-{
-    long long pos = start;
-    const long long stop = start + size_;
-
-    long len;
-
-    //parse the container for the level-1 element ID
-
-    const long long seekIdId = ReadUInt(pReader, pos, len);
-    //seekIdId;
-
-    if (seekIdId != 0x13AB)  //SeekID ID
-        return;
-
-    if ((pos + len) > stop)
-        return;
-
-    pos += len;  //consume SeekID id
-
-    const long long seekIdSize = ReadUInt(pReader, pos, len);
-
-    if (seekIdSize <= 0)
-        return;
-
-    if ((pos + len) > stop)
-        return;
-
-    pos += len;  //consume size of field
-
-    if ((pos + seekIdSize) > stop)
-        return;
-
-    //TODO: it's not clear whether this is correct
-    //It seems as if the payload here is "binary" which
-    //means the value of the ID should be unserialized,
-    //not parsed as an uint.
-    //
-    pEntry->id = ReadUInt(pReader, pos, len);  //payload
-
-    if (pEntry->id <= 0)
-        return;
-
-    if (len != seekIdSize)
-        return;
-
-    pos += seekIdSize;  //consume SeekID payload
-
-    const long long seekPosId = ReadUInt(pReader, pos, len);
-
-    if (seekPosId != 0x13AC)  //SeekPos ID
-        return;
-
-    if ((pos + len) > stop)
-        return;
-
-    pos += len;  //consume id
-
-    const long long seekPosSize = ReadUInt(pReader, pos, len);
-
-    if (seekPosSize <= 0)
-        return;
-
-    if ((pos + len) > stop)
-        return;
-
-    pos += len;  //consume size
-
-    if ((pos + seekPosSize) > stop)
-        return;
-
-    pEntry->pos = UnserializeUInt(pReader, pos, seekPosSize);
-
-    if (pEntry->pos < 0)
-        return;
-
-    pos += seekPosSize;  //consume payload
-
-    if (pos != stop)
-        return;
-
-    ++pEntry;  //success
-}
-#endif
-
-
-Cues::Cues(
-    Segment* pSegment,
-    long long start_,
-    long long size_,
-    long long element_start,
-    long long element_size) :
-    m_pSegment(pSegment),
-    m_start(start_),
-    m_size(size_),
-    m_cue_points(NULL),
-    m_count(0),
-    m_preload_count(0),
-    m_pos(start_),
-    m_element_start(element_start),
-    m_element_size(element_size)
-{
-}
-
-
-Cues::~Cues()
-{
-    const size_t n = m_count + m_preload_count;
-
-    CuePoint** p = m_cue_points;
-    CuePoint** const q = p + n;
-
-    while (p != q)
-    {
-        CuePoint* const pCP = *p++;
-        assert(pCP);
-
-        delete pCP;
-    }
-
-    delete[] m_cue_points;
-}
-
-
-long Cues::GetCount() const
-{
-    if (m_cue_points == NULL)
-        return -1;
-
-    return m_count;  //TODO: really ignore preload count?
-}
-
-
-bool Cues::DoneParsing() const
-{
-    const long long stop = m_start + m_size;
-    return (m_pos >= stop);
-}
-
-
-void Cues::Init() const
-{
-    if (m_cue_points)
-        return;
-
-    assert(m_count == 0);
-    assert(m_preload_count == 0);
-
-    IMkvReader* const pReader = m_pSegment->m_pReader;
-
-    const long long stop = m_start + m_size;
-    long long pos = m_start;
-
-    size_t cue_points_size = 0;
-
-    while (pos < stop)
-    {
-        const long long idpos = pos;
-
-        long len;
-
-        const long long id = ReadUInt(pReader, pos, len);
-        assert(id >= 0);  //TODO
-        assert((pos + len) <= stop);
-
-        pos += len;  //consume ID
-
-        const long long size = ReadUInt(pReader, pos, len);
-        assert(size >= 0);
-        assert((pos + len) <= stop);
-
-        pos += len;  //consume Size field
-        assert((pos + size) <= stop);
-
-        if (id == 0x3B)  //CuePoint ID
-            PreloadCuePoint(cue_points_size, idpos);
-
-        pos += size;  //consume payload
-        assert(pos <= stop);
-    }
-}
-
-
-void Cues::PreloadCuePoint(
-    size_t& cue_points_size,
-    long long pos) const
-{
-    assert(m_count == 0);
-
-    if (m_preload_count >= cue_points_size)
-    {
-        size_t n;
-
-        if (cue_points_size > 0)
-            n = static_cast<size_t>(2 * cue_points_size);
-        else
-        {
-            const SegmentInfo* const pInfo = m_pSegment->GetInfo();
-
-            if (pInfo == NULL)
-                n = 2048;
-            else
-            {
-                const long long ns = pInfo->GetDuration();
-
-                if (ns <= 0)
-                    n = 2048;
-                else
-                {
-                    const long long sec = (ns + 999999999LL) / 1000000000LL;
-                    n = static_cast<size_t>(sec);
-                }
-            }
-        }
-
-        CuePoint** const qq = new CuePoint*[n];
-        CuePoint** q = qq;  //beginning of target
-
-        CuePoint** p = m_cue_points;                //beginning of source
-        CuePoint** const pp = p + m_preload_count;  //end of source
-
-        while (p != pp)
-            *q++ = *p++;
-
-        delete[] m_cue_points;
-
-        m_cue_points = qq;
-        cue_points_size = n;
-    }
-
-    CuePoint* const pCP = new CuePoint(m_preload_count, pos);
-    m_cue_points[m_preload_count++] = pCP;
-}
-
-
-bool Cues::LoadCuePoint() const
-{
-    //odbgstream os;
-    //os << "Cues::LoadCuePoint" << endl;
-
-    const long long stop = m_start + m_size;
-
-    if (m_pos >= stop)
-        return false;  //nothing else to do
-
-    Init();
-
-    IMkvReader* const pReader = m_pSegment->m_pReader;
-
-    while (m_pos < stop)
-    {
-        const long long idpos = m_pos;
-
-        long len;
-
-        const long long id = ReadUInt(pReader, m_pos, len);
-        assert(id >= 0);  //TODO
-        assert((m_pos + len) <= stop);
-
-        m_pos += len;  //consume ID
-
-        const long long size = ReadUInt(pReader, m_pos, len);
-        assert(size >= 0);
-        assert((m_pos + len) <= stop);
-
-        m_pos += len;  //consume Size field
-        assert((m_pos + size) <= stop);
-
-        if (id != 0x3B)  //CuePoint ID
-        {
-            m_pos += size;  //consume payload
-            assert(m_pos <= stop);
-
-            continue;
-        }
-
-        assert(m_preload_count > 0);
-
-        CuePoint* const pCP = m_cue_points[m_count];
-        assert(pCP);
-        assert((pCP->GetTimeCode() >= 0) || (-pCP->GetTimeCode() == idpos));
-
-        pCP->Load(pReader);
-        ++m_count;
-        --m_preload_count;
-
-        m_pos += size;  //consume payload
-        assert(m_pos <= stop);
-
-        break;
-    }
-
-    return (m_pos < stop);
-}
-
-
-bool Cues::Find(
-    long long time_ns,
-    const Track* pTrack,
-    const CuePoint*& pCP,
-    const CuePoint::TrackPosition*& pTP) const
-{
-    assert(time_ns >= 0);
-    assert(pTrack);
-
-#if 0
-    LoadCuePoint();  //establish invariant
-
-    assert(m_cue_points);
-    assert(m_count > 0);
-
-    CuePoint** const ii = m_cue_points;
-    CuePoint** i = ii;
-
-    CuePoint** const jj = ii + m_count + m_preload_count;
-    CuePoint** j = jj;
-
-    pCP = *i;
-    assert(pCP);
-
-    if (time_ns <= pCP->GetTime(m_pSegment))
-    {
-        pTP = pCP->Find(pTrack);
-        return (pTP != NULL);
-    }
-
-    IMkvReader* const pReader = m_pSegment->m_pReader;
-
-    while (i < j)
-    {
-        //INVARIANT:
-        //[ii, i) <= time_ns
-        //[i, j)  ?
-        //[j, jj) > time_ns
-
-        CuePoint** const k = i + (j - i) / 2;
-        assert(k < jj);
-
-        CuePoint* const pCP = *k;
-        assert(pCP);
-
-        pCP->Load(pReader);
-
-        const long long t = pCP->GetTime(m_pSegment);
-
-        if (t <= time_ns)
-            i = k + 1;
-        else
-            j = k;
-
-        assert(i <= j);
-    }
-
-    assert(i == j);
-    assert(i <= jj);
-    assert(i > ii);
-
-    pCP = *--i;
-    assert(pCP);
-    assert(pCP->GetTime(m_pSegment) <= time_ns);
-#else
-    if (m_cue_points == NULL)
-        return false;
-
-    if (m_count == 0)
-        return false;
-
-    CuePoint** const ii = m_cue_points;
-    CuePoint** i = ii;
-
-    CuePoint** const jj = ii + m_count;
-    CuePoint** j = jj;
-
-    pCP = *i;
-    assert(pCP);
-
-    if (time_ns <= pCP->GetTime(m_pSegment))
-    {
-        pTP = pCP->Find(pTrack);
-        return (pTP != NULL);
-    }
-
-    while (i < j)
-    {
-        //INVARIANT:
-        //[ii, i) <= time_ns
-        //[i, j)  ?
-        //[j, jj) > time_ns
-
-        CuePoint** const k = i + (j - i) / 2;
-        assert(k < jj);
-
-        CuePoint* const pCP = *k;
-        assert(pCP);
-
-        const long long t = pCP->GetTime(m_pSegment);
-
-        if (t <= time_ns)
-            i = k + 1;
-        else
-            j = k;
-
-        assert(i <= j);
-    }
-
-    assert(i == j);
-    assert(i <= jj);
-    assert(i > ii);
-
-    pCP = *--i;
-    assert(pCP);
-    assert(pCP->GetTime(m_pSegment) <= time_ns);
-#endif
-
-    //TODO: here and elsewhere, it's probably not correct to search
-    //for the cue point with this time, and then search for a matching
-    //track.  In principle, the matching track could be on some earlier
-    //cue point, and with our current algorithm, we'd miss it.  To make
-    //this bullet-proof, we'd need to create a secondary structure,
-    //with a list of cue points that apply to a track, and then search
-    //that track-based structure for a matching cue point.
-
-    pTP = pCP->Find(pTrack);
-    return (pTP != NULL);
-}
-
-
-#if 0
-bool Cues::FindNext(
-    long long time_ns,
-    const Track* pTrack,
-    const CuePoint*& pCP,
-    const CuePoint::TrackPosition*& pTP) const
-{
-    pCP = 0;
-    pTP = 0;
-
-    if (m_count == 0)
-        return false;
-
-    assert(m_cue_points);
-
-    const CuePoint* const* const ii = m_cue_points;
-    const CuePoint* const* i = ii;
-
-    const CuePoint* const* const jj = ii + m_count;
-    const CuePoint* const* j = jj;
-
-    while (i < j)
-    {
-        //INVARIANT:
-        //[ii, i) <= time_ns
-        //[i, j)  ?
-        //[j, jj) > time_ns
-
-        const CuePoint* const* const k = i + (j - i) / 2;
-        assert(k < jj);
-
-        pCP = *k;
-        assert(pCP);
-
-        const long long t = pCP->GetTime(m_pSegment);
-
-        if (t <= time_ns)
-            i = k + 1;
-        else
-            j = k;
-
-        assert(i <= j);
-    }
-
-    assert(i == j);
-    assert(i <= jj);
-
-    if (i >= jj)  //time_ns is greater than max cue point
-        return false;
-
-    pCP = *i;
-    assert(pCP);
-    assert(pCP->GetTime(m_pSegment) > time_ns);
-
-    pTP = pCP->Find(pTrack);
-    return (pTP != NULL);
-}
-#endif
-
-
-const CuePoint* Cues::GetFirst() const
-{
-    if (m_cue_points == NULL)
-        return NULL;
-
-    if (m_count == 0)
-        return NULL;
-
-#if 0
-    LoadCuePoint();  //init cues
-
-    const size_t count = m_count + m_preload_count;
-
-    if (count == 0)  //weird
-        return NULL;
-#endif
-
-    CuePoint* const* const pp = m_cue_points;
-    assert(pp);
-
-    CuePoint* const pCP = pp[0];
-    assert(pCP);
-    assert(pCP->GetTimeCode() >= 0);
-
-    return pCP;
-}
-
-
-const CuePoint* Cues::GetLast() const
-{
-    if (m_cue_points == NULL)
-        return NULL;
-
-    if (m_count == 0)
-        return NULL;
-
-#if 0
-    LoadCuePoint();  //init cues
-
-    const size_t count = m_count + m_preload_count;
-
-    if (count == 0)  //weird
-        return NULL;
-
-    const size_t index = count - 1;
-
-    CuePoint* const* const pp = m_cue_points;
-    assert(pp);
-
-    CuePoint* const pCP = pp[index];
-    assert(pCP);
-
-    pCP->Load(m_pSegment->m_pReader);
-    assert(pCP->GetTimeCode() >= 0);
-#else
-    const size_t index = m_count - 1;
-
-    CuePoint* const* const pp = m_cue_points;
-    assert(pp);
-
-    CuePoint* const pCP = pp[index];
-    assert(pCP);
-    assert(pCP->GetTimeCode() >= 0);
-#endif
-
-    return pCP;
-}
-
-
-const CuePoint* Cues::GetNext(const CuePoint* pCurr) const
-{
-    if (pCurr == NULL)
-        return NULL;
-
-    assert(pCurr->GetTimeCode() >= 0);
-    assert(m_cue_points);
-    assert(m_count >= 1);
-
-#if 0
-    const size_t count = m_count + m_preload_count;
-
-    size_t index = pCurr->m_index;
-    assert(index < count);
-
-    CuePoint* const* const pp = m_cue_points;
-    assert(pp);
-    assert(pp[index] == pCurr);
-
-    ++index;
-
-    if (index >= count)
-        return NULL;
-
-    CuePoint* const pNext = pp[index];
-    assert(pNext);
-
-    pNext->Load(m_pSegment->m_pReader);
-#else
-    size_t index = pCurr->m_index;
-    assert(index < m_count);
-
-    CuePoint* const* const pp = m_cue_points;
-    assert(pp);
-    assert(pp[index] == pCurr);
-
-    ++index;
-
-    if (index >= m_count)
-        return NULL;
-
-    CuePoint* const pNext = pp[index];
-    assert(pNext);
-    assert(pNext->GetTimeCode() >= 0);
-#endif
-
-    return pNext;
-}
-
-
-const BlockEntry* Cues::GetBlock(
-    const CuePoint* pCP,
-    const CuePoint::TrackPosition* pTP) const
-{
-    if (pCP == NULL)
-        return NULL;
-
-    if (pTP == NULL)
-        return NULL;
-
-    return m_pSegment->GetBlock(*pCP, *pTP);
-}
-
-
-const BlockEntry* Segment::GetBlock(
-    const CuePoint& cp,
-    const CuePoint::TrackPosition& tp)
-{
-    Cluster** const ii = m_clusters;
-    Cluster** i = ii;
-
-    const long count = m_clusterCount + m_clusterPreloadCount;
-
-    Cluster** const jj = ii + count;
-    Cluster** j = jj;
-
-    while (i < j)
-    {
-        //INVARIANT:
-        //[ii, i) < pTP->m_pos
-        //[i, j) ?
-        //[j, jj)  > pTP->m_pos
-
-        Cluster** const k = i + (j - i) / 2;
-        assert(k < jj);
-
-        Cluster* const pCluster = *k;
-        assert(pCluster);
-
-        //const long long pos_ = pCluster->m_pos;
-        //assert(pos_);
-        //const long long pos = pos_ * ((pos_ < 0) ? -1 : 1);
-
-        const long long pos = pCluster->GetPosition();
-        assert(pos >= 0);
-
-        if (pos < tp.m_pos)
-            i = k + 1;
-        else if (pos > tp.m_pos)
-            j = k;
-        else
-            return pCluster->GetEntry(cp, tp);
-    }
-
-    assert(i == j);
-    //assert(Cluster::HasBlockEntries(this, tp.m_pos));
-
-    Cluster* const pCluster = Cluster::Create(this, -1, tp.m_pos, -1);
-    assert(pCluster);
-
-    const ptrdiff_t idx = i - m_clusters;
-
-    PreloadCluster(pCluster, idx);
-    assert(m_clusters);
-    assert(m_clusterPreloadCount > 0);
-    assert(m_clusters[idx] == pCluster);
-
-    return pCluster->GetEntry(cp, tp);
-}
-
-
-const Cluster* Segment::FindOrPreloadCluster(long long requested_pos)
-{
-    if (requested_pos < 0)
-        return 0;
-
-    Cluster** const ii = m_clusters;
-    Cluster** i = ii;
-
-    const long count = m_clusterCount + m_clusterPreloadCount;
-
-    Cluster** const jj = ii + count;
-    Cluster** j = jj;
-
-    while (i < j)
-    {
-        //INVARIANT:
-        //[ii, i) < pTP->m_pos
-        //[i, j) ?
-        //[j, jj)  > pTP->m_pos
-
-        Cluster** const k = i + (j - i) / 2;
-        assert(k < jj);
-
-        Cluster* const pCluster = *k;
-        assert(pCluster);
-
-        //const long long pos_ = pCluster->m_pos;
-        //assert(pos_);
-        //const long long pos = pos_ * ((pos_ < 0) ? -1 : 1);
-
-        const long long pos = pCluster->GetPosition();
-        assert(pos >= 0);
-
-        if (pos < requested_pos)
-            i = k + 1;
-        else if (pos > requested_pos)
-            j = k;
-        else
-            return pCluster;
-    }
-
-    assert(i == j);
-    //assert(Cluster::HasBlockEntries(this, tp.m_pos));
-
-    Cluster* const pCluster = Cluster::Create(
-                                this,
-                                -1,
-                                requested_pos,
-                                -1);
-    assert(pCluster);
-
-    const ptrdiff_t idx = i - m_clusters;
-
-    PreloadCluster(pCluster, idx);
-    assert(m_clusters);
-    assert(m_clusterPreloadCount > 0);
-    assert(m_clusters[idx] == pCluster);
-
-    return pCluster;
-}
-
-
-CuePoint::CuePoint(size_t idx, long long pos) :
-    m_element_start(0),
-    m_element_size(0),
-    m_index(idx),
-    m_timecode(-1 * pos),
-    m_track_positions(NULL),
-    m_track_positions_count(0)
-{
-    assert(pos > 0);
-}
-
-
-CuePoint::~CuePoint()
-{
-    delete[] m_track_positions;
-}
-
-
-void CuePoint::Load(IMkvReader* pReader)
-{
-    //odbgstream os;
-    //os << "CuePoint::Load(begin): timecode=" << m_timecode << endl;
-
-    if (m_timecode >= 0)  //already loaded
-        return;
-
-    assert(m_track_positions == NULL);
-    assert(m_track_positions_count == 0);
-
-    long long pos_ = -m_timecode;
-    const long long element_start = pos_;
-
-    long long stop;
-
-    {
-        long len;
-
-        const long long id = ReadUInt(pReader, pos_, len);
-        assert(id == 0x3B);  //CuePoint ID
-        //assert((pos + len) <= stop);
-
-        pos_ += len;  //consume ID
-
-        const long long size = ReadUInt(pReader, pos_, len);
-        assert(size >= 0);
-        //assert((pos + len) <= stop);
-
-        pos_ += len;  //consume Size field
-        //assert((pos + size) <= stop);
-
-        //pos_ now points to start of payload
-
-        stop = pos_ + size;
-    }
-
-    const long long element_size = stop - element_start;
-
-    long long pos = pos_;
-
-    //First count number of track positions
-
-    while (pos < stop)
-    {
-        long len;
-
-        const long long id = ReadUInt(pReader, pos, len);
-        assert(id >= 0);  //TODO
-        assert((pos + len) <= stop);
-
-        pos += len;  //consume ID
-
-        const long long size = ReadUInt(pReader, pos, len);
-        assert(size >= 0);
-        assert((pos + len) <= stop);
-
-        pos += len;  //consume Size field
-        assert((pos + size) <= stop);
-
-        if (id == 0x33)  //CueTime ID
-            m_timecode = UnserializeUInt(pReader, pos, size);
-
-        else if (id == 0x37) //CueTrackPosition(s) ID
-            ++m_track_positions_count;
-
-        pos += size;  //consume payload
-        assert(pos <= stop);
-    }
-
-    assert(m_timecode >= 0);
-    assert(m_track_positions_count > 0);
-
-    //os << "CuePoint::Load(cont'd): idpos=" << idpos
-    //   << " timecode=" << m_timecode
-    //   << endl;
-
-    m_track_positions = new TrackPosition[m_track_positions_count];
-
-    //Now parse track positions
-
-    TrackPosition* p = m_track_positions;
-    pos = pos_;
-
-    while (pos < stop)
-    {
-        long len;
-
-        const long long id = ReadUInt(pReader, pos, len);
-        assert(id >= 0);  //TODO
-        assert((pos + len) <= stop);
-
-        pos += len;  //consume ID
-
-        const long long size = ReadUInt(pReader, pos, len);
-        assert(size >= 0);
-        assert((pos + len) <= stop);
-
-        pos += len;  //consume Size field
-        assert((pos + size) <= stop);
-
-        if (id == 0x37) //CueTrackPosition(s) ID
-        {
-            TrackPosition& tp = *p++;
-            tp.Parse(pReader, pos, size);
-        }
-
-        pos += size;  //consume payload
-        assert(pos <= stop);
-    }
-
-    assert(size_t(p - m_track_positions) == m_track_positions_count);
-
-    m_element_start = element_start;
-    m_element_size = element_size;
-}
-
-
-
-void CuePoint::TrackPosition::Parse(
-    IMkvReader* pReader,
-    long long start_,
-    long long size_)
-{
-    const long long stop = start_ + size_;
-    long long pos = start_;
-
-    m_track = -1;
-    m_pos = -1;
-    m_block = 1;  //default
-
-    while (pos < stop)
-    {
-        long len;
-
-        const long long id = ReadUInt(pReader, pos, len);
-        assert(id >= 0);  //TODO
-        assert((pos + len) <= stop);
-
-        pos += len;  //consume ID
-
-        const long long size = ReadUInt(pReader, pos, len);
-        assert(size >= 0);
-        assert((pos + len) <= stop);
-
-        pos += len;  //consume Size field
-        assert((pos + size) <= stop);
-
-        if (id == 0x77)  //CueTrack ID
-            m_track = UnserializeUInt(pReader, pos, size);
-
-        else if (id == 0x71)  //CueClusterPos ID
-            m_pos = UnserializeUInt(pReader, pos, size);
-
-        else if (id == 0x1378)  //CueBlockNumber
-            m_block = UnserializeUInt(pReader, pos, size);
-
-        pos += size;  //consume payload
-        assert(pos <= stop);
-    }
-
-    assert(m_pos >= 0);
-    assert(m_track > 0);
-    //assert(m_block > 0);
-}
-
-
-const CuePoint::TrackPosition* CuePoint::Find(const Track* pTrack) const
-{
-    assert(pTrack);
-
-    const long long n = pTrack->GetNumber();
-
-    const TrackPosition* i = m_track_positions;
-    const TrackPosition* const j = i + m_track_positions_count;
-
-    while (i != j)
-    {
-        const TrackPosition& p = *i++;
-
-        if (p.m_track == n)
-            return &p;
-    }
-
-    return NULL;  //no matching track number found
-}
-
-
-long long CuePoint::GetTimeCode() const
-{
-    return m_timecode;
-}
-
-long long CuePoint::GetTime(const Segment* pSegment) const
-{
-    assert(pSegment);
-    assert(m_timecode >= 0);
-
-    const SegmentInfo* const pInfo = pSegment->GetInfo();
-    assert(pInfo);
-
-    const long long scale = pInfo->GetTimeCodeScale();
-    assert(scale >= 1);
-
-    const long long time = scale * m_timecode;
-
-    return time;
-}
-
-
-long long Segment::Unparsed() const
-{
-    if (m_size < 0)
-        return LLONG_MAX;
-
-    const long long stop = m_start + m_size;
-
-    const long long result = stop - m_pos;
-    assert(result >= 0);
-
-    return result;
-}
-
-
-const Cluster* Segment::GetFirst() const
-{
-    if ((m_clusters == NULL) || (m_clusterCount <= 0))
-       return &m_eos;
-
-    Cluster* const pCluster = m_clusters[0];
-    assert(pCluster);
-
-    return pCluster;
-}
-
-
-const Cluster* Segment::GetLast() const
-{
-    if ((m_clusters == NULL) || (m_clusterCount <= 0))
-        return &m_eos;
-
-    const long idx = m_clusterCount - 1;
-
-    Cluster* const pCluster = m_clusters[idx];
-    assert(pCluster);
-
-    return pCluster;
-}
-
-
-unsigned long Segment::GetCount() const
-{
-    return m_clusterCount;
-}
-
-
-const Cluster* Segment::GetNext(const Cluster* pCurr)
-{
-    assert(pCurr);
-    assert(pCurr != &m_eos);
-    assert(m_clusters);
-
-    long idx =  pCurr->m_index;
-
-    if (idx >= 0)
-    {
-        assert(m_clusterCount > 0);
-        assert(idx < m_clusterCount);
-        assert(pCurr == m_clusters[idx]);
-
-        ++idx;
-
-        if (idx >= m_clusterCount)
-            return &m_eos;  //caller will LoadCluster as desired
-
-        Cluster* const pNext = m_clusters[idx];
-        assert(pNext);
-        assert(pNext->m_index >= 0);
-        assert(pNext->m_index == idx);
-
-        return pNext;
-    }
-
-    assert(m_clusterPreloadCount > 0);
-
-    //const long long off_ = pCurr->m_pos;
-    //const long long off = off_ * ((off_ < 0) ? -1 : 1);
-    //long long pos = m_start + off;
-
-    long long pos = pCurr->m_element_start;
-
-    assert(m_size >= 0);  //TODO
-    const long long stop = m_start + m_size;  //end of segment
-
-    {
-        long len;
-
-        long long result = GetUIntLength(m_pReader, pos, len);
-        assert(result == 0);  //TODO
-        assert((pos + len) <= stop);  //TODO
-
-        const long long id = ReadUInt(m_pReader, pos, len);
-        assert(id == 0x0F43B675);  //Cluster ID   //TODO
-
-        pos += len;  //consume ID
-
-        //Read Size
-        result = GetUIntLength(m_pReader, pos, len);
-        assert(result == 0);  //TODO
-        assert((pos + len) <= stop);  //TODO
-
-        const long long size = ReadUInt(m_pReader, pos, len);
-        assert(size > 0);  //TODO
-        assert((pCurr->m_size <= 0) || (pCurr->m_size == size));
-
-        pos += len;  //consume length of size of element
-        assert((pos + size) <= stop);  //TODO
-
-        //Pos now points to start of payload
-
-        pos += size;  //consume payload
-    }
-
-    long long off_next = 0;
-    //long long element_start_next = 0;
-    long long element_size_next = 0;
-
-    while (pos < stop)
-    {
-        long len;
-
-        long long result = GetUIntLength(m_pReader, pos, len);
-        assert(result == 0);  //TODO
-        assert((pos + len) <= stop);  //TODO
-
-        const long long idpos = pos;  //pos of next (potential) cluster
-
-        const long long id = ReadUInt(m_pReader, idpos, len);
-        assert(id > 0);  //TODO
-
-        pos += len;  //consume ID
-
-        //Read Size
-        result = GetUIntLength(m_pReader, pos, len);
-        assert(result == 0);  //TODO
-        assert((pos + len) <= stop);  //TODO
-
-        const long long size = ReadUInt(m_pReader, pos, len);
-        assert(size >= 0);  //TODO
-
-        pos += len;  //consume length of size of element
-        assert((pos + size) <= stop);  //TODO
-
-        const long long element_size = size + pos - idpos;
-
-        //Pos now points to start of payload
-
-        if (size == 0)  //weird
-            continue;
-
-        if (id == 0x0F43B675)  //Cluster ID
-        {
-            const long long off_next_ = idpos - m_start;
-
-            long long pos_;
-            long len_;
-
-            const long status = Cluster::HasBlockEntries(
-                                    this,
-                                    off_next_,
-                                    pos_,
-                                    len_);
-
-            assert(status >= 0);
-
-            if (status > 0)
-            {
-                off_next = off_next_;
-                //element_start_next = idpos;
-                element_size_next = element_size;
-                break;
-            }
-        }
-
-        pos += size;  //consume payload
-    }
-
-    if (off_next <= 0)
-        return 0;
-
-    Cluster** const ii = m_clusters + m_clusterCount;
-    Cluster** i = ii;
-
-    Cluster** const jj = ii + m_clusterPreloadCount;
-    Cluster** j = jj;
-
-    while (i < j)
-    {
-        //INVARIANT:
-        //[0, i) < pos_next
-        //[i, j) ?
-        //[j, jj)  > pos_next
-
-        Cluster** const k = i + (j - i) / 2;
-        assert(k < jj);
-
-        Cluster* const pNext = *k;
-        assert(pNext);
-        assert(pNext->m_index < 0);
-
-        //const long long pos_ = pNext->m_pos;
-        //assert(pos_);
-        //pos = pos_ * ((pos_ < 0) ? -1 : 1);
-
-        pos = pNext->GetPosition();
-
-        if (pos < off_next)
-            i = k + 1;
-        else if (pos > off_next)
-            j = k;
-        else
-            return pNext;
-    }
-
-    assert(i == j);
-
-    Cluster* const pNext = Cluster::Create(this,
-                                          -1,
-                                          off_next,
-                                          element_size_next);
-    assert(pNext);
-
-    const ptrdiff_t idx_next = i - m_clusters;  //insertion position
-
-    PreloadCluster(pNext, idx_next);
-    assert(m_clusters);
-    assert(idx_next < m_clusterSize);
-    assert(m_clusters[idx_next] == pNext);
-
-    return pNext;
-}
-
-
-long Segment::ParseNext(
-    const Cluster* pCurr,
-    const Cluster*& pResult,
-    long long& pos,
-    long& len)
-{
-    assert(pCurr);
-    assert(!pCurr->EOS());
-    assert(m_clusters);
-
-    pResult = 0;
-
-    if (pCurr->m_index >= 0)  //loaded (not merely preloaded)
-    {
-        assert(m_clusters[pCurr->m_index] == pCurr);
-
-        const long next_idx = pCurr->m_index + 1;
-
-        if (next_idx < m_clusterCount)
-        {
-            pResult = m_clusters[next_idx];
-            return 0;  //success
-        }
-
-        //curr cluster is last among loaded
-
-        const long result = LoadCluster(pos, len);
-
-        if (result < 0)  //error or underflow
-            return result;
-
-        if (result > 0)  //no more clusters
-        {
-            //pResult = &m_eos;
-            return 1;
-        }
-
-        pResult = GetLast();
-        return 0;  //success
-    }
-
-    long long total, avail;
-
-    long status = m_pReader->Length(&total, &avail);
-
-    if (status < 0)  //error
-        return status;
-
-    assert((total < 0) || (avail <= total));
-
-    //const long long off_curr_ = pCurr->m_pos;
-    //const long long off_curr = off_curr_ * ((off_curr_ < 0) ? -1 : 1);
-
-    //pos = m_start + off_curr;
-
-    const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
-
-    //interrogate curr cluster
-
-    pos = pCurr->m_element_start;
-
-    if (pCurr->m_size >= 0)  //loaded (either partially or fully)
-    {
-        assert(pCurr->m_element_size > pCurr->m_size);
-        pos += pCurr->m_element_size;
-    }
-    else  //weird: preloaded only
-    {
-        if ((pos + 1) > avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        long long result = GetUIntLength(m_pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if (result > 0)  //weird
-            return E_BUFFER_NOT_FULL;
-
-        if ((segment_stop >= 0) && ((pos + len) > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > avail)
-            return E_BUFFER_NOT_FULL;
-
-        const long long id = ReadUInt(m_pReader, pos, len);
-
-        if (id != 0x0F43B675)  //weird: not Cluster ID
-            return -1;
-
-        pos += len;  //consume ID
-
-        //Read Size
-
-        if ((pos + 1) > avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        result = GetUIntLength(m_pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if (result > 0)  //weird
-            return E_BUFFER_NOT_FULL;
-
-        if ((segment_stop >= 0) && ((pos + len) > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > avail)
-            return E_BUFFER_NOT_FULL;
-
-        const long long size = ReadUInt(m_pReader, pos, len);
-
-        if (size < 0) //error
-            return static_cast<long>(size);
-
-        const long long unknown_size = (1LL << (7 * len)) - 1;
-
-        if (size == unknown_size)
-            return E_FILE_FORMAT_INVALID;
-
-        if (size == 0)
-            return E_FILE_FORMAT_INVALID;
-
-        assert((pCurr->m_size <= 0) || (pCurr->m_size == size));
-
-        pos += len;  //consume length of size of element
-
-        if ((segment_stop >= 0) && ((pos + size) > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-        //Pos now points to start of payload
-
-        pos += size;  //consume payload (that is, the current cluster)
-        assert((segment_stop < 0) || (pos <= segment_stop));
-
-        //By consuming the payload, we are assuming that the curr
-        //cluster isn't interesting.  That is, we don't bother checking
-        //whether the payload of the curr cluster is less than what
-        //happens to be available (obtained via IMkvReader::Length).
-        //Presumably the caller has already dispensed with the current
-        //cluster, and really does want the next cluster.
-    }
-
-    //pos now points to just beyond the last fully-loaded cluster
-
-    //Parse next cluster.  This is strictly a parsing activity.
-    //Creation of a new cluster object happens later, after the
-    //parsing is done.
-
-    long long off_next = 0;
-    long long element_start = -1;
-    long long element_size = -1;
-
-    for (;;)
-    {
-        if ((total >= 0) && (pos >= total))
-            break;
-
-        if ((segment_stop >= 0) && (pos >= segment_stop))
-            break;
-
-        if ((pos + 1) > avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        long long result = GetUIntLength(m_pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if (result > 0)  //weird
-            return E_BUFFER_NOT_FULL;
-
-        if ((segment_stop >= 0) && ((pos + len) > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > avail)
-            return E_BUFFER_NOT_FULL;
-
-        const long long idpos = pos;             //absolute
-        const long long idoff = pos - m_start;   //relative
-
-        const long long id = ReadUInt(m_pReader, idpos, len);  //absolute
-
-        if (id < 0)  //error
-            return static_cast<long>(id);
-
-        if (id == 0)  //weird
-            return -1;  //generic error
-
-        pos += len;  //consume ID
-
-        //Read Size
-
-        if ((pos + 1) > avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        result = GetUIntLength(m_pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if (result > 0)  //weird
-            return E_BUFFER_NOT_FULL;
-
-        if ((segment_stop >= 0) && ((pos + len) > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > avail)
-            return E_BUFFER_NOT_FULL;
-
-        const long long size = ReadUInt(m_pReader, pos, len);
-
-        if (size < 0)  //error
-            return static_cast<long>(size);
-
-        const long long unknown_size = (1LL << (7 * len)) - 1;
-
-        if (size == unknown_size)
-            return E_FILE_FORMAT_INVALID;
-
-        pos += len;  //consume length of size of element
-
-        //Pos now points to start of payload
-
-        if (size == 0)  //weird
-            continue;
-
-        element_start = idpos;
-        const long long element_stop = pos + size;
-
-        if ((segment_stop >= 0) && (element_stop > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-        element_size = element_stop - element_start;
-
-        if (id == 0x0C53BB6B)  //Cues ID
-        {
-            if (m_pCues == NULL)
-            {
-                m_pCues = new Cues(this,
-                                    pos,
-                                    size,
-                                    element_start,
-                                    element_size);
-                assert(m_pCues);  //TODO
-            }
-
-            pos += size;  //consume payload
-            assert((segment_stop < 0) || (pos <= segment_stop));
-
-            continue;
-        }
-
-        if (id != 0x0F43B675)  //Cluster ID
-        {
-            pos += size;  //consume payload
-            assert((segment_stop < 0) || (pos <= segment_stop));
-
-            continue;
-        }
-
-#if 0
-        len = static_cast<long>(size);
-
-        if (element_stop > avail)
-            return E_BUFFER_NOT_FULL;
-#endif
-
-        long long pos_;
-        long len_;
-
-        status = Cluster::HasBlockEntries(this, idoff, pos_, len_);
-
-        if (status < 0)  //error or underflow
-        {
-            pos = pos_;
-            len = len_;
-
-            return status;
-        }
-
-        if (status > 0)  //have block entries
-        {
-            off_next = idoff;
-            break;
-        }
-
-        pos += size;  //consume payload
-        assert((segment_stop < 0) || (pos <= segment_stop));
-    }
-
-    if (off_next <= 0)  //no next cluster found
-    {
-        //pResult = &m_eos;
-        return 1;
-    }
-
-    //We have parsed the next cluster.
-    //We have not created a cluster object yet.  What we need
-    //to do now is determine whether it has already be preloaded
-    //(in which case, an object for this cluster has already been
-    //created), and if not, create a new cluster object.
-
-    Cluster** const ii = m_clusters + m_clusterCount;
-    Cluster** i = ii;
-
-    Cluster** const jj = ii + m_clusterPreloadCount;
-    Cluster** j = jj;
-
-    while (i < j)
-    {
-        //INVARIANT:
-        //[0, i) < pos_next
-        //[i, j) ?
-        //[j, jj)  > pos_next
-
-        Cluster** const k = i + (j - i) / 2;
-        assert(k < jj);
-
-        const Cluster* const pNext = *k;
-        assert(pNext);
-        assert(pNext->m_index < 0);
-
-        //const long long pos_ = pNext->m_pos;
-        //assert(pos_);
-        //pos = pos_ * ((pos_ < 0) ? -1 : 1);
-
-        pos = pNext->GetPosition();
-        assert(pos >= 0);
-
-        if (pos < off_next)
-            i = k + 1;
-        else if (pos > off_next)
-            j = k;
-        else
-        {
-#if 0
-            status = pNext->Load(pos, len);
-            assert(status == 0);
-
-            if (status < 0)  //should never happen
-                return status;
-#endif
-            pResult = pNext;
-            return 0;  //success
-        }
-    }
-
-    assert(i == j);
-
-    Cluster* const pNext = Cluster::Create(this,
-                                            -1,   //preloaded
-                                            off_next,
-                                            element_size);
-    assert(pNext);
-
-    const ptrdiff_t idx_next = i - m_clusters;  //insertion position
-
-    PreloadCluster(pNext, idx_next);
-    assert(m_clusters);
-    assert(idx_next < m_clusterSize);
-    assert(m_clusters[idx_next] == pNext);
-
-#if 0
-    status = pNext->Load(pos, len);
-    assert(status == 0);
-
-    if (status < 0)
-        return status;
-#endif
-
-    pResult = pNext;
-    return 0;  //success
-}
-
-
-const Cluster* Segment::FindCluster(long long time_ns) const
-{
-    if ((m_clusters == NULL) || (m_clusterCount <= 0))
-        return &m_eos;
-
-    {
-        Cluster* const pCluster = m_clusters[0];
-        assert(pCluster);
-        assert(pCluster->m_index == 0);
-
-        if (time_ns <= pCluster->GetTime())
-            return pCluster;
-    }
-
-    //Binary search of cluster array
-
-    long i = 0;
-    long j = m_clusterCount;
-
-    while (i < j)
-    {
-        //INVARIANT:
-        //[0, i) <= time_ns
-        //[i, j) ?
-        //[j, m_clusterCount)  > time_ns
-
-        const long k = i + (j - i) / 2;
-        assert(k < m_clusterCount);
-
-        Cluster* const pCluster = m_clusters[k];
-        assert(pCluster);
-        assert(pCluster->m_index == k);
-
-        const long long t = pCluster->GetTime();
-
-        if (t <= time_ns)
-            i = k + 1;
-        else
-            j = k;
-
-        assert(i <= j);
-    }
-
-    assert(i == j);
-    assert(i > 0);
-    assert(i <= m_clusterCount);
-
-    const long k = i - 1;
-
-    Cluster* const pCluster = m_clusters[k];
-    assert(pCluster);
-    assert(pCluster->m_index == k);
-    assert(pCluster->GetTime() <= time_ns);
-
-    return pCluster;
-}
-
-
-#if 0
-const BlockEntry* Segment::Seek(
-    long long time_ns,
-    const Track* pTrack) const
-{
-    assert(pTrack);
-
-    if ((m_clusters == NULL) || (m_clusterCount <= 0))
-        return pTrack->GetEOS();
-
-    Cluster** const i = m_clusters;
-    assert(i);
-
-    {
-        Cluster* const pCluster = *i;
-        assert(pCluster);
-        assert(pCluster->m_index == 0);  //m_clusterCount > 0
-        assert(pCluster->m_pSegment == this);
-
-        if (time_ns <= pCluster->GetTime())
-            return pCluster->GetEntry(pTrack);
-    }
-
-    Cluster** const j = i + m_clusterCount;
-
-    if (pTrack->GetType() == 2)  //audio
-    {
-        //TODO: we could decide to use cues for this, as we do for video.
-        //But we only use it for video because looking around for a keyframe
-        //can get expensive.  Audio doesn't require anything special so a
-        //straight cluster search is good enough (we assume).
-
-        Cluster** lo = i;
-        Cluster** hi = j;
-
-        while (lo < hi)
-        {
-            //INVARIANT:
-            //[i, lo) <= time_ns
-            //[lo, hi) ?
-            //[hi, j)  > time_ns
-
-            Cluster** const mid = lo + (hi - lo) / 2;
-            assert(mid < hi);
-
-            Cluster* const pCluster = *mid;
-            assert(pCluster);
-            assert(pCluster->m_index == long(mid - m_clusters));
-            assert(pCluster->m_pSegment == this);
-
-            const long long t = pCluster->GetTime();
-
-            if (t <= time_ns)
-                lo = mid + 1;
-            else
-                hi = mid;
-
-            assert(lo <= hi);
-        }
-
-        assert(lo == hi);
-        assert(lo > i);
-        assert(lo <= j);
-
-        while (lo > i)
-        {
-            Cluster* const pCluster = *--lo;
-            assert(pCluster);
-            assert(pCluster->GetTime() <= time_ns);
-
-            const BlockEntry* const pBE = pCluster->GetEntry(pTrack);
-
-            if ((pBE != 0) && !pBE->EOS())
-                return pBE;
-
-            //landed on empty cluster (no entries)
-        }
-
-        return pTrack->GetEOS();  //weird
-    }
-
-    assert(pTrack->GetType() == 1);  //video
-
-    Cluster** lo = i;
-    Cluster** hi = j;
-
-    while (lo < hi)
-    {
-        //INVARIANT:
-        //[i, lo) <= time_ns
-        //[lo, hi) ?
-        //[hi, j)  > time_ns
-
-        Cluster** const mid = lo + (hi - lo) / 2;
-        assert(mid < hi);
-
-        Cluster* const pCluster = *mid;
-        assert(pCluster);
-
-        const long long t = pCluster->GetTime();
-
-        if (t <= time_ns)
-            lo = mid + 1;
-        else
-            hi = mid;
-
-        assert(lo <= hi);
-    }
-
-    assert(lo == hi);
-    assert(lo > i);
-    assert(lo <= j);
-
-    Cluster* pCluster = *--lo;
-    assert(pCluster);
-    assert(pCluster->GetTime() <= time_ns);
-
-    {
-        const BlockEntry* const pBE = pCluster->GetEntry(pTrack, time_ns);
-
-        if ((pBE != 0) && !pBE->EOS())  //found a keyframe
-            return pBE;
-    }
-
-    const VideoTrack* const pVideo = static_cast<const VideoTrack*>(pTrack);
-
-    while (lo != i)
-    {
-        pCluster = *--lo;
-        assert(pCluster);
-        assert(pCluster->GetTime() <= time_ns);
-
-        const BlockEntry* const pBlockEntry = pCluster->GetMaxKey(pVideo);
-
-        if ((pBlockEntry != 0) && !pBlockEntry->EOS())
-            return pBlockEntry;
-    }
-
-    //weird: we're on the first cluster, but no keyframe found
-    //should never happen but we must return something anyway
-
-    return pTrack->GetEOS();
-}
-#endif
-
-
-#if 0
-bool Segment::SearchCues(
-    long long time_ns,
-    Track* pTrack,
-    Cluster*& pCluster,
-    const BlockEntry*& pBlockEntry,
-    const CuePoint*& pCP,
-    const CuePoint::TrackPosition*& pTP)
-{
-    if (pTrack->GetType() != 1)  //not video
-        return false;  //TODO: for now, just handle video stream
-
-    if (m_pCues == NULL)
-        return false;
-
-    if (!m_pCues->Find(time_ns, pTrack, pCP, pTP))
-        return false;  //weird
-
-    assert(pCP);
-    assert(pTP);
-    assert(pTP->m_track == pTrack->GetNumber());
-
-    //We have the cue point and track position we want,
-    //so we now need to search for the cluster having
-    //the indicated position.
-
-    return GetCluster(pCP, pTP, pCluster, pBlockEntry);
-}
-#endif
-
-
-const Tracks* Segment::GetTracks() const
-{
-    return m_pTracks;
-}
-
-
-const SegmentInfo* Segment::GetInfo() const
-{
-    return m_pInfo;
-}
-
-
-const Cues* Segment::GetCues() const
-{
-    return m_pCues;
-}
-
-
-const SeekHead* Segment::GetSeekHead() const
-{
-    return m_pSeekHead;
-}
-
-
-long long Segment::GetDuration() const
-{
-    assert(m_pInfo);
-    return m_pInfo->GetDuration();
-}
-
-
-SegmentInfo::SegmentInfo(
-    Segment* pSegment,
-    long long start,
-    long long size_,
-    long long element_start,
-    long long element_size) :
-    m_pSegment(pSegment),
-    m_start(start),
-    m_size(size_),
-    m_pMuxingAppAsUTF8(NULL),
-    m_pWritingAppAsUTF8(NULL),
-    m_pTitleAsUTF8(NULL),
-    m_element_start(element_start),
-    m_element_size(element_size)
-{
-    IMkvReader* const pReader = m_pSegment->m_pReader;
-
-    long long pos = start;
-    const long long stop = start + size_;
-
-    m_timecodeScale = 1000000;
-    m_duration = -1;
-
-    while (pos < stop)
-    {
-        if (Match(pReader, pos, 0x0AD7B1, m_timecodeScale))
-            assert(m_timecodeScale > 0);
-
-        else if (Match(pReader, pos, 0x0489, m_duration))
-            assert(m_duration >= 0);
-
-        else if (Match(pReader, pos, 0x0D80, m_pMuxingAppAsUTF8))   //[4D][80]
-            assert(m_pMuxingAppAsUTF8);
-
-        else if (Match(pReader, pos, 0x1741, m_pWritingAppAsUTF8))  //[57][41]
-            assert(m_pWritingAppAsUTF8);
-
-        else if (Match(pReader, pos, 0x3BA9, m_pTitleAsUTF8))       //[7B][A9]
-            assert(m_pTitleAsUTF8);
-
-        else
-        {
-            long len;
-
-            const long long id = ReadUInt(pReader, pos, len);
-            //id;
-            assert(id >= 0);
-            assert((pos + len) <= stop);
-
-            pos += len;  //consume id
-            assert((stop - pos) > 0);
-
-            const long long size = ReadUInt(pReader, pos, len);
-            assert(size >= 0);
-            assert((pos + len) <= stop);
-
-            pos += len + size;  //consume size and payload
-            assert(pos <= stop);
-        }
-    }
-
-    assert(pos == stop);
-}
-
-SegmentInfo::~SegmentInfo()
-{
-    if (m_pMuxingAppAsUTF8)
-    {
-        delete[] m_pMuxingAppAsUTF8;
-        m_pMuxingAppAsUTF8 = NULL;
-    }
-
-    if (m_pWritingAppAsUTF8)
-    {
-        delete[] m_pWritingAppAsUTF8;
-        m_pWritingAppAsUTF8 = NULL;
-    }
-
-    if (m_pTitleAsUTF8)
-    {
-        delete[] m_pTitleAsUTF8;
-        m_pTitleAsUTF8 = NULL;
-    }
-}
-
-long long SegmentInfo::GetTimeCodeScale() const
-{
-    return m_timecodeScale;
-}
-
-
-long long SegmentInfo::GetDuration() const
-{
-    if (m_duration < 0)
-        return -1;
-
-    assert(m_timecodeScale >= 1);
-
-    const double dd = double(m_duration) * double(m_timecodeScale);
-    const long long d = static_cast<long long>(dd);
-
-    return d;
-}
-
-const char* SegmentInfo::GetMuxingAppAsUTF8() const
-{
-    return m_pMuxingAppAsUTF8;
-}
-
-
-const char* SegmentInfo::GetWritingAppAsUTF8() const
-{
-    return m_pWritingAppAsUTF8;
-}
-
-const char* SegmentInfo::GetTitleAsUTF8() const
-{
-    return m_pTitleAsUTF8;
-}
-
-Track::Track(
-    Segment* pSegment,
-    const Info& i,
-    long long element_start,
-    long long element_size) :
-    m_pSegment(pSegment),
-    m_info(i),
-    m_element_start(element_start),
-    m_element_size(element_size)
-{
-}
-
-Track::~Track()
-{
-    Info& info = const_cast<Info&>(m_info);
-    info.Clear();
-}
-
-Track::Info::Info():
-    type(-1),
-    number(-1),
-    uid(ULLONG_MAX),
-    nameAsUTF8(NULL),
-    codecId(NULL),
-    codecPrivate(NULL),
-    codecPrivateSize(0),
-    codecNameAsUTF8(NULL)
-{
-}
-
-void Track::Info::Clear()
-{
-    delete[] nameAsUTF8;
-    nameAsUTF8 = NULL;
-
-    delete[] codecId;
-    codecId = NULL;
-
-    delete[] codecPrivate;
-    codecPrivate = NULL;
-
-    codecPrivateSize = 0;
-
-    delete[] codecNameAsUTF8;
-    codecNameAsUTF8 = NULL;
-}
-
-const BlockEntry* Track::GetEOS() const
-{
-    return &m_eos;
-}
-
-long long Track::GetType() const
-{
-    return m_info.type;
-}
-
-long long Track::GetNumber() const
-{
-    return m_info.number;
-}
-
-unsigned long long Track::GetUid() const
-{
-    return m_info.uid;
-}
-
-const char* Track::GetNameAsUTF8() const
-{
-    return m_info.nameAsUTF8;
-}
-
-const char* Track::GetCodecNameAsUTF8() const
-{
-    return m_info.codecNameAsUTF8;
-}
-
-
-const char* Track::GetCodecId() const
-{
-    return m_info.codecId;
-}
-
-const unsigned char* Track::GetCodecPrivate(size_t& size) const
-{
-    size = m_info.codecPrivateSize;
-    return m_info.codecPrivate;
-}
-
-
-bool Track::GetLacing() const
-{
-    return m_info.lacing;
-}
-
-
-long Track::GetFirst(const BlockEntry*& pBlockEntry) const
-{
-    const Cluster* pCluster = m_pSegment->GetFirst();
-
-    for (int i = 0; ; )
-    {
-        if (pCluster == NULL)
-        {
-            pBlockEntry = GetEOS();
-            return 1;
-        }
-
-        if (pCluster->EOS())
-        {
-            if (m_pSegment->Unparsed() <= 0)  //all clusters have been loaded
-            {
-                pBlockEntry = GetEOS();
-                return 1;
-            }
-
-            pBlockEntry = 0;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        pBlockEntry = pCluster->GetFirst();
-
-        if (pBlockEntry == 0)  //empty cluster
-        {
-            pCluster = m_pSegment->GetNext(pCluster);
-            continue;
-        }
-
-        for (;;)
-        {
-            const Block* const pBlock = pBlockEntry->GetBlock();
-            assert(pBlock);
-
-            const long long tn = pBlock->GetTrackNumber();
-
-            if ((tn == m_info.number) && VetEntry(pBlockEntry))
-                return 0;
-
-            pBlockEntry = pCluster->GetNext(pBlockEntry);
-
-            if (pBlockEntry == 0)
-                break;
-        }
-
-        ++i;
-
-        if (i >= 100)
-            break;
-
-        pCluster = m_pSegment->GetNext(pCluster);
-    }
-
-    //NOTE: if we get here, it means that we didn't find a block with
-    //a matching track number.  We interpret that as an error (which
-    //might be too conservative).
-
-    pBlockEntry = GetEOS();  //so we can return a non-NULL value
-    return 1;
-}
-
-
-long Track::GetNext(
-    const BlockEntry* pCurrEntry,
-    const BlockEntry*& pNextEntry) const
-{
-    assert(pCurrEntry);
-    assert(!pCurrEntry->EOS());  //?
-
-    const Block* const pCurrBlock = pCurrEntry->GetBlock();
-    assert(pCurrBlock->GetTrackNumber() == m_info.number);
-
-    const Cluster* pCluster = pCurrEntry->GetCluster();
-    assert(pCluster);
-    assert(!pCluster->EOS());
-
-    pNextEntry = pCluster->GetNext(pCurrEntry);
-
-    for (int i = 0; ; )
-    {
-        while (pNextEntry)
-        {
-            const Block* const pNextBlock = pNextEntry->GetBlock();
-            assert(pNextBlock);
-
-            if (pNextBlock->GetTrackNumber() == m_info.number)
-                return 0;
-
-            pNextEntry = pCluster->GetNext(pNextEntry);
-        }
-
-        pCluster = m_pSegment->GetNext(pCluster);
-
-        if (pCluster == NULL)
-        {
-            pNextEntry = GetEOS();
-            return 1;
-        }
-
-        if (pCluster->EOS())
-        {
-            if (m_pSegment->Unparsed() <= 0)   //all clusters have been loaded
-            {
-                pNextEntry = GetEOS();
-                return 1;
-            }
-
-            //TODO: there is a potential O(n^2) problem here: we tell the
-            //caller to (pre)load another cluster, which he does, but then he
-            //calls GetNext again, which repeats the same search.  This is
-            //a pathological case, since the only way it can happen is if
-            //there exists a long sequence of clusters none of which contain a
-            // block from this track.  One way around this problem is for the
-            //caller to be smarter when he loads another cluster: don't call
-            //us back until you have a cluster that contains a block from this
-            //track. (Of course, that's not cheap either, since our caller
-            //would have to scan the each cluster as it's loaded, so that
-            //would just push back the problem.)
-
-            pNextEntry = NULL;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        pNextEntry = pCluster->GetFirst();
-
-        if (pNextEntry == NULL)  //empty cluster
-            continue;
-
-        ++i;
-
-        if (i >= 100)
-            break;
-    }
-
-    //NOTE: if we get here, it means that we didn't find a block with
-    //a matching track number after lots of searching, so we give
-    //up trying.
-
-    pNextEntry = GetEOS();  //so we can return a non-NULL value
-    return 1;
-}
-
-
-Track::EOSBlock::EOSBlock()
-{
-}
-
-
-bool Track::EOSBlock::EOS() const
-{
-    return true;
-}
-
-
-const Cluster* Track::EOSBlock::GetCluster() const
-{
-    return NULL;
-}
-
-
-size_t Track::EOSBlock::GetIndex() const
-{
-    return 0;
-}
-
-
-const Block* Track::EOSBlock::GetBlock() const
-{
-    return NULL;
-}
-
-
-bool Track::EOSBlock::IsBFrame() const
-{
-    return false;
-}
-
-
-VideoTrack::VideoTrack(
-    Segment* pSegment,
-    const Info& i,
-    long long element_start,
-    long long element_size) :
-    Track(pSegment, i, element_start, element_size),
-    m_width(-1),
-    m_height(-1),
-    m_rate(-1)
-{
-    assert(i.type == 1);
-    assert(i.number > 0);
-
-    IMkvReader* const pReader = pSegment->m_pReader;
-
-    const Settings& s = i.settings;
-    assert(s.start >= 0);
-    assert(s.size >= 0);
-
-    long long pos = s.start;
-    assert(pos >= 0);
-
-    const long long stop = pos + s.size;
-
-    while (pos < stop)
-    {
-#ifdef _DEBUG
-        long len;
-        const long long id = ReadUInt(pReader, pos, len);
-        assert(id >= 0);  //TODO: handle error case
-        assert((pos + len) <= stop);
-#endif
-        if (Match(pReader, pos, 0x30, m_width))
-            ;
-        else if (Match(pReader, pos, 0x3A, m_height))
-            ;
-        else if (Match(pReader, pos, 0x0383E3, m_rate))
-            ;
-        else
-        {
-            long len;
-            const long long id = ReadUInt(pReader, pos, len);
-            assert(id >= 0);  //TODO: handle error case
-            assert((pos + len) <= stop);
-
-            pos += len;  //consume id
-
-            const long long size = ReadUInt(pReader, pos, len);
-            assert(size >= 0);  //TODO: handle error case
-            assert((pos + len) <= stop);
-
-            pos += len;  //consume length of size
-            assert((pos + size) <= stop);
-
-            //pos now designates start of payload
-
-            pos += size;  //consume payload
-            assert(pos <= stop);
-        }
-    }
-
-    return;
-}
-
-
-bool VideoTrack::VetEntry(const BlockEntry* pBlockEntry) const
-{
-    assert(pBlockEntry);
-
-    const Block* const pBlock = pBlockEntry->GetBlock();
-    assert(pBlock);
-    assert(pBlock->GetTrackNumber() == m_info.number);
-
-    return pBlock->IsKey();
-}
-
-
-long VideoTrack::Seek(
-    long long time_ns,
-    const BlockEntry*& pResult) const
-{
-    const long status = GetFirst(pResult);
-
-    if (status < 0)  //buffer underflow, etc
-        return status;
-
-    assert(pResult);
-
-    if (pResult->EOS())
-        return 0;
-
-    const Cluster* pCluster = pResult->GetCluster();
-    assert(pCluster);
-    assert(pCluster->GetIndex() >= 0);
-
-    if (time_ns <= pResult->GetBlock()->GetTime(pCluster))
-        return 0;
-
-    Cluster** const clusters = m_pSegment->m_clusters;
-    assert(clusters);
-
-    const long count = m_pSegment->GetCount();  //loaded only, not pre-loaded
-    assert(count > 0);
-
-    Cluster** const i = clusters + pCluster->GetIndex();
-    assert(i);
-    assert(*i == pCluster);
-    assert(pCluster->GetTime() <= time_ns);
-
-    Cluster** const j = clusters + count;
-
-    Cluster** lo = i;
-    Cluster** hi = j;
-
-    while (lo < hi)
-    {
-        //INVARIANT:
-        //[i, lo) <= time_ns
-        //[lo, hi) ?
-        //[hi, j)  > time_ns
-
-        Cluster** const mid = lo + (hi - lo) / 2;
-        assert(mid < hi);
-
-        pCluster = *mid;
-        assert(pCluster);
-        assert(pCluster->GetIndex() >= 0);
-        assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters));
-
-        const long long t = pCluster->GetTime();
-
-        if (t <= time_ns)
-            lo = mid + 1;
-        else
-            hi = mid;
-
-        assert(lo <= hi);
-    }
-
-    assert(lo == hi);
-    assert(lo > i);
-    assert(lo <= j);
-
-    pCluster = *--lo;
-    assert(pCluster);
-    assert(pCluster->GetTime() <= time_ns);
-
-    pResult = pCluster->GetEntry(this, time_ns);
-
-    if ((pResult != 0) && !pResult->EOS())  //found a keyframe
-        return 0;
-
-    while (lo != i)
-    {
-        pCluster = *--lo;
-        assert(pCluster);
-        assert(pCluster->GetTime() <= time_ns);
-
-        //TODO:
-        //We need to handle the case when a cluster
-        //contains multiple keyframes.  Simply returning
-        //the largest keyframe on the cluster isn't
-        //good enough.
-        pResult = pCluster->GetMaxKey(this);
-
-        if ((pResult != 0) && !pResult->EOS())
-            return 0;
-    }
-
-    //weird: we're on the first cluster, but no keyframe found
-    //should never happen but we must return something anyway
-
-    pResult = GetEOS();
-    return 0;
-}
-
-
-long long VideoTrack::GetWidth() const
-{
-    return m_width;
-}
-
-
-long long VideoTrack::GetHeight() const
-{
-    return m_height;
-}
-
-
-double VideoTrack::GetFrameRate() const
-{
-    return m_rate;
-}
-
-
-AudioTrack::AudioTrack(
-    Segment* pSegment,
-    const Info& i,
-    long long element_start,
-    long long element_size) :
-    Track(pSegment, i, element_start, element_size),
-    m_rate(0.0),
-    m_channels(0),
-    m_bitDepth(-1)
-{
-    assert(i.type == 2);
-    assert(i.number > 0);
-
-    IMkvReader* const pReader = pSegment->m_pReader;
-
-    const Settings& s = i.settings;
-    assert(s.start >= 0);
-    assert(s.size >= 0);
-
-    long long pos = s.start;
-    assert(pos >= 0);
-
-    const long long stop = pos + s.size;
-
-    while (pos < stop)
-    {
-#ifdef _DEBUG
-        long len;
-        const long long id = ReadUInt(pReader, pos, len);
-        assert(id >= 0);  //TODO: handle error case
-        assert((pos + len) <= stop);
-#endif
-        if (Match(pReader, pos, 0x35, m_rate))
-            ;
-        else if (Match(pReader, pos, 0x1F, m_channels))
-            ;
-        else if (Match(pReader, pos, 0x2264, m_bitDepth))
-            ;
-        else
-        {
-            long len;
-            const long long id = ReadUInt(pReader, pos, len);
-            assert(id >= 0);  //TODO: handle error case
-            assert((pos + len) <= stop);
-
-            pos += len;  //consume id
-
-            const long long size = ReadUInt(pReader, pos, len);
-            assert(size >= 0);  //TODO: handle error case
-            assert((pos + len) <= stop);
-
-            pos += len;  //consume length of size
-            assert((pos + size) <= stop);
-
-            //pos now designates start of payload
-
-            pos += size;  //consume payload
-            assert(pos <= stop);
-        }
-    }
-
-    if (m_channels <= 0)
-        m_channels = 1;  //Matroska spec says this is the default
-
-    return;
-}
-
-
-bool AudioTrack::VetEntry(const BlockEntry* pBlockEntry) const
-{
-    assert(pBlockEntry);
-
-    const Block* const pBlock = pBlockEntry->GetBlock();
-    assert(pBlock);
-    assert(pBlock->GetTrackNumber() == m_info.number);
-
-    return true;
-}
-
-
-long AudioTrack::Seek(
-    long long time_ns,
-    const BlockEntry*& pResult) const
-{
-    const long status = GetFirst(pResult);
-
-    if (status < 0)  //buffer underflow, etc
-        return status;
-
-    assert(pResult);
-
-    if (pResult->EOS())
-        return 0;
-
-    const Cluster* pCluster = pResult->GetCluster();
-    assert(pCluster);
-    assert(pCluster->GetIndex() >= 0);
-
-    if (time_ns <= pResult->GetBlock()->GetTime(pCluster))
-        return 0;
-
-    Cluster** const clusters = m_pSegment->m_clusters;
-    assert(clusters);
-
-    const long count = m_pSegment->GetCount();  //loaded only, not preloaded
-    assert(count > 0);
-
-    Cluster** const i = clusters + pCluster->GetIndex();
-    assert(i);
-    assert(*i == pCluster);
-    assert(pCluster->GetTime() <= time_ns);
-
-    Cluster** const j = clusters + count;
-
-    Cluster** lo = i;
-    Cluster** hi = j;
-
-    while (lo < hi)
-    {
-        //INVARIANT:
-        //[i, lo) <= time_ns
-        //[lo, hi) ?
-        //[hi, j)  > time_ns
-
-        Cluster** const mid = lo + (hi - lo) / 2;
-        assert(mid < hi);
-
-        pCluster = *mid;
-        assert(pCluster);
-        assert(pCluster->GetIndex() >= 0);
-        assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters));
-
-        const long long t = pCluster->GetTime();
-
-        if (t <= time_ns)
-            lo = mid + 1;
-        else
-            hi = mid;
-
-        assert(lo <= hi);
-    }
-
-    assert(lo == hi);
-    assert(lo > i);
-    assert(lo <= j);
-
-    while (lo > i)
-    {
-        pCluster = *--lo;
-        assert(pCluster);
-        assert(pCluster->GetTime() <= time_ns);
-
-        pResult = pCluster->GetEntry(this);
-
-        if ((pResult != 0) && !pResult->EOS())
-            return 0;
-
-        //landed on empty cluster (no entries)
-    }
-
-    pResult = GetEOS();  //weird
-    return 0;
-}
-
-
-double AudioTrack::GetSamplingRate() const
-{
-    return m_rate;
-}
-
-
-long long AudioTrack::GetChannels() const
-{
-    return m_channels;
-}
-
-long long AudioTrack::GetBitDepth() const
-{
-    return m_bitDepth;
-}
-
-Tracks::Tracks(
-    Segment* pSegment,
-    long long start,
-    long long size_,
-    long long element_start,
-    long long element_size) :
-    m_pSegment(pSegment),
-    m_start(start),
-    m_size(size_),
-    m_trackEntries(NULL),
-    m_trackEntriesEnd(NULL),
-    m_element_start(element_start),
-    m_element_size(element_size)
-{
-    long long stop = m_start + m_size;
-    IMkvReader* const pReader = m_pSegment->m_pReader;
-
-    long long pos1 = m_start;
-    int count = 0;
-
-    while (pos1 < stop)
-    {
-        long len;
-        const long long id = ReadUInt(pReader, pos1, len);
-        assert(id >= 0);
-        assert((pos1 + len) <= stop);
-
-        pos1 += len;  //consume id
-
-        const long long size = ReadUInt(pReader, pos1, len);
-        assert(size >= 0);
-        assert((pos1 + len) <= stop);
-
-        pos1 += len;  //consume length of size
-
-        //pos now desinates start of element
-        if (id == 0x2E)  //TrackEntry ID
-            ++count;
-
-        pos1 += size;  //consume payload
-        assert(pos1 <= stop);
-    }
-
-    if (count <= 0)
-        return;
-
-    m_trackEntries = new Track*[count];
-    m_trackEntriesEnd = m_trackEntries;
-
-    long long pos = m_start;
-
-    while (pos < stop)
-    {
-        long len;
-        const long long id = ReadUInt(pReader, pos, len);
-        assert(id >= 0);
-        assert((pos + len) <= stop);
-
-        const long long element_start = pos;
-
-        pos += len;  //consume id
-
-        const long long size1 = ReadUInt(pReader, pos, len);
-        assert(size1 >= 0);
-        assert((pos + len) <= stop);
-
-        pos += len;  //consume length of size
-
-        //pos now desinates start of element
-
-        const long long element_size = size1 + pos - element_start;
-
-        if (id == 0x2E)  //TrackEntry ID
-        {
-            Track*& pTrack = *m_trackEntriesEnd;
-            ParseTrackEntry(pos, size1, pTrack, element_start, element_size);
-
-            if (pTrack)
-                ++m_trackEntriesEnd;
-        }
-
-        pos += size1;  //consume payload
-        assert(pos <= stop);
-    }
-}
-
-
-unsigned long Tracks::GetTracksCount() const
-{
-    const ptrdiff_t result = m_trackEntriesEnd - m_trackEntries;
-    assert(result >= 0);
-
-    return static_cast<unsigned long>(result);
-}
-
-
-void Tracks::ParseTrackEntry(
-    long long start,
-    long long size,
-    Track*& pTrack,
-    long long element_start,
-    long long element_size)
-{
-    IMkvReader* const pReader = m_pSegment->m_pReader;
-
-    long long pos = start;
-    const long long stop = start + size;
-
-    Track::Info i;
-
-    Track::Settings videoSettings;
-    videoSettings.start = -1;
-
-    Track::Settings audioSettings;
-    audioSettings.start = -1;
-
-    long long lacing = 1;  //default is true
-
-    while (pos < stop)
-    {
-#ifdef _DEBUG
-        long len;
-        const long long id = ReadUInt(pReader, pos, len);
-        len;
-        id;
-#endif
-        if (Match(pReader, pos, 0x57, i.number))
-            assert(i.number > 0);
-        //else if (Match(pReader, pos, 0x33C5, i.uid))
-        //    ;
-        else if (Match(pReader, pos, 0x03, i.type))
-            ;
-        else if (Match(pReader, pos, 0x136E, i.nameAsUTF8))
-            assert(i.nameAsUTF8);
-        else if (Match(pReader, pos, 0x06, i.codecId))
-            ;
-        else if (Match(pReader, pos, 0x1C, lacing))
-            assert(lacing <= 1);
-        else if (Match(pReader,
-                       pos,
-                       0x23A2,
-                       i.codecPrivate,
-                       i.codecPrivateSize))
-            ;
-        else if (Match(pReader, pos, 0x058688, i.codecNameAsUTF8))
-            assert(i.codecNameAsUTF8);
-        else
-        {
-            long len;
-
-            const long long idpos = pos;
-            idpos;
-
-            const long long id = ReadUInt(pReader, pos, len);
-            assert(id >= 0);  //TODO: handle error case
-            assert((pos + len) <= stop);
-
-            pos += len;  //consume id
-
-            const long long size = ReadUInt(pReader, pos, len);
-            assert(size >= 0);  //TODO: handle error case
-            assert((pos + len) <= stop);
-
-            pos += len;  //consume length of size
-            const long long start = pos;
-
-            pos += size;  //consume payload
-            assert(pos <= stop);
-
-            if (id == 0x60)
-            {
-                videoSettings.start = start;
-                videoSettings.size = size;
-            }
-            else if (id == 0x61)
-            {
-                audioSettings.start = start;
-                audioSettings.size = size;
-            }
-            else if (id == 0x33C5)  //Track UID
-            {
-                assert(size <= 8);
-
-                i.uid = 0;
-                long long pos_ = start;
-                const long long pos_end = start + size;
-
-                while (pos_ != pos_end)
-                {
-                    unsigned char b;
-
-                    const long status = pReader->Read(pos_, 1, &b);
-                    assert(status == 0);
-
-                    i.uid <<= 8;
-                    i.uid |= b;
-
-                    ++pos_;
-                }
-            }
-        }
-    }
-
-    assert(pos == stop);
-    //TODO: propertly vet info.number, to ensure both its existence,
-    //and that it is unique among all tracks.
-    assert(i.number > 0);
-
-    i.lacing = (lacing > 0) ? true : false;
-
-    //TODO: vet settings, to ensure that video settings (0x60)
-    //were specified when type = 1, and that audio settings (0x61)
-    //were specified when type = 2.
-    if (i.type == 1)  //video
-    {
-        assert(audioSettings.start < 0);
-        assert(videoSettings.start >= 0);
-
-        i.settings = videoSettings;
-
-        VideoTrack* const t = new VideoTrack(
-            m_pSegment,
-            i,
-            element_start,
-            element_size);
-        assert(t);  //TODO
-        pTrack = t;
-    }
-    else if (i.type == 2)  //audio
-    {
-        assert(videoSettings.start < 0);
-        assert(audioSettings.start >= 0);
-
-        i.settings = audioSettings;
-
-        AudioTrack* const t = new  AudioTrack(
-            m_pSegment,
-            i,
-            element_start,
-            element_size);
-        assert(t);  //TODO
-        pTrack = t;
-    }
-    else
-    {
-        // for now we do not support other track types yet.
-        // TODO: support other track types
-        i.Clear();
-
-        pTrack = NULL;
-    }
-
-    return;
-}
-
-
-Tracks::~Tracks()
-{
-    Track** i = m_trackEntries;
-    Track** const j = m_trackEntriesEnd;
-
-    while (i != j)
-    {
-        Track* const pTrack = *i++;
-        delete pTrack;
-    }
-
-    delete[] m_trackEntries;
-}
-
-const Track* Tracks::GetTrackByNumber(unsigned long tn_) const
-{
-    const long long tn = tn_;
-
-    Track** i = m_trackEntries;
-    Track** const j = m_trackEntriesEnd;
-
-    while (i != j)
-    {
-        Track* const pTrack = *i++;
-
-        if (pTrack == NULL)
-            continue;
-
-        if (tn == pTrack->GetNumber())
-            return pTrack;
-    }
-
-    return NULL;  //not found
-}
-
-
-const Track* Tracks::GetTrackByIndex(unsigned long idx) const
-{
-    const ptrdiff_t count = m_trackEntriesEnd - m_trackEntries;
-
-    if (idx >= static_cast<unsigned long>(count))
-         return NULL;
-
-    return m_trackEntries[idx];
-}
-
-
-long long Cluster::Unparsed() const
-{
-    if (m_size < 0)  //not even partially loaded
-        return LLONG_MAX;
-
-    assert(m_pos >= m_element_start);
-    assert(m_element_size > m_size);
-
-    const long long element_stop = m_element_start + m_element_size;
-    assert(m_pos <= element_stop);
-
-    const long long result = element_stop - m_pos;
-    assert(result >= 0);
-
-    return result;
-}
-
-
-void Cluster::Load() const
-{
-    assert(m_pSegment);
-    assert(m_pos >= m_element_start);
-    assert(m_size);
-
-    if (m_size > 0)  //loaded
-    {
-        assert(m_timecode >= 0);
-        return;
-    }
-
-    assert(m_pos == m_element_start);
-    assert(m_size < 0);
-    assert(m_timecode < 0);
-
-    IMkvReader* const pReader = m_pSegment->m_pReader;
-
-    //m_pos *= -1;                                  //relative to segment
-    //long long pos = m_pSegment->m_start + m_pos;  //absolute
-
-    long len;
-
-    const long long id_ = ReadUInt(pReader, m_pos, len);
-    assert(id_ >= 0);
-    assert(id_ == 0x0F43B675);  //Cluster ID
-
-    m_pos += len;  //consume id
-
-    m_size = ReadUInt(pReader, m_pos, len);
-    assert(m_size >= 0);
-
-    m_pos += len;  //consume size field
-
-    const long long stop = m_pos + m_size;
-
-    const long long element_size = stop - m_element_start;
-    assert((m_element_size <= 0) || (m_element_size == element_size));
-
-    if (m_element_size <= 0)
-        m_element_size = element_size;
-
-    long long timecode = -1;
-
-    while (m_pos < stop)
-    {
-        if (Match(pReader, m_pos, 0x67, timecode))
-            break;
-        else
-        {
-            const long long id = ReadUInt(pReader, m_pos, len);
-            assert(id >= 0);  //TODO
-            assert((m_pos + len) <= stop);
-
-            m_pos += len;  //consume id
-
-            const long long size = ReadUInt(pReader, m_pos, len);
-            assert(size >= 0);  //TODO
-            assert((m_pos + len) <= stop);
-
-            m_pos += len;  //consume size
-
-            if (id == 0x20)  //BlockGroup ID
-                break;
-
-            if (id == 0x23)  //SimpleBlock ID
-                break;
-
-            m_pos += size;  //consume payload
-            assert(m_pos <= stop);
-        }
-    }
-
-    assert(m_pos <= stop);
-    assert(timecode >= 0);
-
-    m_timecode = timecode;
-}
-
-
-long Cluster::Load(long long& pos, long& len) const
-{
-    assert(m_pSegment);
-    assert(m_pos >= m_element_start);
-    assert(m_size);
-
-    if (m_size > 0)  //loaded (partially or fully)
-    {
-        assert(m_timecode >= 0);
-        assert(m_element_size > m_size);
-        assert(m_pos <= (m_element_start + m_element_size));
-
-        return 0;
-    }
-
-    assert(m_pos == m_element_start);
-    assert(m_size < 0);
-    assert(m_timecode < 0);
-
-    IMkvReader* const pReader = m_pSegment->m_pReader;
-
-    long long total, avail;
-
-    const int status = pReader->Length(&total, &avail);
-
-    if (status < 0)  //error
-        return status;
-
-    assert((total < 0) || (avail <= total));
-
-    pos = m_pos;
-
-    long long cluster_size, cluster_stop;
-
-    {
-        if ((pos + 1) > avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        long long result = GetUIntLength(pReader, pos, len);
-
-        if (result < 0)  //error or underflow
-            return static_cast<long>(result);
-
-        if (result > 0)  //underflow (weird)
-            return E_BUFFER_NOT_FULL;
-
-        //if ((pos + len) > segment_stop)
-        //    return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > avail)
-            return E_BUFFER_NOT_FULL;
-
-        const long long id_ = ReadUInt(pReader, pos, len);
-
-        if (id_ < 0)  //error
-            return static_cast<long>(id_);
-
-        if (id_ != 0x0F43B675)  //Cluster ID
-            return E_FILE_FORMAT_INVALID;
-
-        pos += len;  //consume id
-
-        //read cluster size
-
-        if ((pos + 1) > avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        result = GetUIntLength(pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if (result > 0)  //weird
-            return E_BUFFER_NOT_FULL;
-
-        //if ((pos + len) > segment_stop)
-        //    return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > avail)
-            return E_BUFFER_NOT_FULL;
-
-        cluster_size = ReadUInt(pReader, pos, len);
-
-        if (cluster_size < 0)  //error
-            return static_cast<long>(cluster_size);
-
-        const long long unknown_size = (1LL << (7 * len)) - 1;
-
-        if (cluster_size == unknown_size)
-            return E_FILE_FORMAT_INVALID;
-
-        if (cluster_size == 0)
-            return E_FILE_FORMAT_INVALID;
-
-        pos += len;  //consume length of size of element
-
-        cluster_stop = pos + cluster_size;
-    }
-
-    //pos points to start of payload
-
-#if 0
-    len = static_cast<long>(size_);
-
-    if (cluster_stop > avail)
-        return E_BUFFER_NOT_FULL;
-#endif
-
-    long long timecode = -1;
-    long long new_pos = -1;
-    bool bBlock = false;
-
-    while (pos < cluster_stop)
-    {
-        //Parse ID
-
-        if ((pos + 1) > avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        long long result = GetUIntLength(pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if (result > 0)  //weird
-            return E_BUFFER_NOT_FULL;
-
-        if ((pos + len) > cluster_stop)
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > avail)
-            return E_BUFFER_NOT_FULL;
-
-        const long long id = ReadUInt(pReader, pos, len);
-
-        if (id < 0) //error
-            return static_cast<long>(id);
-
-        if (id == 0)
-            return E_FILE_FORMAT_INVALID;
-
-        pos += len;  //consume ID field
-
-        //Parse Size
-
-        if ((pos + 1) > avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        result = GetUIntLength(pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if (result > 0)  //weird
-            return E_BUFFER_NOT_FULL;
-
-        if ((pos + len) > cluster_stop)
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > avail)
-            return E_BUFFER_NOT_FULL;
-
-        const long long size = ReadUInt(pReader, pos, len);
-
-        if (size < 0)  //error
-            return static_cast<long>(size);
-
-        const long long unknown_size = (1LL << (7 * len)) - 1;
-
-        if (size == unknown_size)
-            return E_FILE_FORMAT_INVALID;
-
-        pos += len;  //consume size field
-
-        if (pos > cluster_stop)
-            return E_FILE_FORMAT_INVALID;
-
-        //pos now points to start of payload
-
-        if (size == 0)  //weird
-            continue;
-
-        if ((pos + size) > cluster_stop)
-            return E_FILE_FORMAT_INVALID;
-
-        if (id == 0x67)  //TimeCode ID
-        {
-            len = static_cast<long>(size);
-
-            if ((pos + size) > avail)
-                return E_BUFFER_NOT_FULL;
-
-            timecode = UnserializeUInt(pReader, pos, size);
-
-            if (timecode < 0)  //error (or underflow)
-                return static_cast<long>(timecode);
-
-            new_pos = pos + size;
-
-            if (bBlock)
-                break;
-        }
-        else if (id == 0x20)  //BlockGroup ID
-        {
-            bBlock = true;
-            break;
-        }
-        else if (id == 0x23)  //SimpleBlock ID
-        {
-            bBlock = true;
-            break;
-        }
-
-        pos += size;  //consume payload
-        assert(pos <= cluster_stop);
-    }
-
-    assert(pos <= cluster_stop);
-
-    if (timecode < 0)  //no timecode found
-        return E_FILE_FORMAT_INVALID;
-
-    if (!bBlock)
-        return E_FILE_FORMAT_INVALID;
-
-    m_pos = new_pos;  //designates position just beyond timecode payload
-    m_size = cluster_size;  // m_size > 0 means we're partially loaded
-    m_element_size = cluster_stop - m_element_start;
-
-    m_timecode = timecode;  // m_timecode >= 0 means we're partially loaded
-
-    //LoadBlockEntries();
-
-    return 0;
-}
-
-
-long Cluster::Parse(long long& pos, long& len) const
-{
-    long status = Load(pos, len);
-
-    if (status < 0)
-        return status;
-
-    assert(m_pos >= m_element_start);
-    assert(m_size > 0);
-    assert(m_element_size > m_size);
-    assert(m_timecode >= 0);
-
-    const long long cluster_stop = m_element_start + m_element_size;
-
-    if (m_pos >= cluster_stop)
-        return 1;  //nothing else to do
-
-    IMkvReader* const pReader = m_pSegment->m_pReader;
-
-    long long total, avail;
-
-    status = pReader->Length(&total, &avail);
-
-    if (status < 0)  //error
-        return status;
-
-    assert((total < 0) || (avail <= total));
-
-    pos = m_pos;
-
-    while (pos < cluster_stop)
-    {
-        //Parse ID
-
-        if ((pos + 1) > avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        long long result = GetUIntLength(pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if (result > 0)  //weird
-            return E_BUFFER_NOT_FULL;
-
-        if ((pos + len) > cluster_stop)
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > avail)
-            return E_BUFFER_NOT_FULL;
-
-        const long long id = ReadUInt(pReader, pos, len);
-
-        if (id < 0) //error
-            return static_cast<long>(id);
-
-        if (id == 0)
-            return E_FILE_FORMAT_INVALID;
-
-        pos += len;  //consume ID field
-
-        //Parse Size
-
-        if ((pos + 1) > avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        result = GetUIntLength(pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if (result > 0)  //weird
-            return E_BUFFER_NOT_FULL;
-
-        if ((pos + len) > cluster_stop)
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > avail)
-            return E_BUFFER_NOT_FULL;
-
-        const long long size = ReadUInt(pReader, pos, len);
-
-        if (size < 0)  //error
-            return static_cast<long>(size);
-
-        const long long unknown_size = (1LL << (7 * len)) - 1;
-
-        if (size == unknown_size)
-            return E_FILE_FORMAT_INVALID;
-
-        pos += len;  //consume size field
-
-        if (pos > cluster_stop)
-            return E_FILE_FORMAT_INVALID;
-
-        //pos now points to start of payload
-
-        if (size == 0)  //weird
-            continue;
-
-        const long long block_start = pos;
-        const long long block_stop = pos + size;
-
-        if (block_stop > cluster_stop)
-            return E_FILE_FORMAT_INVALID;
-
-        if ((id != 0x20) && (id != 0x23))  //BlockGroup or SimpleBlock
-        {
-            pos += size;  //consume payload
-            assert(pos <= cluster_stop);
-
-            continue;
-        }
-
-        //Parse track number
-
-        if ((pos + 1) > avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        result = GetUIntLength(pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if (result > 0)  //weird
-            return E_BUFFER_NOT_FULL;
-
-        if ((pos + len) > block_stop)
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > avail)
-            return E_BUFFER_NOT_FULL;
-
-        const long long track = ReadUInt(pReader, pos, len);
-
-        if (track < 0) //error
-            return static_cast<long>(track);
-
-        if (track == 0)
-            return E_FILE_FORMAT_INVALID;
-
-        pos += len;  //consume track number
-
-        if (pos >= block_stop)
-            return E_FILE_FORMAT_INVALID;
-
-        pos += 2;  //consume timecode
-
-        if (pos >= block_stop)
-            return E_FILE_FORMAT_INVALID;
-
-        if (pos >= avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        unsigned char flags;
-
-        status = pReader->Read(pos, 1, &flags);
-
-        if (status < 0)  //error or underflow
-        {
-            len = 1;
-            return status;
-        }
-
-        ++pos;  //consume flags byte
-
-        if (pos >= block_stop)
-            return E_FILE_FORMAT_INVALID;
-
-        const int lacing = int(flags & 0x06) >> 1;
-
-        if ((lacing != 0) && (block_stop > avail))
-        {
-            len = static_cast<long>(block_stop - pos);
-            return E_BUFFER_NOT_FULL;
-        }
-
-        ParseBlock(id, block_start, size);
-
-        m_pos = block_stop;
-        assert(m_pos <= cluster_stop);
-
-        return 0;  //success
-    }
-
-    m_pos = pos;
-    assert(m_pos <= cluster_stop);
-
-    return 1;  //no more entries
-}
-
-
-long Cluster::GetEntry(long index, const mkvparser::BlockEntry*& pEntry) const
-{
-    assert(m_pos >= m_element_start);
-
-    pEntry = 0;
-
-    if (index < 0)
-        return -1;  //generic error
-
-    if (m_entries_count < 0)
-        return E_BUFFER_NOT_FULL;
-
-    assert(m_entries);
-    assert(m_entries_size > 0);
-    assert(m_entries_count <= m_entries_size);
-    assert(m_size > 0);
-    assert(m_element_size > m_size);
-
-    if (index < m_entries_count)
-    {
-        pEntry = m_entries[index];
-        assert(pEntry);
-
-        return 1;  //found entry
-    }
-
-    const long long element_stop = m_element_start + m_element_size;
-
-    if (m_pos >= element_stop)
-        return 0;  //nothing left to parse
-
-    return E_BUFFER_NOT_FULL;  //underflow, since more remains to be parsed
-}
-
-
-Cluster* Cluster::Create(
-    Segment* pSegment,
-    long idx,
-    long long off,
-    long long element_size)
-{
-    assert(pSegment);
-    assert(off >= 0);
-
-    const long long element_start = pSegment->m_start + off;
-
-    Cluster* const pCluster = new Cluster(pSegment,
-                                          idx,
-                                          //-off,  //means preloaded only
-                                          element_start,
-                                          element_size);
-    assert(pCluster);
-
-    return pCluster;
-}
-
-
-Cluster::Cluster() :
-    m_pSegment(NULL),
-    m_index(0),
-    m_pos(0),
-    m_size(0),
-    m_element_start(0),
-    m_element_size(0),
-    m_timecode(0),
-    m_entries(NULL),
-    m_entries_size(0),
-    m_entries_count(0)  //means "no entries"
-{
-}
-
-
-Cluster::Cluster(
-    Segment* pSegment,
-    long idx,
-    long long element_start,
-    long long element_size) :
-    m_pSegment(pSegment),
-    m_index(idx),
-    m_pos(element_start),
-    m_element_start(element_start),
-    m_element_size(element_size),
-    m_size(-1),
-    m_timecode(-1),
-    m_entries(NULL),
-    m_entries_size(0),
-    m_entries_count(-1)  //means "has not been parsed yet"
-{
-}
-
-
-Cluster::~Cluster()
-{
-    if (m_entries_count <= 0)
-        return;
-
-    BlockEntry** i = m_entries;
-    BlockEntry** const j = m_entries + m_entries_count;
-
-    while (i != j)
-    {
-         BlockEntry* p = *i++;
-         assert(p);
-
-         delete p;
-    }
-
-    delete[] m_entries;
-}
-
-
-bool Cluster::EOS() const
-{
-    return (m_pSegment == NULL);
-}
-
-
-long Cluster::GetIndex() const
-{
-    return m_index;
-}
-
-
-long long Cluster::GetPosition() const
-{
-    const long long pos = m_element_start - m_pSegment->m_start;
-    assert(pos >= 0);
-
-    return pos;
-}
-
-
-long long Cluster::GetElementSize() const
-{
-    return m_element_size;
-}
-
-
-#if 0
-bool Cluster::HasBlockEntries(
-    const Segment* pSegment,
-    long long off)  //relative to start of segment payload
-{
-    assert(pSegment);
-    assert(off >= 0);  //relative to segment
-
-    IMkvReader* const pReader = pSegment->m_pReader;
-
-    long long pos = pSegment->m_start + off;  //absolute
-    long long size;
-
-    {
-        long len;
-
-        const long long id = ReadUInt(pReader, pos, len);
-        id;
-        assert(id >= 0);
-        assert(id == 0x0F43B675);  //Cluster ID
-
-        pos += len;  //consume id
-
-        size = ReadUInt(pReader, pos, len);
-        assert(size > 0);
-
-        pos += len;  //consume size
-
-        //pos now points to start of payload
-    }
-
-    const long long stop = pos + size;
-
-    while (pos < stop)
-    {
-        long len;
-
-        const long long id = ReadUInt(pReader, pos, len);
-        assert(id >= 0);  //TODO
-        assert((pos + len) <= stop);
-
-        pos += len;  //consume id
-
-        const long long size = ReadUInt(pReader, pos, len);
-        assert(size >= 0);  //TODO
-        assert((pos + len) <= stop);
-
-        pos += len;  //consume size
-
-        if (id == 0x20)  //BlockGroup ID
-            return true;
-
-        if (id == 0x23)  //SimpleBlock ID
-            return true;
-
-        pos += size;  //consume payload
-        assert(pos <= stop);
-    }
-
-    return false;
-}
-#endif
-
-
-long Cluster::HasBlockEntries(
-    const Segment* pSegment,
-    long long off,  //relative to start of segment payload
-    long long& pos,
-    long& len)
-{
-    assert(pSegment);
-    assert(off >= 0);  //relative to segment
-
-    IMkvReader* const pReader = pSegment->m_pReader;
-
-    long long total, avail;
-
-    long status = pReader->Length(&total, &avail);
-
-    if (status < 0)  //error
-        return status;
-
-    assert((total < 0) || (avail <= total));
-
-    pos = pSegment->m_start + off;  //absolute
-
-    const long long segment_stop =
-        (pSegment->m_size < 0) ? -1 : pSegment->m_start + pSegment->m_size;
-
-    long long cluster_stop;
-
-    {
-        if ((pos + 1) > avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        long long result = GetUIntLength(pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if (result > 0)  //need more data
-            return E_BUFFER_NOT_FULL;
-
-        if ((segment_stop >= 0) && ((pos + len) > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > avail)
-            return E_BUFFER_NOT_FULL;
-
-        const long long id = ReadUInt(pReader, pos, len);
-
-        if (id < 0)  //error
-            return static_cast<long>(id);
-
-        if (id != 0x0F43B675)  //weird: not cluster ID
-            return -1;         //generic error
-
-        pos += len;  //consume Cluster ID field
-
-        //read size field
-
-        if ((pos + 1) > avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        result = GetUIntLength(pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if (result > 0)  //weird
-            return E_BUFFER_NOT_FULL;
-
-        if ((segment_stop >= 0) && ((pos + len) > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > avail)
-            return E_BUFFER_NOT_FULL;
-
-        const long long size = ReadUInt(pReader, pos, len);
-
-        if (size < 0)  //error
-            return static_cast<long>(size);
-
-        const long long unknown_size = (1LL << (7 * len)) - 1;
-
-        if (size == unknown_size)
-            return E_FILE_FORMAT_INVALID;
-
-        if (size == 0)
-            return 0;  //cluster does not have entries
-
-        pos += len;  //consume size field
-
-        cluster_stop = pos + size;
-
-        if ((segment_stop >= 0) && (cluster_stop > segment_stop))
-            return E_FILE_FORMAT_INVALID;
-
-        if ((total >= 0) && (cluster_stop > total))
-            return E_FILE_FORMAT_INVALID;
-    }
-
-    //pos points to start of payload
-
-    while (pos < cluster_stop)
-    {
-        if ((pos + 1) > avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        long long result = GetUIntLength(pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if (result > 0)  //need more data
-            return E_BUFFER_NOT_FULL;
-
-        if ((pos + len) > cluster_stop)
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > avail)
-            return E_BUFFER_NOT_FULL;
-
-        const long long id = ReadUInt(pReader, pos, len);
-
-        if (id < 0)  //error
-            return static_cast<long>(id);
-
-        pos += len;  //consume id field
-
-        if (pos >= cluster_stop)
-            return E_FILE_FORMAT_INVALID;
-
-        //read size field
-
-        if ((pos + 1) > avail)
-        {
-            len = 1;
-            return E_BUFFER_NOT_FULL;
-        }
-
-        result = GetUIntLength(pReader, pos, len);
-
-        if (result < 0)  //error
-            return static_cast<long>(result);
-
-        if (result > 0)  //underflow
-            return E_BUFFER_NOT_FULL;
-
-        if ((pos + len) > cluster_stop)
-            return E_FILE_FORMAT_INVALID;
-
-        if ((pos + len) > avail)
-            return E_BUFFER_NOT_FULL;
-
-        const long long size = ReadUInt(pReader, pos, len);
-
-        if (size < 0)  //error
-            return static_cast<long>(size);
-
-        const long long unknown_size = (1LL << (7 * len)) - 1;
-
-        if (size == unknown_size)
-            return E_FILE_FORMAT_INVALID;
-
-        pos += len;  //consume size field
-
-        if (pos > cluster_stop)
-            return E_FILE_FORMAT_INVALID;
-
-        if (size == 0)  //weird
-            continue;
-
-        if ((pos + size) > cluster_stop)
-            return E_FILE_FORMAT_INVALID;
-
-        if (id == 0x20)  //BlockGroup ID
-            return 1;    //have at least one entry
-
-        if (id == 0x23)  //SimpleBlock ID
-            return 1;    //have at least one entry
-
-        pos += size;  //consume payload
-        assert(pos <= cluster_stop);
-    }
-
-    return 0;  //no entries detected
-}
-
-
-void Cluster::LoadBlockEntries() const
-{
-    //LoadBlockEntries loads all of the entries on the cluster.
-
-    //if (m_entries)
-    //    return;
-
-    //if (m_entries_count == 0)  //already parsed, and no entries found
-    //    return;
-
-    if (m_pSegment == 0)  //EOS cluster
-        return;
-
-    assert(m_pos >= m_element_start);
-    assert(m_size);  //preloaded only, or (partially) loaded
-    //assert(m_entries_count < 0);
-
-    IMkvReader* const pReader = m_pSegment->m_pReader;
-
-    //if (m_pos < 0)
-    //    m_pos *= -1;  //relative to segment
-    //long long pos = m_pSegment->m_start + m_pos;  //absolute
-
-    if (m_size < 0)
-    {
-        assert(m_pos == m_element_start);
-
-        long len;
-
-        const long long id = ReadUInt(pReader, m_pos, len);
-   //     id;
-        assert(id >= 0);
-        assert(id == 0x0F43B675);  //Cluster ID
-
-        m_pos += len;  //consume id
-
-        m_size = ReadUInt(pReader, m_pos, len);
-        assert(m_size > 0);
-
-        const long long unknown_size = (1LL << (7 * len)) - 1;
-        unknown_size;
-        assert(m_size != unknown_size);
-
-        m_pos += len;  //consume size field
-
-        //m_pos now points to start of cluster payload
-
-        const long long cluster_stop = m_pos + m_size;
-        const long long element_size = cluster_stop - m_element_start;
-        assert((m_element_size <= 0) || (m_element_size == element_size));
-
-        if (element_size <= 0)
-            m_element_size = element_size;
-    }
-
-    assert(m_size > 0);
-    assert(m_element_size > m_size);
-
-    const long long cluster_stop = m_element_start + m_element_size;
-
-    if (m_pos >= cluster_stop)
-        return;
-
-    long long timecode = -1;  //of cluster itself
-
-    //First count the number of entries (that remain)
-
-    long long pos = m_pos;
-    int entries_count = 0;  //that remain
-
-    while (pos < cluster_stop)
-    {
-        if (Match(pReader, pos, 0x67, timecode))
-        {
-            if (m_timecode >= 0)
-                assert(timecode == m_timecode);
-            else
-                m_timecode = timecode;
-        }
-        else
-        {
-            long len;
-
-            const long long id = ReadUInt(pReader, pos, len);
-            assert(id >= 0);  //TODO
-            assert((pos + len) <= cluster_stop);
-
-            pos += len;  //consume id
-
-            const long long size = ReadUInt(pReader, pos, len);
-            assert(size >= 0);  //TODO
-            assert((pos + len) <= cluster_stop);
-
-            pos += len;  //consume size
-
-            if (id == 0x20)  //BlockGroup ID
-                ++entries_count;
-            else if (id == 0x23)  //SimpleBlock ID
-                ++entries_count;
-
-            pos += size;  //consume payload
-            assert(pos <= cluster_stop);
-        }
-    }
-
-    assert(pos == cluster_stop);
-    assert(m_timecode >= 0);
-
-    if (entries_count == 0)  //nothing remains to be done
-    {
-        m_pos = pos;
-
-        if (m_entries_count < 0)
-            m_entries_count = 0;
-
-        return;
-    }
-
-    BlockEntry** ppEntry;
-
-    if (m_entries_count < 0)  //haven't parsed anything yet
-    {
-        assert(m_entries == NULL);
-        assert(m_entries_size == 0);
-
-        m_entries_size = entries_count;
-        m_entries = new BlockEntry*[m_entries_size];
-
-        ppEntry = m_entries;
-        m_entries_count = entries_count;
-    }
-    else
-    {
-        assert(m_entries);
-        assert(m_entries_size > 0);
-        assert(m_entries_count > 0);
-        assert(m_entries_count <= m_entries_size);
-
-        const long entries_size = m_entries_count + entries_count;
-
-        if (m_entries_size < entries_size)
-        {
-            BlockEntry** const entries = new BlockEntry*[entries_size];
-            assert(entries);
-
-            BlockEntry** src = m_entries;
-            BlockEntry** const src_end = src + m_entries_count;
-
-            BlockEntry** dst = entries;
-
-            while (src != src_end)
-                *dst++ = *src++;
-
-            delete[] m_entries;
-
-            m_entries = entries;
-            m_entries_size = entries_size;
-        }
-
-        ppEntry = m_entries + m_entries_count;
-        m_entries_count = entries_size;
-    }
-
-    while (m_pos < cluster_stop)
-    {
-        long len;
-        const long long id = ReadUInt(pReader, m_pos, len);
-        assert(id >= 0);  //TODO
-        assert((m_pos + len) <= cluster_stop);
-
-        m_pos += len;  //consume id
-
-        const long long size = ReadUInt(pReader, m_pos, len);
-        assert(size >= 0);  //TODO
-        assert((m_pos + len) <= cluster_stop);
-
-        m_pos += len;  //consume size
-
-        if (id == 0x20)  //BlockGroup ID
-            ParseBlockGroup(m_pos, size, ppEntry);
-        else if (id == 0x23)  //SimpleBlock ID
-            ParseSimpleBlock(m_pos, size, ppEntry);
-
-        m_pos += size;  //consume payload
-        assert(m_pos <= cluster_stop);
-    }
-
-    assert(m_pos == cluster_stop);
-    assert((ppEntry - m_entries) == m_entries_count);
-}
-
-
-
-long long Cluster::GetTimeCode() const
-{
-    Load();
-    return m_timecode;
-}
-
-
-long long Cluster::GetTime() const
-{
-    const long long tc = GetTimeCode();
-    assert(tc >= 0);
-
-    const SegmentInfo* const pInfo = m_pSegment->GetInfo();
-    assert(pInfo);
-
-    const long long scale = pInfo->GetTimeCodeScale();
-    assert(scale >= 1);
-
-    const long long t = m_timecode * scale;
-
-    return t;
-}
-
-
-long long Cluster::GetFirstTime() const
-{
-    const BlockEntry* const pEntry = GetFirst();
-
-    if (pEntry == NULL)  //empty cluster
-        return GetTime();
-
-    const Block* const pBlock = pEntry->GetBlock();
-    assert(pBlock);
-
-    return pBlock->GetTime(this);
-}
-
-
-long long Cluster::GetLastTime() const
-{
-    const BlockEntry* const pEntry = GetLast();
-
-    if (pEntry == NULL)  //empty cluster
-        return GetTime();
-
-    const Block* const pBlock = pEntry->GetBlock();
-    assert(pBlock);
-
-    return pBlock->GetTime(this);
-}
-
-
-void Cluster::ParseBlock(
-    long long id,
-    long long pos,   //absolute pos of payload
-    long long size) const
-{
-    BlockEntry** ppEntry;
-
-    if (m_entries_count < 0)  //haven't parsed anything yet
-    {
-        assert(m_entries == NULL);
-        assert(m_entries_size == 0);
-
-        m_entries_size = 1024;
-        m_entries = new BlockEntry*[m_entries_size];
-
-        ppEntry = m_entries;
-        m_entries_count = 1;
-    }
-    else
-    {
-        assert(m_entries);
-        assert(m_entries_size > 0);
-        assert(m_entries_count > 0);
-        assert(m_entries_count <= m_entries_size);
-
-        if (m_entries_count >= m_entries_size)
-        {
-            const long entries_size = 2 * m_entries_size;
-
-            BlockEntry** const entries = new BlockEntry*[entries_size];
-            assert(entries);
-
-            BlockEntry** src = m_entries;
-            BlockEntry** const src_end = src + m_entries_count;
-
-            BlockEntry** dst = entries;
-
-            while (src != src_end)
-                *dst++ = *src++;
-
-            delete[] m_entries;
-
-            m_entries = entries;
-            m_entries_size = entries_size;
-        }
-
-        ppEntry = m_entries + m_entries_count;
-        ++m_entries_count;
-    }
-
-    if (id == 0x20)  //BlockGroup ID
-        ParseBlockGroup(pos, size, ppEntry);
-    else
-    {
-        assert(id == 0x23);  //SimpleBlock ID
-        ParseSimpleBlock(pos, size, ppEntry);
-    }
-}
-
-
-void Cluster::ParseBlockGroup(
-    long long st,
-    long long sz,
-    BlockEntry**& ppEntry) const
-{
-    assert(m_entries);
-    assert(m_entries_size > 0);
-    assert(ppEntry);
-    assert(ppEntry >= m_entries);
-
-    const ptrdiff_t idx = ppEntry - m_entries;
-    assert(idx >= 0);
-    assert(idx < m_entries_size);
-
-    Cluster* const this_ = const_cast<Cluster*>(this);
-    *ppEntry++ = new BlockGroup(this_, idx, st, sz);
-}
-
-
-
-void Cluster::ParseSimpleBlock(
-    long long st,
-    long long sz,
-    BlockEntry**& ppEntry) const
-{
-    assert(m_entries);
-    assert(m_entries_size > 0);
-    assert(ppEntry);
-    assert(ppEntry >= m_entries);
-
-    const ptrdiff_t idx = ppEntry - m_entries;
-    assert(idx >= 0);
-    assert(idx < m_entries_size);
-
-    Cluster* const this_ = const_cast<Cluster*>(this);
-    *ppEntry++ = new SimpleBlock(this_, idx, st, sz);
-}
-
-
-const BlockEntry* Cluster::GetFirst() const
-{
-    LoadBlockEntries();
-
-    if ((m_entries == NULL) || (m_entries_count <= 0))
-        return NULL;
-
-    const BlockEntry* const pFirst = m_entries[0];
-    assert(pFirst);
-
-    return pFirst;
-}
-
-
-const BlockEntry* Cluster::GetLast() const
-{
-    LoadBlockEntries();
-
-    if ((m_entries == NULL) || (m_entries_count <= 0))
-        return NULL;
-
-    const long idx = m_entries_count - 1;
-
-    const BlockEntry* const pLast = m_entries[idx];
-    assert(pLast);
-
-    return pLast;
-}
-
-
-const BlockEntry* Cluster::GetNext(const BlockEntry* pEntry) const
-{
-    assert(pEntry);
-    assert(m_entries != NULL);
-    assert(m_entries_count > 0);
-
-    size_t idx = pEntry->GetIndex();
-    assert(idx < size_t(m_entries_count));
-    assert(m_entries[idx] == pEntry);
-
-    ++idx;
-
-    if (idx >= size_t(m_entries_count))
-      return NULL;
-
-    return m_entries[idx];
-}
-
-
-long Cluster::GetEntryCount() const
-{
-    return m_entries_count;
-}
-
-
-const BlockEntry* Cluster::GetEntry(
-    const Track* pTrack,
-    long long time_ns) const
-{
-    assert(pTrack);
-
-    if (m_pSegment == NULL)  //this is the special EOS cluster
-        return pTrack->GetEOS();
-
-    LoadBlockEntries();
-
-    if ((m_entries == NULL) || (m_entries_count <= 0))
-        return NULL;  //return EOS here?
-
-    const BlockEntry* pResult = pTrack->GetEOS();
-
-    BlockEntry** i = m_entries;
-    assert(i);
-
-    BlockEntry** const j = i + m_entries_count;
-
-    while (i != j)
-    {
-        const BlockEntry* const pEntry = *i++;
-        assert(pEntry);
-        assert(!pEntry->EOS());
-
-        const Block* const pBlock = pEntry->GetBlock();
-        assert(pBlock);
-
-        if (pBlock->GetTrackNumber() != pTrack->GetNumber())
-            continue;
-
-        if (pTrack->VetEntry(pEntry))
-        {
-            if (time_ns < 0)  //just want first candidate block
-                return pEntry;
-
-            const long long ns = pBlock->GetTime(this);
-
-            if (ns > time_ns)
-                break;
-
-            pResult = pEntry;
-        }
-        else if (time_ns >= 0)
-        {
-            const long long ns = pBlock->GetTime(this);
-
-            if (ns > time_ns)
-                break;
-        }
-    }
-
-    return pResult;
-}
-
-
-const BlockEntry*
-Cluster::GetEntry(
-    const CuePoint& cp,
-    const CuePoint::TrackPosition& tp) const
-{
-    assert(m_pSegment);
-
-    LoadBlockEntries();
-
-    if (m_entries == NULL)
-        return NULL;
-
-    const long long count = m_entries_count;
-
-    if (count <= 0)
-        return NULL;
-
-    const long long tc = cp.GetTimeCode();
-
-    if ((tp.m_block > 0) && (tp.m_block <= count))
-    {
-        const size_t block = static_cast<size_t>(tp.m_block);
-        const size_t index = block - 1;
-
-        const BlockEntry* const pEntry = m_entries[index];
-        assert(pEntry);
-        assert(!pEntry->EOS());
-
-        const Block* const pBlock = pEntry->GetBlock();
-        assert(pBlock);
-
-        if ((pBlock->GetTrackNumber() == tp.m_track) &&
-            (pBlock->GetTimeCode(this) == tc))
-        {
-            return pEntry;
-        }
-    }
-
-    const BlockEntry* const* i = m_entries;
-    const BlockEntry* const* const j = i + count;
-
-    while (i != j)
-    {
-#ifdef _DEBUG
-        const ptrdiff_t idx = i - m_entries;
-        idx;
-#endif
-
-        const BlockEntry* const pEntry = *i++;
-        assert(pEntry);
-        assert(!pEntry->EOS());
-
-        const Block* const pBlock = pEntry->GetBlock();
-        assert(pBlock);
-
-        if (pBlock->GetTrackNumber() != tp.m_track)
-            continue;
-
-        const long long tc_ = pBlock->GetTimeCode(this);
-        assert(tc_ >= 0);
-
-        if (tc_ < tc)
-            continue;
-
-        if (tc_ > tc)
-            return NULL;
-
-        const Tracks* const pTracks = m_pSegment->GetTracks();
-        assert(pTracks);
-
-        const long tn = static_cast<long>(tp.m_track);
-        const Track* const pTrack = pTracks->GetTrackByNumber(tn);
-
-        if (pTrack == NULL)
-            return NULL;
-
-        const long long type = pTrack->GetType();
-
-        if (type == 2)  //audio
-            return pEntry;
-
-        if (type != 1)  //not video
-            return NULL;
-
-        if (!pBlock->IsKey())
-            return NULL;
-
-        return pEntry;
-    }
-
-    return NULL;
-}
-
-
-const BlockEntry* Cluster::GetMaxKey(const VideoTrack* pTrack) const
-{
-    assert(pTrack);
-
-    if (m_pSegment == NULL)  //EOS
-        return pTrack->GetEOS();
-
-    LoadBlockEntries();
-
-    if ((m_entries == NULL) || (m_entries_count <= 0))
-        return pTrack->GetEOS();
-
-    BlockEntry** i = m_entries + m_entries_count;
-    BlockEntry** const j = m_entries;
-
-    while (i != j)
-    {
-        const BlockEntry* const pEntry = *--i;
-        assert(pEntry);
-        assert(!pEntry->EOS());
-
-        const Block* const pBlock = pEntry->GetBlock();
-        assert(pBlock);
-
-        if (pBlock->GetTrackNumber() != pTrack->GetNumber())
-            continue;
-
-        if (pBlock->IsKey())
-            return pEntry;
-    }
-
-    return pTrack->GetEOS();  //no satisfactory block found
-}
-
-
-
-BlockEntry::BlockEntry()
-{
-}
-
-
-BlockEntry::~BlockEntry()
-{
-}
-
-
-SimpleBlock::SimpleBlock(
-    Cluster* pCluster,
-    size_t idx,
-    long long start,
-    long long size) :
-    m_pCluster(pCluster),
-    m_index(idx),
-    m_block(start, size, pCluster->m_pSegment->m_pReader)
-{
-}
-
-
-bool SimpleBlock::EOS() const
-{
-    return false;
-}
-
-
-const Cluster* SimpleBlock::GetCluster() const
-{
-    return m_pCluster;
-}
-
-
-size_t SimpleBlock::GetIndex() const
-{
-    return m_index;
-}
-
-
-const Block* SimpleBlock::GetBlock() const
-{
-    return &m_block;
-}
-
-
-//bool SimpleBlock::IsBFrame() const
-//{
-//    return false;
-//}
-
-
-BlockGroup::BlockGroup(
-    Cluster* pCluster,
-    size_t idx,
-    long long start,
-    long long size_) :
-    m_pCluster(pCluster),
-    m_index(idx),
-    m_prevTimeCode(0),
-    m_nextTimeCode(0),
-    m_pBlock(NULL)  //TODO: accept multiple blocks within a block group
-{
-    IMkvReader* const pReader = m_pCluster->m_pSegment->m_pReader;
-
-    long long pos = start;
-    const long long stop = start + size_;
-
-    bool bSimpleBlock = false;
-    bool bReferenceBlock = false;
-
-    while (pos < stop)
-    {
-        short t;
-
-        if (Match(pReader, pos, 0x7B, t))
-        {
-            if (t < 0)
-                m_prevTimeCode = t;
-            else if (t > 0)
-                m_nextTimeCode = t;
-            else
-                assert(false);
-
-            bReferenceBlock = true;
-        }
-        else
-        {
-            long len;
-            const long long id = ReadUInt(pReader, pos, len);
-            assert(id >= 0);  //TODO
-            assert((pos + len) <= stop);
-
-            pos += len;  //consume ID
-
-            const long long size = ReadUInt(pReader, pos, len);
-            assert(size >= 0);  //TODO
-            assert((pos + len) <= stop);
-
-            pos += len;  //consume size
-
-            switch (id)
-            {
-                case 0x23:  //SimpleBlock ID
-                    bSimpleBlock = true;
-                    //YES, FALL THROUGH TO NEXT CASE
-
-                case 0x21:  //Block ID
-                    ParseBlock(pos, size);
-                    break;
-
-                default:
-                    break;
-            }
-
-            pos += size;  //consume payload
-            assert(pos <= stop);
-        }
-    }
-
-    assert(pos == stop);
-    assert(m_pBlock);
-
-    if (!bSimpleBlock)
-        m_pBlock->SetKey(!bReferenceBlock);
-}
-
-
-BlockGroup::~BlockGroup()
-{
-    delete m_pBlock;
-}
-
-
-void BlockGroup::ParseBlock(long long start, long long size)
-{
-    IMkvReader* const pReader = m_pCluster->m_pSegment->m_pReader;
-
-    Block* const pBlock = new Block(start, size, pReader);
-    assert(pBlock);  //TODO
-
-    //TODO: the Matroska spec says you have multiple blocks within the
-    //same block group, with blocks ranked by priority (the flag bits).
-
-    assert(m_pBlock == NULL);
-    m_pBlock = pBlock;
-}
-
-
-bool BlockGroup::EOS() const
-{
-    return false;
-}
-
-
-const Cluster* BlockGroup::GetCluster() const
-{
-    return m_pCluster;
-}
-
-
-size_t BlockGroup::GetIndex() const
-{
-    return m_index;
-}
-
-
-const Block* BlockGroup::GetBlock() const
-{
-    return m_pBlock;
-}
-
-
-short BlockGroup::GetPrevTimeCode() const
-{
-    return m_prevTimeCode;
-}
-
-
-short BlockGroup::GetNextTimeCode() const
-{
-    return m_nextTimeCode;
-}
-
-
-//bool BlockGroup::IsBFrame() const
-//{
-//    return (m_nextTimeCode > 0);
-//}
-
-
-Block::Block(long long start, long long size_, IMkvReader* pReader) :
-    m_start(start),
-    m_size(size_)
-{
-    long long pos = start;
-    const long long stop = start + size_;
-
-    long len;
-
-    m_track = ReadUInt(pReader, pos, len);
-    assert(m_track > 0);
-    assert((pos + len) <= stop);
-
-    pos += len;  //consume track number
-    assert((stop - pos) >= 2);
-
-    m_timecode = Unserialize2SInt(pReader, pos);
-
-    pos += 2;
-    assert((stop - pos) >= 1);
-
-    long status = pReader->Read(pos, 1, &m_flags);
-    assert(status == 0);
-
-#if 0
-    const int invisible = int(m_flags & 0x08) >> 3;
-    invisible;
-    assert(!invisible);  //TODO
-#endif
-
-    const int lacing = int(m_flags & 0x06) >> 1;
-
-    ++pos;  //consume flags byte
-    assert(pos <= stop);
-
-    if (lacing == 0)  //no lacing
-    {
-        m_frame_count = 1;
-        m_frames = new Frame[m_frame_count];
-
-        Frame& f = m_frames[0];
-        f.pos = pos;
-
-        const long long frame_size = stop - pos;
-        assert(frame_size <= LONG_MAX);
-
-        f.len = static_cast<long>(frame_size);
-
-        return;
-    }
-
-    assert(pos < stop);
-
-    unsigned char count;
-
-    status = pReader->Read(pos, 1, &count);
-    assert(status == 0);
-
-    ++pos;  //consume frame count
-    assert(pos <= stop);
-
-    m_frame_count = ++count;
-    m_frames = new Frame[m_frame_count];
-
-    if (lacing == 1)  //Xiph
-    {
-        Frame* pf = m_frames;
-        Frame* const pf_end = pf + m_frame_count;
-
-        long size = 0;
-
-        while (count > 1)
-        {
-            long frame_size = 0;
-
-            for (;;)
-            {
-                unsigned char val;
-
-                status = pReader->Read(pos, 1, &val);
-                assert(status == 0);
-
-                ++pos;  //consume xiph size byte
-
-                frame_size += val;
-
-                if (val < 255)
-                    break;
-            }
-
-            Frame& f = *pf++;
-            assert(pf < pf_end);
-
-            f.len = frame_size;
-            size += frame_size;  //contribution of this frame
-
-            --count;
-        }
-
-        assert(pf < pf_end);
-        assert(pos < stop);
-
-        {
-            Frame& f = *pf++;
-            assert(pf == pf_end);
-
-            const long long total_size = stop - pos;
-            assert(total_size > size);
-
-            const long long frame_size = total_size - size;
-            assert(frame_size <= LONG_MAX);
-
-            f.len = static_cast<long>(frame_size);
-        }
-
-        pf = m_frames;
-        while (pf != pf_end)
-        {
-            Frame& f = *pf++;
-            assert((pos + f.len) <= stop);
-
-            f.pos = pos;
-            pos += f.len;
-        }
-
-        assert(pos == stop);
-    }
-    else if (lacing == 2)  //fixed-size lacing
-    {
-        const long long total_size = stop - pos;
-        assert((total_size % m_frame_count) == 0);
-
-        const long long frame_size = total_size / m_frame_count;
-        assert(frame_size <= LONG_MAX);
-
-        Frame* pf = m_frames;
-        Frame* const pf_end = pf + m_frame_count;
-
-        while (pf != pf_end)
-        {
-            assert((pos + frame_size) <= stop);
-
-            Frame& f = *pf++;
-
-            f.pos = pos;
-            f.len = static_cast<long>(frame_size);
-
-            pos += frame_size;
-        }
-
-        assert(pos == stop);
-    }
-    else
-    {
-        assert(lacing == 3);  //EBML lacing
-        assert(pos < stop);
-
-        long size = 0;
-
-        long long frame_size = ReadUInt(pReader, pos, len);
-        assert(frame_size > 0);
-        assert(frame_size <= LONG_MAX);
-        assert((pos + len) <= stop);
-
-        pos += len; //consume length of size of first frame
-        assert((pos + frame_size) <= stop);
-
-        Frame* pf = m_frames;
-        Frame* const pf_end = pf + m_frame_count;
-
-        {
-            Frame& curr = *pf;
-
-            curr.len = static_cast<long>(frame_size);
-            size += curr.len;  //contribution of this frame
-        }
-
-        --count;
-
-        while (count > 1)
-        {
-            assert(pos < stop);
-            assert(pf < pf_end);
-
-            const Frame& prev = *pf++;
-            assert(pf < pf_end);
-            assert(prev.len == frame_size);
-
-            Frame& curr = *pf;
-
-            const long long delta_size_ = ReadUInt(pReader, pos, len);
-            assert(delta_size_ >= 0);
-            assert((pos + len) <= stop);
-
-            pos += len;  //consume length of (delta) size
-            assert(pos <= stop);
-
-            const int exp = 7*len - 1;
-            const long long bias = (1LL << exp) - 1LL;
-            const long long delta_size = delta_size_ - bias;
-
-            frame_size += delta_size;
-            assert(frame_size > 0);
-            assert(frame_size <= LONG_MAX);
-
-            curr.len = static_cast<long>(frame_size);
-            size += curr.len;  //contribution of this frame
-
-            --count;
-        }
-
-        {
-            assert(pos < stop);
-            assert(pf < pf_end);
-
-            const Frame& prev = *pf++;
-            assert(pf < pf_end);
-            assert(prev.len == frame_size);
-
-            Frame& curr = *pf++;
-            assert(pf == pf_end);
-
-            const long long total_size = stop - pos;
-            assert(total_size > 0);
-            assert(total_size > size);
-
-            frame_size = total_size - size;
-            assert(frame_size > 0);
-            assert(frame_size <= LONG_MAX);
-
-            curr.len = static_cast<long>(frame_size);
-        }
-
-        pf = m_frames;
-        while (pf != pf_end)
-        {
-            Frame& f = *pf++;
-            assert((pos + f.len) <= stop);
-
-            f.pos = pos;
-            pos += f.len;
-        }
-
-        assert(pos == stop);
-    }
-}
-
-
-Block::~Block()
-{
-    delete[] m_frames;
-}
-
-
-long long Block::GetTimeCode(const Cluster* pCluster) const
-{
-    assert(pCluster);
-
-    const long long tc0 = pCluster->GetTimeCode();
-    assert(tc0 >= 0);
-
-    const long long tc = tc0 + static_cast<long long>(m_timecode);
-    assert(tc >= 0);
-
-    return tc;  //unscaled timecode units
-}
-
-
-long long Block::GetTime(const Cluster* pCluster) const
-{
-    assert(pCluster);
-
-    const long long tc = GetTimeCode(pCluster);
-
-    const Segment* const pSegment = pCluster->m_pSegment;
-    const SegmentInfo* const pInfo = pSegment->GetInfo();
-    assert(pInfo);
-
-    const long long scale = pInfo->GetTimeCodeScale();
-    assert(scale >= 1);
-
-    const long long ns = tc * scale;
-
-    return ns;
-}
-
-
-long long Block::GetTrackNumber() const
-{
-    return m_track;
-}
-
-
-bool Block::IsKey() const
-{
-    return ((m_flags & static_cast<unsigned char>(1 << 7)) != 0);
-}
-
-
-void Block::SetKey(bool bKey)
-{
-    if (bKey)
-        m_flags |= static_cast<unsigned char>(1 << 7);
-    else
-        m_flags &= 0x7F;
-}
-
-
-bool Block::IsInvisible() const
-{
-    return bool(int(m_flags & 0x08) != 0);
-}
-
-
-int Block::GetFrameCount() const
-{
-    return m_frame_count;
-}
-
-
-const Block::Frame& Block::GetFrame(int idx) const
-{
-    assert(idx >= 0);
-    assert(idx < m_frame_count);
-
-    const Frame& f = m_frames[idx];
-    assert(f.pos > 0);
-    assert(f.len > 0);
-
-    return f;
-}
-
-
-long Block::Frame::Read(IMkvReader* pReader, unsigned char* buf) const
-{
-    assert(pReader);
-    assert(buf);
-
-    const long status = pReader->Read(pos, len, buf);
-    return status;
-}
-
-
-}  //end namespace mkvparser
diff --git a/engines/sludge/libwebm/mkvparser.hpp b/engines/sludge/libwebm/mkvparser.hpp
deleted file mode 100644
index 1ebfbaf..0000000
--- a/engines/sludge/libwebm/mkvparser.hpp
+++ /dev/null
@@ -1,729 +0,0 @@
-// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
-//
-// Use of this source code is governed by a BSD-style license
-// that can be found in the LICENSE file in the root of the source
-// tree. An additional intellectual property rights grant can be found
-// in the file PATENTS.  All contributing project authors may
-// be found in the AUTHORS file in the root of the source tree.
-
-#ifndef MKVPARSER_HPP
-#define MKVPARSER_HPP
-
-#include <cstdlib>
-#include <cstdio>
-#include <cstddef>
-
-namespace mkvparser
-{
-
-const int E_FILE_FORMAT_INVALID = -2;
-const int E_BUFFER_NOT_FULL = -3;
-
-class IMkvReader
-{
-public:
-    virtual int Read(long long pos, long len, unsigned char* buf) = 0;
-    virtual int Length(long long* total, long long* available) = 0;
-protected:
-    virtual ~IMkvReader();
-};
-
-long long GetUIntLength(IMkvReader*, long long, long&);
-long long ReadUInt(IMkvReader*, long long, long&);
-long long SyncReadUInt(IMkvReader*, long long pos, long long stop, long&);
-long long UnserializeUInt(IMkvReader*, long long pos, long long size);
-float Unserialize4Float(IMkvReader*, long long);
-double Unserialize8Double(IMkvReader*, long long);
-short Unserialize2SInt(IMkvReader*, long long);
-signed char Unserialize1SInt(IMkvReader*, long long);
-bool Match(IMkvReader*, long long&, unsigned long, long long&);
-bool Match(IMkvReader*, long long&, unsigned long, char*&);
-bool Match(IMkvReader*, long long&, unsigned long, unsigned char*&, size_t&);
-bool Match(IMkvReader*, long long&, unsigned long, double&);
-bool Match(IMkvReader*, long long&, unsigned long, short&);
-
-void GetVersion(int& major, int& minor, int& build, int& revision);
-
-struct EBMLHeader
-{
-    EBMLHeader();
-    ~EBMLHeader();
-    long long m_version;
-    long long m_readVersion;
-    long long m_maxIdLength;
-    long long m_maxSizeLength;
-    char* m_docType;
-    long long m_docTypeVersion;
-    long long m_docTypeReadVersion;
-
-    long long Parse(IMkvReader*, long long&);
-    void Init();
-};
-
-
-class Segment;
-class Track;
-class Cluster;
-
-class Block
-{
-    Block(const Block&);
-    Block& operator=(const Block&);
-
-public:
-    const long long m_start;
-    const long long m_size;
-
-    Block(long long start, long long size, IMkvReader*);
-    ~Block();
-
-    long long GetTrackNumber() const;
-    long long GetTimeCode(const Cluster*) const;  //absolute, but not scaled
-    long long GetTime(const Cluster*) const;      //absolute, and scaled (ns)
-    bool IsKey() const;
-    void SetKey(bool);
-    bool IsInvisible() const;
-
-    int GetFrameCount() const;  //to index frames: [0, count)
-
-    struct Frame
-    {
-        long long pos;  //absolute offset
-        long len;
-
-        long Read(IMkvReader*, unsigned char*) const;
-    };
-
-    const Frame& GetFrame(int frame_index) const;
-
-private:
-    long long m_track;   //Track::Number()
-    short m_timecode;  //relative to cluster
-    unsigned char m_flags;
-
-    Frame* m_frames;
-    int m_frame_count;
-
-};
-
-
-class BlockEntry
-{
-    BlockEntry(const BlockEntry&);
-    BlockEntry& operator=(const BlockEntry&);
-
-public:
-    virtual ~BlockEntry();
-    virtual bool EOS() const = 0;
-    virtual const Cluster* GetCluster() const = 0;
-    virtual size_t GetIndex() const = 0;
-    virtual const Block* GetBlock() const = 0;
-    //virtual bool IsBFrame() const = 0;
-
-protected:
-    BlockEntry();
-
-};
-
-
-class SimpleBlock : public BlockEntry
-{
-    SimpleBlock(const SimpleBlock&);
-    SimpleBlock& operator=(const SimpleBlock&);
-
-public:
-    SimpleBlock(Cluster*, size_t, long long start, long long size);
-
-    bool EOS() const;
-    const Cluster* GetCluster() const;
-    size_t GetIndex() const;
-    const Block* GetBlock() const;
-    //bool IsBFrame() const;
-
-protected:
-    Cluster* const m_pCluster;
-    const size_t m_index;
-    Block m_block;
-
-};
-
-
-class BlockGroup : public BlockEntry
-{
-    BlockGroup(const BlockGroup&);
-    BlockGroup& operator=(const BlockGroup&);
-
-public:
-    BlockGroup(Cluster*, size_t, long long, long long);
-    ~BlockGroup();
-
-    bool EOS() const;
-    const Cluster* GetCluster() const;
-    size_t GetIndex() const;
-    const Block* GetBlock() const;
-    //bool IsBFrame() const;
-
-    short GetPrevTimeCode() const;  //relative to block's time
-    short GetNextTimeCode() const;  //as above
-
-protected:
-    Cluster* const m_pCluster;
-    const size_t m_index;
-
-private:
-    BlockGroup(Cluster*, size_t, unsigned long);
-    void ParseBlock(long long start, long long size);
-
-    short m_prevTimeCode;
-    short m_nextTimeCode;
-
-    //TODO: the Matroska spec says you can have multiple blocks within the
-    //same block group, with blocks ranked by priority (the flag bits).
-    //For now we just cache a single block.
-#if 0
-    typedef std::deque<Block*> blocks_t;
-    blocks_t m_blocks;  //In practice should contain only a single element.
-#else
-    Block* m_pBlock;
-#endif
-
-};
-
-
-class Track
-{
-    Track(const Track&);
-    Track& operator=(const Track&);
-
-public:
-    Segment* const m_pSegment;
-    const long long m_element_start;
-    const long long m_element_size;
-    virtual ~Track();
-
-    long long GetType() const;
-    long long GetNumber() const;
-    unsigned long long GetUid() const;
-    const char* GetNameAsUTF8() const;
-    const char* GetCodecNameAsUTF8() const;
-    const char* GetCodecId() const;
-    const unsigned char* GetCodecPrivate(size_t&) const;
-    bool GetLacing() const;
-
-    const BlockEntry* GetEOS() const;
-
-    struct Settings
-    {
-        long long start;
-        long long size;
-    };
-
-    struct Info
-    {
-        long long type;
-        long long number;
-        unsigned long long uid;
-        char* nameAsUTF8;
-        char* codecId;
-        unsigned char* codecPrivate;
-        size_t codecPrivateSize;
-        char* codecNameAsUTF8;
-        bool lacing;
-        Settings settings;
-
-        Info();
-        void Clear();
-    };
-
-    long GetFirst(const BlockEntry*&) const;
-    long GetNext(const BlockEntry* pCurr, const BlockEntry*& pNext) const;
-    virtual bool VetEntry(const BlockEntry*) const = 0;
-    virtual long Seek(long long time_ns, const BlockEntry*&) const = 0;
-
-protected:
-    Track(
-        Segment*,
-        const Info&,
-        long long element_start,
-        long long element_size);
-    const Info m_info;
-
-    class EOSBlock : public BlockEntry
-    {
-    public:
-        EOSBlock();
-
-        bool EOS() const;
-        const Cluster* GetCluster() const;
-        size_t GetIndex() const;
-        const Block* GetBlock() const;
-        bool IsBFrame() const;
-    };
-
-    EOSBlock m_eos;
-
-};
-
-
-class VideoTrack : public Track
-{
-    VideoTrack(const VideoTrack&);
-    VideoTrack& operator=(const VideoTrack&);
-
-public:
-    VideoTrack(
-        Segment*,
-        const Info&,
-        long long element_start,
-        long long element_size);
-    long long GetWidth() const;
-    long long GetHeight() const;
-    double GetFrameRate() const;
-
-    bool VetEntry(const BlockEntry*) const;
-    long Seek(long long time_ns, const BlockEntry*&) const;
-
-private:
-    long long m_width;
-    long long m_height;
-    double m_rate;
-
-};
-
-
-class AudioTrack : public Track
-{
-    AudioTrack(const AudioTrack&);
-    AudioTrack& operator=(const AudioTrack&);
-
-public:
-    AudioTrack(
-        Segment*,
-        const Info&,
-        long long element_start,
-        long long element_size);
-    double GetSamplingRate() const;
-    long long GetChannels() const;
-    long long GetBitDepth() const;
-    bool VetEntry(const BlockEntry*) const;
-    long Seek(long long time_ns, const BlockEntry*&) const;
-
-private:
-    double m_rate;
-    long long m_channels;
-    long long m_bitDepth;
-};
-
-
-class Tracks
-{
-    Tracks(const Tracks&);
-    Tracks& operator=(const Tracks&);
-
-public:
-    Segment* const m_pSegment;
-    const long long m_start;
-    const long long m_size;
-    const long long m_element_start;
-    const long long m_element_size;
-
-    Tracks(
-        Segment*,
-        long long start,
-        long long size,
-        long long element_start,
-        long long element_size);
-    virtual ~Tracks();
-
-    const Track* GetTrackByNumber(unsigned long tn) const;
-    const Track* GetTrackByIndex(unsigned long idx) const;
-
-private:
-    Track** m_trackEntries;
-    Track** m_trackEntriesEnd;
-
-    void ParseTrackEntry(
-        long long,
-        long long,
-        Track*&,
-        long long element_start,
-        long long element_size);
-
-public:
-    unsigned long GetTracksCount() const;
-};
-
-
-class SegmentInfo
-{
-    SegmentInfo(const SegmentInfo&);
-    SegmentInfo& operator=(const SegmentInfo&);
-
-public:
-    Segment* const m_pSegment;
-    const long long m_start;
-    const long long m_size;
-    const long long m_element_start;
-    const long long m_element_size;
-
-    SegmentInfo(
-        Segment*,
-        long long start,
-        long long size,
-        long long element_start,
-        long long element_size);
-
-    ~SegmentInfo();
-
-    long long GetTimeCodeScale() const;
-    long long GetDuration() const;  //scaled
-    const char* GetMuxingAppAsUTF8() const;
-    const char* GetWritingAppAsUTF8() const;
-    const char* GetTitleAsUTF8() const;
-
-private:
-    long long m_timecodeScale;
-    double m_duration;
-    char* m_pMuxingAppAsUTF8;
-    char* m_pWritingAppAsUTF8;
-    char* m_pTitleAsUTF8;
-};
-
-
-class SeekHead
-{
-    SeekHead(const SeekHead&);
-    SeekHead& operator=(const SeekHead&);
-
-public:
-    Segment* const m_pSegment;
-    const long long m_start;
-    const long long m_size;
-    const long long m_element_start;
-    const long long m_element_size;
-
-    SeekHead(
-        Segment*,
-        long long start,
-        long long size,
-        long long element_start,
-        long long element_size);
-
-    ~SeekHead();
-
-    struct Entry
-    {
-        long long id;
-        long long pos;
-    };
-
-    int GetCount() const;
-    const Entry* GetEntry(int idx) const;
-
-private:
-    Entry* m_entries;
-    int m_count;
-
-    static void ParseEntry(
-        IMkvReader*,
-        long long pos,
-        long long size,
-        Entry*&);
-
-};
-
-class Cues;
-class CuePoint
-{
-    friend class Cues;
-
-    CuePoint(size_t, long long);
-    ~CuePoint();
-
-    CuePoint(const CuePoint&);
-    CuePoint& operator=(const CuePoint&);
-
-public:
-    long long m_element_start;
-    long long m_element_size;
-
-    void Load(IMkvReader*);
-
-    long long GetTimeCode() const;      //absolute but unscaled
-    long long GetTime(const Segment*) const;  //absolute and scaled (ns units)
-
-    struct TrackPosition
-    {
-        long long m_track;
-        long long m_pos;  //of cluster
-        long long m_block;
-        //codec_state  //defaults to 0
-        //reference = clusters containing req'd referenced blocks
-        //  reftime = timecode of the referenced block
-
-        void Parse(IMkvReader*, long long, long long);
-    };
-
-    const TrackPosition* Find(const Track*) const;
-
-private:
-    const size_t m_index;
-    long long m_timecode;
-    TrackPosition* m_track_positions;
-    size_t m_track_positions_count;
-
-};
-
-
-class Cues
-{
-    friend class Segment;
-
-    Cues(
-        Segment*,
-        long long start,
-        long long size,
-        long long element_start,
-        long long element_size);
-    ~Cues();
-
-    Cues(const Cues&);
-    Cues& operator=(const Cues&);
-
-public:
-    Segment* const m_pSegment;
-    const long long m_start;
-    const long long m_size;
-    const long long m_element_start;
-    const long long m_element_size;
-
-    bool Find(  //lower bound of time_ns
-        long long time_ns,
-        const Track*,
-        const CuePoint*&,
-        const CuePoint::TrackPosition*&) const;
-
-#if 0
-    bool FindNext(  //upper_bound of time_ns
-        long long time_ns,
-        const Track*,
-        const CuePoint*&,
-        const CuePoint::TrackPosition*&) const;
-#endif
-
-    const CuePoint* GetFirst() const;
-    const CuePoint* GetLast() const;
-    const CuePoint* GetNext(const CuePoint*) const;
-
-    const BlockEntry* GetBlock(
-                        const CuePoint*,
-                        const CuePoint::TrackPosition*) const;
-
-    bool LoadCuePoint() const;
-    long GetCount() const;  //loaded only
-    //long GetTotal() const;  //loaded + preloaded
-    bool DoneParsing() const;
-
-private:
-    void Init() const;
-    void PreloadCuePoint(size_t&, long long) const;
-
-    mutable CuePoint** m_cue_points;
-    mutable size_t m_count;
-    mutable size_t m_preload_count;
-    mutable long long m_pos;
-
-};
-
-
-class Cluster
-{
-    friend class Segment;
-
-    Cluster(const Cluster&);
-    Cluster& operator=(const Cluster&);
-
-public:
-    Segment* const m_pSegment;
-
-public:
-    static Cluster* Create(
-        Segment*,
-        long index,     //index in segment
-        long long off,  //offset relative to segment
-        long long element_size);
-
-    Cluster();  //EndOfStream
-    ~Cluster();
-
-    bool EOS() const;
-
-    long long GetTimeCode() const;   //absolute, but not scaled
-    long long GetTime() const;       //absolute, and scaled (nanosecond units)
-    long long GetFirstTime() const;  //time (ns) of first (earliest) block
-    long long GetLastTime() const;   //time (ns) of last (latest) block
-
-    const BlockEntry* GetFirst() const;
-    const BlockEntry* GetLast() const;
-    const BlockEntry* GetNext(const BlockEntry*) const;
-    const BlockEntry* GetEntry(const Track*, long long ns = -1) const;
-    const BlockEntry* GetEntry(
-        const CuePoint&,
-        const CuePoint::TrackPosition&) const;
-    const BlockEntry* GetMaxKey(const VideoTrack*) const;
-
-//    static bool HasBlockEntries(const Segment*, long long);
-
-    static long HasBlockEntries(
-            const Segment*,
-            long long idoff,
-            long long& pos,
-            long& size);
-
-    long GetEntryCount() const;
-
-    void Load() const;
-    long Load(long long& pos, long& size) const;
-
-    void LoadBlockEntries() const;
-
-    long Parse(long long& pos, long& size) const;
-    long GetEntry(long index, const mkvparser::BlockEntry*&) const;
-
-protected:
-    Cluster(
-        Segment*,
-        long index,
-        //long long off,
-        long long element_start,
-        long long element_size);
-
-public:
-    const long long m_element_start;
-    long long GetPosition() const;  //offset relative to segment
-
-    long GetIndex() const;
-    long long GetElementSize() const;
-    //long long GetPayloadSize() const;
-
-    long long Unparsed() const;
-
-private:
-    long m_index;
-    mutable long long m_pos;
-    mutable long long m_size;
-    mutable long long m_element_size;
-    mutable long long m_timecode;
-    mutable BlockEntry** m_entries;
-    mutable long m_entries_size;
-    mutable long m_entries_count;
-
-    void ParseBlock(long long id, long long pos, long long size) const;
-    void ParseBlockGroup(long long, long long, BlockEntry**&) const;
-    void ParseSimpleBlock(long long, long long, BlockEntry**&) const;
-
-};
-
-
-class Segment
-{
-    friend class Cues;
-    friend class VideoTrack;
-    friend class AudioTrack;
-
-    Segment(const Segment&);
-    Segment& operator=(const Segment&);
-
-private:
-    Segment(IMkvReader*, long long pos, long long size);
-
-public:
-    IMkvReader* const m_pReader;
-    const long long m_start;  //posn of segment payload
-    const long long m_size;   //size of segment payload
-    Cluster m_eos;  //TODO: make private?
-
-    static long long CreateInstance(IMkvReader*, long long, Segment*&);
-    ~Segment();
-
-    long Load();  //loads headers and all clusters
-
-    //for incremental loading
-    long long Unparsed() const;
-    long long ParseHeaders();  //stops when first cluster is found
-    //long FindNextCluster(long long& pos, long& size) const;
-    long LoadCluster(long long& pos, long& size);  //load one cluster
-    long LoadCluster();
-
-    long ParseNext(
-            const Cluster* pCurr,
-            const Cluster*& pNext,
-            long long& pos,
-            long& size);
-
-#if 0
-    //This pair parses one cluster, but only changes the state of the
-    //segment object when the cluster is actually added to the index.
-    long ParseCluster(long long& cluster_pos, long long& new_pos) const;
-    bool AddCluster(long long cluster_pos, long long new_pos);
-#endif
-
-    const SeekHead* GetSeekHead() const;
-    const Tracks* GetTracks() const;
-    const SegmentInfo* GetInfo() const;
-    const Cues* GetCues() const;
-
-    long long GetDuration() const;
-
-    unsigned long GetCount() const;
-    const Cluster* GetFirst() const;
-    const Cluster* GetLast() const;
-    const Cluster* GetNext(const Cluster*);
-
-    const Cluster* FindCluster(long long time_nanoseconds) const;
-    //const BlockEntry* Seek(long long time_nanoseconds, const Track*) const;
-
-    const Cluster* FindOrPreloadCluster(long long pos);
-
-    long ParseCues(
-        long long cues_off,  //offset relative to start of segment
-        long long& parse_pos,
-        long& parse_len);
-
-private:
-
-    long long m_pos;  //absolute file posn; what has been consumed so far
-
-    SeekHead* m_pSeekHead;
-    SegmentInfo* m_pInfo;
-    Tracks* m_pTracks;
-    Cues* m_pCues;
-    Cluster** m_clusters;
-    long m_clusterCount;         //number of entries for which m_index >= 0
-    long m_clusterPreloadCount;  //number of entries for which m_index < 0
-    long m_clusterSize;          //array size
-
-    void AppendCluster(Cluster*);
-    void PreloadCluster(Cluster*, ptrdiff_t);
-
-    //void ParseSeekHead(long long pos, long long size);
-    //void ParseSeekEntry(long long pos, long long size);
-    //void ParseCues(long long);
-
-    const BlockEntry* GetBlock(
-        const CuePoint&,
-        const CuePoint::TrackPosition&);
-
-};
-
-}  //end namespace mkvparser
-
-inline long mkvparser::Segment::LoadCluster()
-{
-    long long pos;
-    long size;
-
-    return LoadCluster(pos, size);
-}
-
-#endif  //MKVPARSER_HPP
diff --git a/engines/sludge/libwebm/mkvreader.cpp b/engines/sludge/libwebm/mkvreader.cpp
deleted file mode 100644
index 4cae468..0000000
--- a/engines/sludge/libwebm/mkvreader.cpp
+++ /dev/null
@@ -1,120 +0,0 @@
-// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
-//
-// Use of this source code is governed by a BSD-style license
-// that can be found in the LICENSE file in the root of the source
-// tree. An additional intellectual property rights grant can be found
-// in the file PATENTS.  All contributing project authors may
-// be found in the AUTHORS file in the root of the source tree.
-
-// Modified by Rikard Peterson 2011 to fit in the SLUDGE engine.
-
-#include "mkvreader.hpp"
-#include "../newfatal.h"
-#include "../fileset.h"
-
-#include <cassert>
-#include <stdio.h>
-
-#if 0
-MkvReader::MkvReader() :
-    m_file(0)
-{
-}
-
-MkvReader::~MkvReader()
-{
-    Close();
-}
-
-int MkvReader::Open(int fileNumber)
-{
-    if (! fileNumber)
-        return -1;
-
-    if (m_file)
-        return -1;
-
-	m_file = fileNumber;
-
-	setResourceForFatal (fileNumber);
-	m_length = openFileFromNum (fileNumber);
-	if (m_length == 0) {
-		finishAccess();
-		setResourceForFatal (-1);
-		return -1;
-	}
-	/*
-#ifdef WIN32
-	m_start = _ftelli64(bigDataFile);
-#else*/
-    m_start = ftell(bigDataFile);
-/*#endif
-*/
-	finishAccess();
-    return 0;
-}
-
-void MkvReader::Close()
-{
-    if (m_file)
-    {
-		finishAccess();
-		setResourceForFatal (-1);
-        m_file = 0;
-    }
-}
-
-int MkvReader::Length(long long* total, long long* available)
-{
-    if (! m_file)
-        return -1;
-
-    if (total)
-        *total = m_length;
-
-    if (available)
-        *available = m_length;
-
-    return 0;
-}
-
-int MkvReader::Read(long long offset, long len, unsigned char* buffer)
-{
-    if (! m_file)
-        return -1;
-
-    if (offset < 0)
-        return -1;
-
-    if (len < 0)
-        return -1;
-
-    if (len == 0)
-        return 0;
-
-
-    if (offset >= m_length)
-        return -1;
-
-	if (startAccess())
-		fprintf(stderr, "Warning: Datafile already in use when playing movie!\n");
-/*
-#ifdef WIN32
-    const int status = _fseeki64(bigDataFile, m_start+offset, SEEK_SET);
-
-    if (status)
-        return -1;  //error
-#else*/
-    fseek(bigDataFile, m_start+offset, SEEK_SET);
-//#endif
-
-    const size_t size = fread(buffer, 1, len, bigDataFile);
-
-	finishAccess();
-
-    if (size < size_t(len))
-        return -1;  //error
-
-    return 0;  //success
-}
-#endif
diff --git a/engines/sludge/libwebm/mkvreader.hpp b/engines/sludge/libwebm/mkvreader.hpp
deleted file mode 100644
index b46ef78..0000000
--- a/engines/sludge/libwebm/mkvreader.hpp
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
-//
-// Use of this source code is governed by a BSD-style license
-// that can be found in the LICENSE file in the root of the source
-// tree. An additional intellectual property rights grant can be found
-// in the file PATENTS.  All contributing project authors may
-// be found in the AUTHORS file in the root of the source tree.
-
-// Modified by Rikard Peterson 2011 to fit in the SLUDGE engine.
-
-#ifndef MKVREADER_HPP
-#define MKVREADER_HPP
-
-#include "mkvparser.hpp"
-#include <cstdio>
-
-class MkvReader : public mkvparser::IMkvReader
-{
-#if 0
-    MkvReader(const MkvReader&);
-    MkvReader& operator=(const MkvReader&);
-public:
-    MkvReader();
-    virtual ~MkvReader();
-
-    int Open(int fileNumber);
-    void Close();
-    bool IsOpen() const;
-
-    virtual int Read(long long position, long length, unsigned char* buffer);
-    virtual int Length(long long* total, long long* available);
-private:
-    long long m_length;
-	unsigned int m_start;
-    int m_file;
-#endif
-};
-
-#endif //MKVREADER_HPP
diff --git a/engines/sludge/module.mk b/engines/sludge/module.mk
index 2e321ea..fa1f313 100644
--- a/engines/sludge/module.mk
+++ b/engines/sludge/module.mk
@@ -42,8 +42,6 @@ MODULE_OBJS := \
 	utf8.o \
 	variable.o \
 	zbuffer.o \
-#	libwebm/mkvparser.o \
-#	libwebm/mkvreader.o \
  
 MODULE_DIRS += \
 	engines/sludge
diff --git a/engines/sludge/movie.cpp b/engines/sludge/movie.cpp
index df9031b..51f45e5 100644
--- a/engines/sludge/movie.cpp
+++ b/engines/sludge/movie.cpp
@@ -36,8 +36,6 @@
 #endif
 
 #include "sludge/CommonCode/specialsettings.h"
-#include "sludge/libwebm/mkvreader.hpp"
-#include "sludge/libwebm/mkvparser.hpp"
 
 #include "sludge/newfatal.h"
 #include "sludge/timing.h"


Commit: 07e4982027f042c0c8fb27e28bd410cb70d51b27
    https://github.com/scummvm/scummvm/commit/07e4982027f042c0c8fb27e28bd410cb70d51b27
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove #ifdef HAVE_GLES2 and clean code in graphics

Changed paths:
    engines/sludge/graphics.cpp
    engines/sludge/graphics.h
    engines/sludge/main_loop.cpp
    engines/sludge/movie.cpp
    engines/sludge/sludger.cpp
    engines/sludge/sprites.cpp
    engines/sludge/thumbnail.cpp


diff --git a/engines/sludge/graphics.cpp b/engines/sludge/graphics.cpp
index 29cc47f..dbcb691 100644
--- a/engines/sludge/graphics.cpp
+++ b/engines/sludge/graphics.cpp
@@ -21,15 +21,12 @@
  */
 
 #include "sludge/allfiles.h"
-#include "sludge/debug.h"
-#include "sludge/platform-dependent.h"
 #include "sludge/graphics.h"
 #include "sludge/language.h"
 #include "sludge/newfatal.h"
 #include "sludge/sprbanks.h"
 #include "sludge/zbuffer.h"
 #include "sludge/backdrop.h"
-#include "sludge/shaders.h"
 #include "sludge/movie.h"
 #include "sludge/stringy.h"
 #include "sludge/CommonCode/specialsettings.h"
@@ -48,232 +45,10 @@ extern int specialSettings;
 
 void setMovieViewport();
 
-#if 0
-extern GLuint backdropTextureName;
-extern GLuint snapshotTextureName;
-#endif
-
 extern unsigned int sceneWidth, sceneHeight;
 extern zBufferData zBuffer;
 extern int lightMapNumber;
-#if 0
-extern GLuint yTextureName;
-extern GLuint uTextureName;
-extern GLuint vTextureName;
-//extern GLubyte * ytex, * utex, * vtex;
-
-shaders shader;
-GLfloat aPMVMatrix[16];
-
-void sludgeDisplay();
-
-GLfloat primaryColor[4];
-GLfloat secondaryColor[4];
-#endif
-
-struct textureList *firstTexture = NULL;
-
-textureList *addTexture() {
-	textureList *newTexture = new textureList;
-	newTexture->next = firstTexture;
-	firstTexture = newTexture;
-	return newTexture;
-}
-
-#if 0
-void deleteTextures(GLsizei n, const GLuint *textures) {
-	if (firstTexture == NULL) {
-		//debugOut("Deleting texture while list is already empty.\n");
-	} else {
-		for (int i = 0; i < n; i++) {
-			bool found = false;
-			textureList *list = firstTexture;
-			if (list->name == textures[i]) {
-				found = true;
-				firstTexture = list->next;
-				delete list;
-				continue;
-			}
-
-			while (list->next) {
-				if (list->next->name == textures[i]) {
-					found = true;
-					textureList *deleteMe = list->next;
-					list->next = list->next->next;
-					delete deleteMe;
-					break;
-				}
-				list = list->next;
-			}
-			//if (!found)
-			//  debugOut("Deleting texture that was not in list.\n");
-		}
-	}
-
-	glDeleteTextures(n, textures);
-
-}
-
-void getTextureDimensions(GLuint name, GLint *width, GLint *height) {
-	textureList *list = firstTexture;
-	while (list) {
-		if (list->name == name) {
-			*width = list->width;
-			*height = list->height;
-#if !defined(HAVE_GLES2)
-			//For the following test it is assumed that glBindTexture is always
-			//called for the right texture before getTextureDimensions.
-			GLint tw, th;
-			glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &tw);
-			glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &th);
-			if (tw != *width || th != *height) {
-				debugOut("Warning: Texture dimensions don't match: They are %ix%i, but SLUDGEs bookkeeping says %ix%i.\n", tw, th, *width, *height);
-			}
-#endif
-			return;
-		}
-		list = list->next;
-	}
-	fatal("Texture not found in list.\n");
-}
-
-void storeTextureDimensions(GLuint name, GLsizei width, GLsizei height, const char *file, int line) {
-	if (! NPOT_textures && !(((height & (height - 1)) == 0) || ((width & (width - 1)) == 0))) {
-		debugOut("I was told to create a texture with dimensions %ix%i in %s @ line %d although NPOT textures are disabled.\n", width, height, file, line);
-		//height = getNextPOT(height);
-		//width = getNextPOT(width);
-	}
-
-	textureList *list = firstTexture;
-	while (list) {
-		if (list->name == name) {
-			//debugOut("Texture dimensions are overwritten.\n");
-			break;
-		}
-		list = list->next;
-	}
-	if (list == NULL) {
-		list = addTexture();
-	}
-	list->name = name;
-	list->width = width;
-	list->height = height;
-
-}
-#endif
-
-#ifdef HAVE_GLES2
-void glesCopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height) {
-	// Work around for broken glCopy(Sub)TexImage2D...
-	void *tmp = malloc(width * height * 4);
-	glReadPixels(x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, tmp);
-	glTexSubImage2D(target, level, xoffset, yoffset, width, height, GL_RGBA, GL_UNSIGNED_BYTE, tmp);
-	free(tmp);
-}
-void glesCopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border) {
-	// Work around for broken glCopy(Sub)TexImage2D...
-	void *tmp = malloc(width * height * 4);
-	glReadPixels(x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, tmp);
-	glTexImage2D(target, level, GL_RGBA, width, height, border, GL_RGBA, GL_UNSIGNED_BYTE, tmp);
-	free(tmp);
-}
-#endif
-
-#if 0
-void dcopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border, GLuint name, const char *file, int line) {
-
-	glBindTexture(GL_TEXTURE_2D, name);
-#ifdef HAVE_GLES2_
-	glesCopyTexImage2D(target, level, internalformat, x, y, width, height, border);
-#else
-	glCopyTexImage2D(target, level, internalformat, x, y, width, height, border);
-#endif
-}
-
-void dcopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, GLuint name, const char *file, int line) {
-	glBindTexture(GL_TEXTURE_2D, name);
-#ifdef HAVE_GLES2_
-	glesCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
-#else
-	glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
-#endif
-}
-
-void dtexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height,
-		GLint border, GLenum format, GLenum type, const GLvoid *data, GLuint name, const char *file, int line) {
-	storeTextureDimensions(name, width, height, file, line);
-	glBindTexture(GL_TEXTURE_2D, name);
-	glTexImage2D(target, level, internalformat, width, height, border, format, type, data);
-}
-
-void dtexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
-		GLenum format, GLenum type, const GLvoid *data, GLuint name, const char *file, int line) {
-	storeTextureDimensions(name, width, height, file, line);
-	glBindTexture(GL_TEXTURE_2D, name);
-	glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, data);
-}
-
-void setPrimaryColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a) {
-	primaryColor[0] = r;
-	primaryColor[1] = g;
-	primaryColor[2] = b;
-	primaryColor[3] = a;
-}
-
-void setSecondaryColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a) {
-	secondaryColor[0] = r;
-	secondaryColor[1] = g;
-	secondaryColor[2] = b;
-	secondaryColor[3] = a;
-}
-
-void drawQuad(GLint program, const GLfloat *vertices, int numTexCoords, ...) {
-	int i, vertexLoc, texCoordLocs[numTexCoords];
-	const GLfloat *texCoords[numTexCoords];
-
-	va_list vl;
-	va_start(vl, numTexCoords);
-	for (i = 0; i < numTexCoords; i++) {
-		texCoords[i] = va_arg(vl, const GLfloat *);
-	}
-	va_end(vl);
-
-	glUniform4f(glGetUniformLocation(program, "myColor"), primaryColor[0], primaryColor[1], primaryColor[2], primaryColor[3]);
-	if (program == shader.smartScaler || program == shader.paste) {
-		glUniform4f(glGetUniformLocation(program, "mySecondaryColor"), secondaryColor[0], secondaryColor[1], secondaryColor[2], secondaryColor[3]);
-	}
-
-	vertexLoc = glGetAttribLocation(program, "myVertex");
-	texCoordLocs[0] = glGetAttribLocation(program, "myUV0");
-	if (numTexCoords > 1) texCoordLocs[1] = glGetAttribLocation(program, "myUV1");
-	if (numTexCoords > 2) texCoordLocs[2] = glGetAttribLocation(program, "myUV2");
-	if (numTexCoords > 3) texCoordLocs[3] = glGetAttribLocation(program, "myUV3");
 
-	glEnableVertexAttribArray(vertexLoc);
-	glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, vertices);
-
-	for (i = 0; i < numTexCoords; i++) {
-		if (texCoords[i]) {
-			glEnableVertexAttribArray(texCoordLocs[i]);
-			glVertexAttribPointer(texCoordLocs[i], 2, GL_FLOAT, GL_FALSE, 0, texCoords[i]);
-		}
-	}
-
-	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
-
-	for (i = 0; i < numTexCoords; i++) {
-		if (texCoords[i]) {
-			glDisableVertexAttribArray(texCoordLocs[i]);
-		}
-	}
-	glDisableVertexAttribArray(vertexLoc);
-
-}
-
-void setPMVMatrix(GLint program) {
-	glUniformMatrix4fv(glGetUniformLocation(program, "myPMVMatrix"), 1, GL_FALSE, aPMVMatrix);
-}
-#endif
 // This is for swapping settings between rendering to texture or to the screen
 void setPixelCoords(bool pixels) {
 	static int current = -1;
@@ -325,40 +100,6 @@ void setPixelCoords(bool pixels) {
 #endif
 }
 
-int desktopW = 0, desktopH = 0;
-bool runningFullscreen = false;
-
-#if defined(HAVE_GLES2)
-void saveTexture(GLuint tex, GLubyte *data) {
-	// use an FBO to easily grab the texture...
-	static GLuint fbo = 0;
-	GLuint old_fbo;
-	GLint tw, th;
-	GLint old_vp[4];
-	if (fbo == 0) {
-		glGenFramebuffers(1, &fbo);
-	}
-	glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint *)&old_fbo);
-	glBindFramebuffer(GL_FRAMEBUFFER, fbo);
-	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0);
-	getTextureDimensions(tex, &tw, &th);
-	glGetIntegerv(GL_VIEWPORT, old_vp);
-	glViewport(0, 0, tw, th);
-	glBindFramebuffer(GL_FRAMEBUFFER, fbo);
-	glReadPixels(0, 0, tw, th, GL_RGBA, GL_UNSIGNED_BYTE, data);
-	glViewport(old_vp[0], old_vp[1], old_vp[2], old_vp[3]);
-	glBindFramebuffer(GL_FRAMEBUFFER, old_fbo);
-}
-#else
-#if 0
-void saveTexture(GLuint tex, GLubyte *data) {
-
-	glBindTexture(GL_TEXTURE_2D, tex);
-	glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
-}
-#endif
-#endif
-
 // This is for setting windowed or fullscreen graphics.
 // Used for switching, and for initial window creation.
 void setGraphicsWindow(bool fullscreen, bool restoreGraphics, bool resize) {
@@ -419,11 +160,8 @@ void setGraphicsWindow(bool fullscreen, bool restoreGraphics, bool resize) {
 
 	if (fullscreen) {
 		specialSettings &= ~SPECIAL_INVISIBLE;
-#if !defined(HAVE_GLES2)
-		videoflags = SDL_OPENGL | SDL_FULLSCREEN;
-#else
+
 		videoflags = SDL_SWSURFACE | SDL_FULLSCREEN;
-#endif
 
 		if (gameSettings.fixedPixels) {
 			viewportWidth = realWinWidth = winWidth;
@@ -450,11 +188,7 @@ void setGraphicsWindow(bool fullscreen, bool restoreGraphics, bool resize) {
 		}
 
 	} else {
-#if !defined(HAVE_GLES2)
-		videoflags = SDL_OPENGL/* | SDL_RESIZABLE*/;
-#else
 		videoflags = SDL_SWSURFACE;
-#endif
 
 		if (resize) {
 			float realAspect = (float) desktopW / desktopH;
@@ -511,14 +245,12 @@ void setGraphicsWindow(bool fullscreen, bool restoreGraphics, bool resize) {
 	}
 	debugOut("Video mode %d %d set successfully.\n", realWinWidth, realWinHeight);
 
-#if defined(HAVE_GLES2)
 	if (EGL_Open()) {
 		msgBox("Startup Error", "Couldn't initialize EGL.");
 		SDL_Quit();
 		exit(1);
 	}
 	EGL_Init();
-#endif
 
 	GLint uniform;
 	const char *Vertex;
@@ -526,9 +258,6 @@ void setGraphicsWindow(bool fullscreen, bool restoreGraphics, bool resize) {
 
 	Vertex = shaderFileRead("scale.vert");
 
-#if !defined(HAVE_GLES2)
-	Fragment = shaderFileRead("scale.frag");
-#else
 	/*  const GLubyte *str;
 	 int glDerivativesAvailable;
 	 str = glGetString (GL_EXTENSIONS);
@@ -541,7 +270,6 @@ void setGraphicsWindow(bool fullscreen, bool restoreGraphics, bool resize) {
 //	}
 
 	Fragment = joinStrings("precision mediump float;\n", Fragment);
-#endif
 
 	if (! Vertex || ! Fragment) {
 		fatal("Error loading \"scale\" shader program!", "Try re-installing the game. (scale.frag, scale_noaa.frag or scale.vert was not found.)");
@@ -579,9 +307,7 @@ void setGraphicsWindow(bool fullscreen, bool restoreGraphics, bool resize) {
 	Vertex = shaderFileRead("fixScaleSprite.vert");
 	Fragment = shaderFileRead("fixScaleSprite.frag");
 
-#if defined(HAVE_GLES2)
 	Fragment = joinStrings("precision mediump float;\n", Fragment);
-#endif
 
 	if (! Vertex || ! Fragment) {
 		fatal("Error loading \"fixScaleSprite\" shader program!", "Try re-installing the game. (fixScaleSprite.frag or fixScaleSprite.vert was not found.)");
@@ -610,9 +336,7 @@ void setGraphicsWindow(bool fullscreen, bool restoreGraphics, bool resize) {
 	Vertex = shaderFileRead("yuv.vert");
 	Fragment = shaderFileRead("yuv.frag");
 
-#if defined(HAVE_GLES2)
 	Fragment = joinStrings("precision mediump float;\n", Fragment);
-#endif
 
 	if (! Vertex || ! Fragment) {
 		fatal("Error loading \"yuv\" shader program!", "Try re-installing the game. (yuv.frag or yuv.vert was not found.)");
@@ -639,9 +363,7 @@ void setGraphicsWindow(bool fullscreen, bool restoreGraphics, bool resize) {
 	Vertex = shaderFileRead("texture.vert");
 	Fragment = shaderFileRead("texture.frag");
 
-#if defined(HAVE_GLES2)
 	Fragment = joinStrings("precision mediump float;\n", Fragment);
-#endif
 
 	if (! Vertex || ! Fragment) {
 		fatal("Error loading \"texture\" shader program!", "Try re-installing the game. (texture.frag or texture.vert was not found.)");
@@ -669,9 +391,7 @@ void setGraphicsWindow(bool fullscreen, bool restoreGraphics, bool resize) {
 	Vertex = shaderFileRead("color.vert");
 	Fragment = shaderFileRead("color.frag");
 
-#if defined(HAVE_GLES2)
 	Fragment = joinStrings("precision mediump float;\n", Fragment);
-#endif
 
 	if (! Vertex || ! Fragment) {
 		fatal("Error loading \"color\" shader program!", "Try re-installing the game. (color.frag or color.vert was not found.)");
@@ -765,85 +485,6 @@ void setGraphicsWindow(bool fullscreen, bool restoreGraphics, bool resize) {
 #endif
 }
 
-void setupOpenGLStuff() {
-
-	/*
-	 * Time to setup our requested window attributes for our OpenGL window.
-	 * We want *at least* 8 bits of red, green and blue. We also want at least a 16-bit
-	 * depth buffer.
-	 *
-	 * The last thing we do is request a double buffered window. '1' turns on double
-	 * buffering, '0' turns it off.
-	 */
-#if 0
-	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
-	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
-	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
-	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
-	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
-	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
-	setGraphicsWindow(gameSettings.userFullScreen, false);
-#endif
-#if !defined(HAVE_GLES2)
-#if 0
-	/* Check for graphics capabilities... */
-	if (GLEE_VERSION_2_0) {
-		// Yes! Textures can be any size!
-		NPOT_textures = true;
-		debugOut("OpenGL 2.0! All is good.\n");
-	} else {
-		if (GLEE_VERSION_1_5) {
-			debugOut("OpenGL 1.5!\n");
-		} else if (GLEE_VERSION_1_4) {
-			debugOut("OpenGL 1.4!\n");
-		} else if (GLEE_VERSION_1_3) {
-			debugOut("OpenGL 1.3!\n");
-		} else if (GLEE_VERSION_1_2) {
-			debugOut("OpenGL 1.2!\n");
-		}
-
-		if (GLEE_ARB_texture_non_power_of_two) {
-			// Yes! Textures can be any size!
-			NPOT_textures = true;
-		} else {
-			// Workaround needed for lesser graphics cards. Let's hope this works...
-			NPOT_textures = false;
-			debugOut("Warning: Old graphics card! GLEE_ARB_texture_non_power_of_two not supported.\n");
-		}
-
-		if (GLEE_ARB_shading_language_100) {
-			debugOut("ARB_shading_language_100 supported.\n");
-		} else {
-			debugOut("Warning: Old graphics card! ARB_shading_language_100 not supported. Try updating your drivers.\n");
-		}
-		if (GLEE_ARB_shader_objects) {
-			debugOut("ARB_shader_objects supported.\n");
-		} else {
-			fatal("Error: Old graphics card! ARB_shader_objects not supported.\n");
-		}
-		if (GLEE_ARB_vertex_shader) {
-			debugOut("ARB_vertex_shader supported.\n");
-		} else {
-			fatal("Error: Old graphics card! ARB_vertex_shader not supported.\n");
-		}
-		if (GLEE_ARB_fragment_shader) {
-			debugOut("ARB_fragment_shader supported.\n");
-		} else {
-			fatal("Error: Old graphics card! ARB_fragment_shader not supported.\n");
-		}
-	}
-#else
-	NPOT_textures = false;
-#endif
-#endif
-	int n;
-#if 0
-	glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, (GLint *) &n);
-#endif
-	debugOut("Max texture image units: %d\n", n);
-
-}
-
 // I found this function on a coding forum on the 'net.
 // Looks a bit weird, but it should work.
 int getNextPOT(int n) {
@@ -857,24 +498,4 @@ int getNextPOT(int n) {
 	return n;
 }
 
-int printOglError(const char *file, int line) {
-	/* Returns 1 if an OpenGL error occurred, 0 otherwise. */
-	int retCode = 0;
-#if 0
-	GLenum glErr;
-
-	glErr = glGetError();
-	while (glErr != GL_NO_ERROR) {
-#if !defined(HAVE_GLES2)
-		debugOut("glError in file %s @ line %d: %s\n", file, line, gluErrorString(glErr));
-#else
-		debugOut("glError in file %s @ line %d: error code %i\n", file, line, glErr);
-#endif
-		retCode = 1;
-		glErr = glGetError();
-	}
-#endif
-	return retCode;
-}
-
 } // End of namespace Sludge
diff --git a/engines/sludge/graphics.h b/engines/sludge/graphics.h
index 444d8a4..c03d194 100644
--- a/engines/sludge/graphics.h
+++ b/engines/sludge/graphics.h
@@ -26,31 +26,6 @@
 
 namespace Sludge {
 
-#if 0
-struct shaders {
-	GLuint paste;
-	GLuint smartScaler;
-	GLuint yuv;
-	GLuint texture;
-	GLuint color;
-};
-#endif
-
-struct textureList {
-#if 0
-	GLuint name;
-	GLsizei width;
-	GLsizei height;
-#endif
-	struct textureList *next;
-};
-
-#if 0
-// From Backdrop.cpp, but they're here anyway
-extern GLubyte *backdropTexture;
-extern GLfloat backdropTexW, backdropTexH;
-#endif
-
 extern unsigned int winWidth, winHeight;
 extern int viewportHeight, viewportWidth;
 extern int viewportOffsetX, viewportOffsetY;
@@ -58,50 +33,11 @@ extern int realWinWidth, realWinHeight;
 
 extern bool NPOT_textures;
 
-#if 0
-extern shaders shader;
-extern GLfloat aPMVMatrix[];
-
-void setPrimaryColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a);
-void setSecondaryColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a);
-
-void drawQuad(GLint program, const GLfloat *vertices, int numTexCoords, ...);
-
-void setPMVMatrix(GLint program);
-#endif
-
 void setPixelCoords(bool pixels);
-void setGraphicsWindow(bool fullscreen, bool restoreGraphics = true,
-		bool resize = false);
-
-void setupOpenGLStuff();
+void setGraphicsWindow(bool fullscreen, bool restoreGraphics = true, bool resize = false);
 
 int getNextPOT(int n);
 
-#if 0
-void saveTexture(GLuint tex, GLubyte *data);
-
-void dcopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border, GLuint name, const char *file, int line);
-void dcopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, GLuint name, const char *file, int line);
-void dtexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *data, GLuint name, const char *file, int line);
-void dtexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *data, GLuint name, const char *file, int line);
-
-#define copyTexImage2D(target, level, internalformat, x, y,  width, height, border, name) dcopyTexImage2D(target,  level,  internalformat,  x,  y,  width,height, border, name, __FILE__, __LINE__)
-
-#define copyTexSubImage2D(target,  level,  xoffset,yoffset, x,  y,   width,   height, name) dcopyTexSubImage2D(target,  level,  xoffset,  yoffset,  x,  y,   width,  height, name, __FILE__, __LINE__)
-
-#define texImage2D(target,  level,  internalformat,  width,  height,  border,  format, type,  data,name) dtexImage2D( target,   level,  internalformat, width, height, border,  format,  type,  data, name, __FILE__, __LINE__)
-
-#define texSubImage2D( target,  level,   xoffset,   yoffset,   width,  height, format,  type,   data,name) dtexSubImage2D( target, level,   xoffset,  yoffset,  width,  height, format,  type,  data,  name, __FILE__, __LINE__)
-
-void deleteTextures(GLsizei n, const GLuint *textures);
-
-void getTextureDimensions(GLuint name, GLint *width, GLint *height);
-
-int printOglError(const char *file, int line);
-#define printOpenGLError() printOglError(__FILE__, __LINE__)
-#endif
-
 }
  // End of namespace Sludge
 
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index d530555..636deeb 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -337,10 +337,6 @@ int main_loop(const char *filename)
 
 	killSoundStuff();
 
-#if defined(HAVE_GLES2)
-	EGL_Close();
-#endif
-
 #if 0
 	/* Clean up the SDL library */
 	SDL_Quit();
diff --git a/engines/sludge/movie.cpp b/engines/sludge/movie.cpp
index 51f45e5..2d431e8 100644
--- a/engines/sludge/movie.cpp
+++ b/engines/sludge/movie.cpp
@@ -607,11 +607,6 @@ int playMovie(int fileNumber) {
 	int frameCounter = 0;
 
 	movieStartTick = SDL_GetTicks();
-#ifdef HAVE_GLES2
-	GLuint old_fbo;
-	glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint *)&old_fbo);
-	glBindFramebuffer(GL_FRAMEBUFFER, 0);
-#endif
 
 	while (movieIsPlaying) {
 
@@ -932,18 +927,14 @@ int playMovie(int fileNumber) {
 			}
 
 			glFlush();
-#if !defined(HAVE_GLES2)
-			SDL_GL_SwapBuffers();
-#else
+
 			EGL_SwapBuffers();
-#endif
 
 		}
 		videoUpdated = false;
 	}
 
 	// Cleanup
-#ifdef HAVE_GLES2
 	glBindFramebuffer(GL_FRAMEBUFFER, old_fbo);
 
 	movieIsPlaying = nothing;
@@ -985,7 +976,7 @@ int playMovie(int fileNumber) {
 	Init_Timer();
 
 	glViewport(viewportOffsetX, viewportOffsetY, viewportWidth, viewportHeight);
-#endif
+
 	setPixelCoords(false);
 #endif
 	return 1;
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index c9005e3..26412a0 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -525,13 +525,8 @@ bool initSludge(const char *filename) {
 
 	// There's no startup window on Linux and respecting this
 	// option from the ini file would disable commandline options.
-#if defined __unix__ && !(defined __APPLE__)
 	saveIniFile(filename);
-#else
-	if (!gameSettings.noStartWindow) {
-		saveIniFile(filename);
-	}
-#endif
+
 	
 	// Now set file indices properly to the chosen language.
 	languageNum = getLanguageForFileB();
@@ -581,99 +576,6 @@ void displayBase() {
 }
 
 void sludgeDisplay() {
-#if 0
-#if defined(HAVE_GLES2)
-#ifndef GL_DEPTH24_STENCIL8
-#define GL_DEPTH24_STENCIL8 0x88F0
-#endif
-	// create an FBO
-	static GLuint fbo = 0;
-	static GLuint fbo_tex = 0;
-	static GLuint fbo_rbo = 0;
-	static float fbo_tex_w, fbo_tex_h;
-	static GLuint fbo_shad, fbo_vert, fbo_frag;
-	if (fbo == 0) {
-		// create FBO
-		int width = 1;
-		while (width < realWinWidth) width *= 2;
-		int height = 1;
-		while (height < realWinHeight) height *= 2;
-		glGenFramebuffers(1, &fbo);
-		glGenTextures(1, &fbo_tex);
-		glGenRenderbuffers(1, &fbo_rbo);
-		glBindTexture(GL_TEXTURE_2D, fbo_tex);
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
-		glBindTexture(GL_TEXTURE_2D, 0);
-		glBindRenderbuffer(GL_RENDERBUFFER, fbo_rbo);
-		glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height);
-		glBindRenderbuffer(GL_RENDERBUFFER, 0);
-		glBindFramebuffer(GL_FRAMEBUFFER, fbo);
-		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo_tex, 0);
-		glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo_rbo);
-		glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo_rbo);
-		GLenum ret = glCheckFramebufferStatus(GL_FRAMEBUFFER);
-		printf("Screen is %dx%d, FBO(%dx%d) Status = 0x%04X\n", realWinWidth, realWinHeight, width, height, ret);
-		glBindFramebuffer(GL_FRAMEBUFFER, 0);
-		glBindFramebuffer(GL_FRAMEBUFFER, fbo);
-		fbo_tex_w = (float)realWinWidth / width;
-		fbo_tex_h = (float)realWinHeight / height;
-		// create shader for blitting the fbo...
-		const char _blit_vsh[] = "                              \n\t"
-		"attribute highp vec2 aPosition;                        \n\t"
-		"attribute highp vec2 aTexCoord;                        \n\t"
-		"varying mediump vec2 vTexCoord;                        \n\t"
-		"void main(){                                           \n\t"
-		"gl_Position = vec4(aPosition.x, aPosition.y, 0.0, 1.0);\n\t"
-		"vTexCoord = aTexCoord;                                 \n\t"
-		"}                                                      \n\t";
-
-		const char _blit_fsh[] = "                              \n\t"
-		"uniform sampler2D uTex;                                \n\t"
-		"varying mediump vec2 vTexCoord;                        \n\t"
-		"void main(){                                           \n\t"
-		"gl_FragColor = texture2D(uTex, vTexCoord);             \n\t"
-		"}                                                      \n\t";
-
-		GLint success;
-		fbo_frag = glCreateShader(GL_FRAGMENT_SHADER);
-		const char *src[1];
-		src[0] = _blit_fsh;
-		glShaderSource(fbo_frag, 1, src, NULL);
-		glCompileShader(fbo_frag);
-		glGetShaderiv(fbo_frag, GL_COMPILE_STATUS, &success);
-		if (!success) {
-			printf("Failed to produce default fragment shader.\n");
-		}
-		fbo_vert = glCreateShader(GL_VERTEX_SHADER);
-		src[0] = _blit_vsh;
-		glShaderSource(fbo_vert, 1, src, NULL);
-		glCompileShader(fbo_vert);
-		glGetShaderiv(fbo_vert, GL_COMPILE_STATUS, &success);
-		if (!success) {
-			printf("Failed to produce default vertex shader.\n");
-		}
-		fbo_shad = glCreateProgram();
-		glBindAttribLocation(fbo_shad, 0, "aPosition");
-		glBindAttribLocation(fbo_shad, 1, "aTexCoord");
-		glAttachShader(fbo_shad, fbo_frag);
-		glAttachShader(fbo_shad, fbo_vert);
-		glLinkProgram(fbo_shad);
-		glGetProgramiv(fbo_shad, GL_LINK_STATUS, &success);
-		if (!success) {
-			printf("Failed to link default program.\n");
-		}
-		glUniform1i(glGetUniformLocation(fbo_shad, "uTex"), 0);
-
-	}
-#endif
-
-	glDepthMask(GL_TRUE);
-//	glClearColor(0.5, 0.5, 1.0, 0.0);
-	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Clear The Screen
-	glDepthMask(GL_FALSE);
-#endif
 	displayBase();
 	viewSpeech();// ...and anything being said
 	drawStatusBar();
@@ -681,42 +583,6 @@ void sludgeDisplay() {
 	g_system->copyRectToScreen((byte *)renderSurface.getPixels(), renderSurface.pitch, 0, 0, renderSurface.w, renderSurface.h);
 	g_system->updateScreen();
 	if (brightnessLevel < 255) fixBrightness();// This is for transitionLevel special effects
-#if 0
-	glFlush();
-#if !defined(HAVE_GLES2)
-	SDL_GL_SwapBuffers();
-#else
-	if (fbo) {
-		// blit the FBO now
-		glBindFramebuffer(GL_FRAMEBUFFER, 0);
-		GLuint old_prog;
-		glGetIntegerv(GL_CURRENT_PROGRAM, (GLint *)&old_prog);
-		glUseProgram(fbo_shad);
-		glViewport(0, 0, realWinWidth, realWinHeight);
-		const float vert[] = {
-			-1.0, -1.0, +0.0, +0.0,
-			+1.0, -1.0, fbo_tex_w, +0.0,
-			-1.0, +1.0, +0.0, fbo_tex_h,
-			+1.0, +1.0, fbo_tex_w, fbo_tex_h
-		};
-		glActiveTexture(GL_TEXTURE0);
-		glBindTexture(GL_TEXTURE_2D, fbo_tex);
-		glEnableVertexAttribArray(0);
-		glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (float *)vert);
-		glEnableVertexAttribArray(1);
-		glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (float *)vert + 2);
-		glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
-		glBindTexture(GL_TEXTURE_2D, 0);
-		glUseProgram(old_prog);
-		glViewport(viewportOffsetX, viewportOffsetY, viewportWidth, viewportHeight);
-	}
-	EGL_SwapBuffers();
-	if (fbo) {
-		// Rebind FBO now
-		glBindFramebuffer(GL_FRAMEBUFFER, fbo);
-	}
-#endif
-#endif
 }
 
 void pauseFunction(loadedFunction *fun) {
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index a89d37d..660e580 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -668,138 +668,6 @@ bool scaleSprite(sprite &single, const spritePalette &fontPal, onScreenPerson *t
 		return a != 0;
 	}
 	return false;
-
-#if 0
-	GLfloat z;
-
-	if ((!(thisPerson->extra & EXTRA_NOZB)) && zBuffer.numPanels) {
-		int i;
-		for (i = 1; i < zBuffer.numPanels; i++) {
-			if (zBuffer.panel[i] >= y + cameraY) {
-				i--;
-				break;
-			}
-		}
-		z = 0.999 - (double) i * (1.0 / 128.0);
-	} else {
-		z = -0.5;
-	}
-
-	float ltx1, ltx2, lty1, lty2;
-	if (! NPOT_textures) {
-		ltx1 = lightMap.texW * (x1 + cameraX) / sceneWidth;
-		ltx2 = lightMap.texW * (x2 + cameraX) / sceneWidth;
-		lty1 = lightMap.texH * (y1 + cameraY) / sceneHeight;
-		lty2 = lightMap.texH * (y2 + cameraY) / sceneHeight;
-	} else {
-		ltx1 = (float)(x1 + cameraX) / sceneWidth;
-		ltx2 = (float)(x2 + cameraX) / sceneWidth;
-		lty1 = (float)(y1 + cameraY) / sceneHeight;
-		lty2 = (float)(y2 + cameraY) / sceneHeight;
-	}
-
-	const GLfloat ltexCoords[] = {
-		ltx1, lty1,
-		ltx2, lty1,
-		ltx1, lty2,
-		ltx2, lty2
-	};
-
-	bool light = !(thisPerson->extra & EXTRA_NOLITE);
-	if (light && lightMap.data) {
-		if (lightMapMode == LIGHTMAPMODE_HOTSPOT) {
-			int lx = (int)(x + cameraX);
-			int ly = (int)(y + cameraY);
-
-			if (lx < 0) lx = 0;
-			else if (lx >= sceneWidth) lx = sceneWidth - 1;
-			if (ly < 0) ly = 0;
-			else if (ly >= sceneHeight) ly = sceneHeight - 1;
-
-			GLubyte *target;
-			if (! NPOT_textures) {
-				target = lightMap.data + (ly * getNextPOT(sceneWidth) + lx) * 4;
-			} else {
-				target = lightMap.data + (ly * sceneWidth + lx) * 4;
-			}
-			curLight[0] = target[0];
-			curLight[1] = target[1];
-			curLight[2] = target[2];
-		} else if (lightMapMode == LIGHTMAPMODE_PIXEL) {
-			curLight[0] = curLight[1] = curLight[2] = 255;
-
-			glActiveTexture(GL_TEXTURE1);
-			glBindTexture(GL_TEXTURE_2D, lightMap.name);
-			glActiveTexture(GL_TEXTURE0);
-
-		}
-	} else {
-		curLight[0] = curLight[1] = curLight[2] = 255;
-	}
-#ifndef HAVE_GLES2
-	if (!(thisPerson->extra & EXTRA_RECTANGULAR))
-	checkColourChange(true);
-#endif
-	setDrawMode(thisPerson);
-
-	glBindTexture(GL_TEXTURE_2D, fontPal.tex_names[single.texNum]);
-
-	glEnable(GL_BLEND);
-
-	glUseProgram(shader.smartScaler);
-	GLuint uniform = glGetUniformLocation(shader.smartScaler, "useLightTexture");
-	if (uniform >= 0) glUniform1i(uniform, light && lightMapMode == LIGHTMAPMODE_PIXEL && lightMap.data);
-
-	setPMVMatrix(shader.smartScaler);
-
-	if (gameSettings.antiAlias == 1) {
-		glUniform1i(glGetUniformLocation(shader.smartScaler, "antialias"), 1);
-	} else {
-		glUniform1i(glGetUniformLocation(shader.smartScaler, "antialias"), 0);
-	}
-
-	const GLfloat vertices[] = {
-		x1, y1, z,
-		x2, y1, z,
-		x1, y2, z,
-		x2, y2, z
-	};
-
-	if (! mirror) {
-		GLfloat tx3 = tx1;
-		tx1 = tx2;
-		tx2 = tx3;
-	}
-	const GLfloat texCoords[] = {
-		tx2, ty1,
-		tx1, ty1,
-		tx2, ty2,
-		tx1, ty2
-	};
-
-	drawQuad(shader.smartScaler, vertices, 2, texCoords, ltexCoords);
-
-	glDisable(GL_BLEND);
-	glUseProgram(0);
-
-	if (light && lightMapMode == LIGHTMAPMODE_PIXEL) {
-		glActiveTexture(GL_TEXTURE1);
-		glActiveTexture(GL_TEXTURE0);
-	}
-
-	setSecondaryColor(0., 0., 0., 1.);
-
-	// Are we pointing at the sprite?
-	if (input.mouseX >= x1 && input.mouseX <= x2 && input.mouseY >= y1 && input.mouseY <= y2) {
-		if (thisPerson->extra & EXTRA_RECTANGULAR) return true;
-#ifdef HAVE_GLES2
-		return true;
-#else
-		return checkColourChange(false);
-#endif
-	}
-	return false;
-#endif
 }
 
 void resetSpriteLayers(zBufferData *pz, int x, int y, bool upsidedown) {
diff --git a/engines/sludge/thumbnail.cpp b/engines/sludge/thumbnail.cpp
index b628f0b..74c77ff 100644
--- a/engines/sludge/thumbnail.cpp
+++ b/engines/sludge/thumbnail.cpp
@@ -99,7 +99,6 @@ bool saveThumbnail(Common::WriteStream *stream) {
 		thumbnailTextureName = 0;
 
 		// Save Our ViewPort
-#ifdef HAVE_GLES2
 		GLushort *image = new GLushort [thumbWidth * thumbHeight];
 		GLuint *tmp = new GLuint [thumbWidth * thumbHeight];
 		if (! checkNew(image)) return false;
@@ -111,12 +110,6 @@ bool saveThumbnail(Common::WriteStream *stream) {
 			}
 		}
 		delete[] tmp;
-#else
-		GLushort *image = new GLushort [thumbWidth * thumbHeight];
-		if (! checkNew(image)) return false;
-
-		glReadPixels(viewportOffsetX, viewportOffsetY, thumbWidth, thumbHeight, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, image);
-#endif
 
 		glUseProgram(0);
 #endif


Commit: ee45e1517800aac5d165dc08923f1f5b2b8a21e0
    https://github.com/scummvm/scummvm/commit/ee45e1517800aac5d165dc08923f1f5b2b8a21e0
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: use Common::Point instead of struct POINT

Changed paths:
    engines/sludge/floor.cpp
    engines/sludge/floor.h


diff --git a/engines/sludge/floor.cpp b/engines/sludge/floor.cpp
index e556463..15da333 100644
--- a/engines/sludge/floor.cpp
+++ b/engines/sludge/floor.cpp
@@ -159,7 +159,7 @@ bool setFloor(int fileNum) {
 	// Find out how many vertices there are and reserve memory
 
 	i = bigDataFile->readUint16BE();
-	currentFloor->vertex = new POINT[i];
+	currentFloor->vertex = new Common::Point[i];
 	if (!checkNew(currentFloor->vertex))
 		return false;
 
diff --git a/engines/sludge/floor.h b/engines/sludge/floor.h
index 1b212fa..b1de826 100644
--- a/engines/sludge/floor.h
+++ b/engines/sludge/floor.h
@@ -22,6 +22,8 @@
 #ifndef SLUDGE_FLOOR_H
 #define SLUDGE_FLOOR_H
 
+#include "common/rect.h"
+
 namespace Sludge {
 
 struct floorPolygon {
@@ -29,14 +31,9 @@ struct floorPolygon {
 	int *vertexID;
 };
 
-struct POINT {
-	int x;
-	int y;
-};
-
 struct flor {
 	int originalNum;
-	POINT *vertex;
+	Common::Point *vertex;
 	int numPolygons;
 	floorPolygon *polygon;
 	int * *matrix;


Commit: ed09887e84b7d50fdaed7b87a4c9927620bea6aa
    https://github.com/scummvm/scummvm/commit/ed09887e84b7d50fdaed7b87a4c9927620bea6aa
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove an unused .h

Changed paths:
  R engines/sludge/platform-dependent.h
    engines/sludge/fonttext.cpp
    engines/sludge/language.cpp
    engines/sludge/main_loop.cpp
    engines/sludge/newfatal.cpp
    engines/sludge/sludger.cpp


diff --git a/engines/sludge/fonttext.cpp b/engines/sludge/fonttext.cpp
index a35c51b..2c586e9 100644
--- a/engines/sludge/fonttext.cpp
+++ b/engines/sludge/fonttext.cpp
@@ -27,7 +27,6 @@
 #include "sludge/fonttext.h"
 #include "sludge/newfatal.h"
 #include "sludge/moreio.h"
-#include "sludge/platform-dependent.h"
 #include "sludge/utf8.h"
 
 namespace Sludge {
diff --git a/engines/sludge/language.cpp b/engines/sludge/language.cpp
index cb055f9..ebf4367 100644
--- a/engines/sludge/language.cpp
+++ b/engines/sludge/language.cpp
@@ -25,7 +25,6 @@
 #include "sludge/newfatal.h"
 #include "sludge/moreio.h"
 #include "sludge/language.h"
-#include "sludge/platform-dependent.h"
 #include "sludge/sludge.h"
 #include "sludge/CommonCode/version.h"
 
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index 636deeb..d0ec098 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -30,7 +30,6 @@
 
 #include "sludge/allfiles.h"
 #include "sludge/debug.h"
-#include "sludge/platform-dependent.h"
 #include "sludge/language.h"
 #include "sludge/stringy.h"
 #include "sludge/sludger.h"
diff --git a/engines/sludge/newfatal.cpp b/engines/sludge/newfatal.cpp
index bbb0f8c..4e75194 100644
--- a/engines/sludge/newfatal.cpp
+++ b/engines/sludge/newfatal.cpp
@@ -23,7 +23,6 @@
 #include "common/debug.h"
 
 #include "sludge/allfiles.h"
-#include "sludge/platform-dependent.h"
 #include "sludge/sound.h"
 #include "sludge/stringy.h"
 #include "sludge/errors.h"
diff --git a/engines/sludge/platform-dependent.h b/engines/sludge/platform-dependent.h
deleted file mode 100644
index bf36f5f..0000000
--- a/engines/sludge/platform-dependent.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-#ifndef SLUDGE_PLATEFORM_DEPENDENT_H
-#define SLUDGE_PLATEFORM_DEPENDENT_H
-/* These are the functions which have different versions for
- * the different operating systems.
- */
-
-namespace Sludge {
-
-char *grabFileName();
-
-void msgBox(const char *head, const char *msg);
-int msgBoxQuestion(const char *head, const char *msg);
-
-void changeToUserDir();
-uint32 launch(char *filename);
-
-bool defaultUserFullScreen();
-
-} // End of namespace Sludge
-
-#endif
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index 26412a0..ac60420 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -23,7 +23,6 @@
 #include "common/debug.h"
 
 #include "sludge/allfiles.h"
-#include "sludge/platform-dependent.h"
 #include "sludge/sludger.h"
 #include "sludge/backdrop.h"
 #include "sludge/cursors.h"


Commit: 08304b848ad871e25353bf4fdd9c05182bc83fbf
    https://github.com/scummvm/scummvm/commit/08304b848ad871e25353bf4fdd9c05182bc83fbf
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: use Common/debug instead of sludge debug

Changed paths:
  R engines/sludge/debug.cpp
  R engines/sludge/debug.h
    engines/sludge/bg_effects.cpp
    engines/sludge/builtin.cpp
    engines/sludge/fileset.cpp
    engines/sludge/fonttext.cpp
    engines/sludge/freeze.cpp
    engines/sludge/loadsave.cpp
    engines/sludge/main_loop.cpp
    engines/sludge/module.mk
    engines/sludge/newfatal.cpp
    engines/sludge/newfatal.h
    engines/sludge/people.cpp
    engines/sludge/savedata.cpp
    engines/sludge/sound.cpp
    engines/sludge/sprbanks.cpp
    engines/sludge/sprites.cpp
    engines/sludge/variable.cpp


diff --git a/engines/sludge/bg_effects.cpp b/engines/sludge/bg_effects.cpp
index 529556e..6929915 100644
--- a/engines/sludge/bg_effects.cpp
+++ b/engines/sludge/bg_effects.cpp
@@ -25,7 +25,6 @@
 
 #include "sludge/allfiles.h"
 #include "sludge/backdrop.h"
-#include "sludge/debug.h"
 #include "sludge/graphics.h"
 #include "sludge/moreio.h"
 #include "sludge/newfatal.h"
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index fc92161..299ef35 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -20,7 +20,6 @@
  *
  */
 
-#include "sludge/debug.h"
 #include "sludge/allfiles.h"
 #include "sludge/sludger.h"
 #include "sludge/builtin.h"
diff --git a/engines/sludge/debug.cpp b/engines/sludge/debug.cpp
deleted file mode 100644
index cbeb996..0000000
--- a/engines/sludge/debug.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-
-#include "sludge/allfiles.h"
-#include "sludge/debug.h"
-#include "sludge/language.h"
-
-namespace Sludge {
-
-void debugOut(const char *a, ...) {
-	if (! gameSettings.debugMode) return;
-
-	va_list argptr;
-	va_start(argptr, a);
-
-#if 0
-#if defined __unix__ && !(defined __APPLE__)
-	vfprintf(stderr, a, argptr);
-#else
-	FILE *fp = fopen("debuggy.txt", "at");
-	if (fp) {
-		vfprintf(fp, a, argptr);
-		fclose(fp);
-	}
-#endif
-#endif
-}
-
-void debugHeader() {
-	debugOut("*** Engine compiled " __DATE__ " at " __TIME__ ".\n");
-}
-
-} // End of namespace Sludge
diff --git a/engines/sludge/debug.h b/engines/sludge/debug.h
deleted file mode 100644
index 9382b77..0000000
--- a/engines/sludge/debug.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef SLUDGE_DEBUG_H
-#define SLUDGE_DEBUG_H
-
-namespace Sludge {
-
-void debugOut(const char *a, ...);
-void debugHeader();
-
-} // End of namespace Sludge
-
-#endif
diff --git a/engines/sludge/fileset.cpp b/engines/sludge/fileset.cpp
index deb4a22..c138bb5 100644
--- a/engines/sludge/fileset.cpp
+++ b/engines/sludge/fileset.cpp
@@ -23,7 +23,6 @@
 #include "common/file.h"
 #include "common/debug.h"
 
-#include "sludge/debug.h"
 #include "sludge/stringy.h"
 #include "sludge/allfiles.h"
 #include "sludge/moreio.h"
diff --git a/engines/sludge/fonttext.cpp b/engines/sludge/fonttext.cpp
index 2c586e9..b0324d3 100644
--- a/engines/sludge/fonttext.cpp
+++ b/engines/sludge/fonttext.cpp
@@ -20,7 +20,6 @@
  *
  */
 
-#include "sludge/debug.h"
 #include "sludge/allfiles.h"
 #include "sludge/stringy.h"
 #include "sludge/sprites.h"
diff --git a/engines/sludge/freeze.cpp b/engines/sludge/freeze.cpp
index d3dde17..2f80157 100644
--- a/engines/sludge/freeze.cpp
+++ b/engines/sludge/freeze.cpp
@@ -20,7 +20,6 @@
  *
  */
 #include "sludge/allfiles.h"
-#include "sludge/debug.h"
 #include "sludge/graphics.h"
 #include "sludge/newfatal.h"
 #include "sludge/sprites.h"
@@ -82,7 +81,6 @@ void freezeGraphics() {
 }
 
 bool freeze() {
-	debugOut("calling freeze()\n");
 	frozenStuffStruct *newFreezer = new frozenStuffStruct;
 	if (!checkNew(newFreezer))
 		return false;
diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index d397092..e9daa9b 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -41,7 +41,6 @@
 #include "sludge/statusba.h"
 #include "sludge/sound.h"
 #include "sludge/fileset.h"
-#include "sludge/debug.h"
 #include "sludge/loadsave.h"
 #include "sludge/bg_effects.h"
 #include "sludge/thumbnail.h"
@@ -555,7 +554,7 @@ bool loadGame(char *fname) {
 
 	uint32 bytes_read = fp->read(&savedGameTime, sizeof(FILETIME));
 	if (bytes_read != sizeof(FILETIME) && fp->err()) {
-		debugOut("Reading error in loadGame.\n");
+		warning("Reading error in loadGame.");
 	}
 
 	if (savedGameTime.dwLowDateTime != fileTime.dwLowDateTime || savedGameTime.dwHighDateTime != fileTime.dwHighDateTime) {
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index d0ec098..4fbdad5 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -29,7 +29,6 @@
 #include "graphics/surface.h"
 
 #include "sludge/allfiles.h"
-#include "sludge/debug.h"
 #include "sludge/language.h"
 #include "sludge/stringy.h"
 #include "sludge/sludger.h"
@@ -330,8 +329,6 @@ int main_loop(const char *filename)
 		Wait_Frame();
 	}
 
-	debugOut("Bye!\n\n");
-
 	delete[] gamePath;
 
 	killSoundStuff();
diff --git a/engines/sludge/module.mk b/engines/sludge/module.mk
index fa1f313..ac5529f 100644
--- a/engines/sludge/module.mk
+++ b/engines/sludge/module.mk
@@ -6,7 +6,6 @@ MODULE_OBJS := \
 	builtin.o \
 	console.o \
 	cursors.o \
-	debug.o \
 	detection.o \
 	fileset.o \
 	floor.o \
diff --git a/engines/sludge/newfatal.cpp b/engines/sludge/newfatal.cpp
index 4e75194..d0e5184 100644
--- a/engines/sludge/newfatal.cpp
+++ b/engines/sludge/newfatal.cpp
@@ -66,13 +66,6 @@ void displayFatal() {
 	}
 }
 
-void warning(const Common::String &l) {
-#if 0
-	setGraphicsWindow(false);
-	msgBox("SLUDGE v" TEXT_VERSION " non-fatal indigestion report", l);
-#endif
-}
-
 void registerWindowForFatal() {
 	fatalInfo = "There's an error with this SLUDGE game! If you're designing this game, please turn on verbose error messages in the project manager and recompile. If not, please contact the author saying where and how this problem occured.";
 }
diff --git a/engines/sludge/newfatal.h b/engines/sludge/newfatal.h
index bb22227..47d49e2 100644
--- a/engines/sludge/newfatal.h
+++ b/engines/sludge/newfatal.h
@@ -36,7 +36,6 @@ int checkNew(const void *mem);
 void displayFatal();
 void registerWindowForFatal();
 void setFatalInfo(const Common::String &userFunc, const Common::String &BIF);
-void warning(const Common::String &l);
 void setResourceForFatal(int n);
 const char *resourceNameFromNum(int i);
 
diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index 98b913c..43adbd9 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -35,7 +35,6 @@
 #include "sludge/floor.h"
 #include "sludge/zbuffer.h"
 #include "sludge/sound.h"
-#include "sludge/debug.h"
 #include "sludge/CommonCode/version.h"
 
 #define ANGLEFIX (180.0 / 3.14157)
diff --git a/engines/sludge/savedata.cpp b/engines/sludge/savedata.cpp
index d1e3fa5..081798f 100644
--- a/engines/sludge/savedata.cpp
+++ b/engines/sludge/savedata.cpp
@@ -23,7 +23,6 @@
 #include "common/file.h"
 
 #include "sludge/allfiles.h"
-#include "sludge/debug.h"
 #include "sludge/variable.h"
 #include "sludge/newfatal.h"
 #include "sludge/moreio.h"
@@ -109,7 +108,7 @@ char *readTextPlain(Common::File *fp) {
 			return NULL;
 		size_t bytes_read = fp->read(reply, stringSize);
 		if (bytes_read != stringSize && fp->err()) {
-			debugOut("Reading error in readTextPlain.\n");
+			warning("Reading error in readTextPlain.");
 		}
 		fp->readByte();  // Skip the newline character
 		reply[stringSize] = 0;
diff --git a/engines/sludge/sound.cpp b/engines/sludge/sound.cpp
index 745c3a2..a92a51c 100644
--- a/engines/sludge/sound.cpp
+++ b/engines/sludge/sound.cpp
@@ -32,7 +32,6 @@
 #include "audio/mods/protracker.h"
 
 #include "sludge/allfiles.h"
-#include "sludge/debug.h"
 #include "sludge/newfatal.h"
 #include "sludge/sound.h"
 #include "sludge/moreio.h"
@@ -418,7 +417,7 @@ bool startSound(int f, bool loopy) {
 		Audio::AudioStream *stream = nullptr;
 		int a = makeSoundAudioStream(f, stream, loopy);
 		if (a == -1) {
-			debugOut("Failed to cache sound!\n");
+			warning("Failed to cache sound!");
 			return false;
 		}
 
@@ -552,7 +551,7 @@ void playSoundList(soundList *s) {
 		Audio::AudioStream *stream;
 		int a = makeSoundAudioStream(s->sound, stream, false);
 		if (a == -1) {
-			debugOut("Failed to cache sound!\n");
+			warning("Failed to cache sound!");
 			return;
 		}
 
diff --git a/engines/sludge/sprbanks.cpp b/engines/sludge/sprbanks.cpp
index bc2d084..594ea56 100644
--- a/engines/sludge/sprbanks.cpp
+++ b/engines/sludge/sprbanks.cpp
@@ -20,11 +20,13 @@
  *
  */
 
+#include "common/textconsole.h"
+
 #include "sludge/allfiles.h"
+#include "sludge/sludge.h"
 #include "sludge/sprites.h"
 #include "sludge/sprbanks.h"
 #include "sludge/newfatal.h"
-#include "sludge/debug.h"
 
 namespace Sludge {
 
@@ -33,7 +35,6 @@ extern spriteBank theFont;
 extern int loadedFontNum, fontTableSize;
 
 loadedSpriteBank *loadBankForAnim(int ID) {
-	//debugOut ("loadBankForAnim: Looking for sprite bank with ID %d\n", ID);
 	loadedSpriteBank *returnMe = allLoadedBanks;
 	while (returnMe) {
 		if (returnMe->ID == ID) {
@@ -43,17 +44,16 @@ loadedSpriteBank *loadBankForAnim(int ID) {
 		returnMe = returnMe->next;
 	}
 	returnMe = new loadedSpriteBank;
-	//debugOut ("loadBankForAnim: No existing sprite bank with ID %d\n", ID);
 	if (checkNew(returnMe)) {
 		returnMe->ID = ID;
 		if (loadSpriteBank(ID, returnMe->bank, false)) {
 			returnMe->timesUsed = 0;
 			returnMe->next = allLoadedBanks;
 			allLoadedBanks = returnMe;
-			debugOut("loadBankForAnim: New sprite bank created OK\n");
+			debug(kSludgeDebugDataLoad, "loadBankForAnim: New sprite bank created OK");
 			return returnMe;
 		} else {
-			debugOut("loadBankForAnim: I guess I couldn't load the sprites...\n");
+			debug(kSludgeDebugDataLoad, "loadBankForAnim: I guess I couldn't load the sprites...");
 			return NULL;
 		}
 	} else
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index 660e580..9790193 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -32,7 +32,6 @@
 #include "sludge/backdrop.h"
 #include "sludge/sludger.h"
 #include "sludge/zbuffer.h"
-#include "sludge/debug.h"
 #include "sludge/graphics.h"
 #include "sludge/imgloader.h"
 #include "sludge/sludge.h"
@@ -225,7 +224,7 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 		} else { // RAW DATA
 			size_t bytes_read = bigDataFile->read(data, picwidth * picheight);
 			if (bytes_read != picwidth * picheight && bigDataFile->err()) {
-				debugOut("Reading error in loadSpriteBank.\n");
+				warning("Reading error in loadSpriteBank.");
 			}
 		}
 	}
diff --git a/engines/sludge/variable.cpp b/engines/sludge/variable.cpp
index a9f91d5..9792dbf 100644
--- a/engines/sludge/variable.cpp
+++ b/engines/sludge/variable.cpp
@@ -22,7 +22,6 @@
 
 #include "common/debug.h"
 
-#include "sludge/debug.h"
 #include "sludge/allfiles.h"
 #include "sludge/variable.h"
 #include "sludge/moreio.h"


Commit: b8cede684e6f78e86920ad473a097cf13e0c7db9
    https://github.com/scummvm/scummvm/commit/b8cede684e6f78e86920ad473a097cf13e0c7db9
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove unused files

Changed paths:
  R engines/sludge/vid.cpp
  R engines/sludge/vid.h


diff --git a/engines/sludge/vid.cpp b/engines/sludge/vid.cpp
deleted file mode 100644
index d0c51d1..0000000
--- a/engines/sludge/vid.cpp
+++ /dev/null
@@ -1,270 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef _MSC_VER        // Microsoft compiler?
-#else
-#include <io.h>
-#include <stdio.h>
-#include "vfw.h"
-#endif
-
-#include "sludge/allfiles.h"
-#include "sludge/newfatal.h"
-#include "sludge/stringy.h"
-#include "sludge/sound.h"
-#include "sludge/colours.h"
-#include "sludge/fileset.h"
-
-namespace Sludge {
-
-struct timStream {
-	PAVISTREAM got;
-	AVISTREAMINFO info;
-	LONG chunkSize;
-	LPBYTE chunk;
-};
-
-static PAVIFILE pAviFile = NULL;
-static PGETFRAME pgf;
-static timStream audio, video;
-static int videoFrameNum = 0;
-static int vidBytesPerPixel = 0;
-static int vidWidth, vidHeight;
-static DWORD biSize;
-
-static char *videoFile = NULL;
-
-bool videoPlaying = false;
-
-extern int winWidth, winHeight;
-extern unsigned short int *screen;
-extern HWND hMainWindow;
-
-void initialiseMovieStuff() {
-	char buffer[500];
-	if (ExpandEnvironmentStrings("%temp%", buffer, 499) == 0)
-		buffer[0] = NULL;
-	videoFile = joinStrings(buffer, "\\test.avi");
-//	warning (videoFile);
-}
-
-bool getStream(DWORD type, timStream &intoHere) {
-	if (AVIFileGetStream(pAviFile, &intoHere.got, type, 0)) {
-		intoHere.got = NULL;
-		return true;
-	} else if (AVIStreamInfo(intoHere.got, &intoHere.info, sizeof(AVISTREAMINFO))) {
-		return fatal("Can't get stream info");
-	} else if (AVIStreamReadFormat(intoHere.got, AVIStreamStart(intoHere.got),
-	NULL, &intoHere.chunkSize)) {
-		return fatal("Can't get stream chunk size");
-	} else {
-		// So far so good! Let's read a chunk of data (huh?)
-
-		intoHere.chunk = new BYTE[intoHere.chunkSize];
-
-		if (!intoHere.chunk) {
-			return fatal("Out of memory");
-		} else if (AVIStreamReadFormat(intoHere.got, AVIStreamStart(intoHere.got), intoHere.chunk, &intoHere.chunkSize)) {
-			return fatal("Couldn't read stream format");
-		}
-	}
-	return true;
-}
-
-void killStream(timStream &intoHere) {
-	delete intoHere.chunk;
-	intoHere.chunk = NULL;
-}
-
-/*
- #define WAVHEADERSIZE 20
- char wavHeader[WAVHEADERSIZE] = {'R', 'I', 'F', 'F', 0, 0, 0, 0,
- 'W', 'A', 'V', 'E', 'f', 'm', 't',
- 0x20, 0x10, 0, 0, 0};
-
- void handleAudio () {
- LONG aSize;
-
- if(AVIStreamRead(audio.got, 0, AVISTREAMREAD_CONVENIENT, NULL, 0, & aSize, NULL)) return;
-
- int totalSize = aSize + audio.chunkSize + WAVHEADERSIZE + 4;
-
- LPBYTE pBuffer = new BYTE[totalSize];
- if (!pBuffer) return;
-
- memcpy (pBuffer, wavHeader, WAVHEADERSIZE);
- pBuffer[4] = (char) (aSize);
- pBuffer[5] = (char) (aSize >> 8);
- memcpy (pBuffer + WAVHEADERSIZE, audio.chunk, audio.chunkSize);
- memcpy (pBuffer + WAVHEADERSIZE + audio.chunkSize, "data", 4);
-
- if(! AVIStreamRead (audio.got, 0, AVISTREAMREAD_CONVENIENT, pBuffer + audio.chunkSize + WAVHEADERSIZE + 4, aSize, NULL, NULL)) {
- FILE * fp = fopen ("test.wav", "wb");
- if (fp) {
- fwrite (pBuffer, 1, totalSize, fp);
- fclose (fp);
- }
- int i = fakeCacheSoundForVideo ((char *) pBuffer, totalSize);
- if (i != -1) startSound (i, false);
- }
-
- delete pBuffer;
- }
- */
-
-void finishVideo() {
-	videoPlaying = false;
-	AVIStreamGetFrameClose(pgf);
-	if (audio.got)
-		AVIStreamRelease(audio.got);
-	if (video.got)
-		AVIStreamRelease(video.got);
-	killStream(audio);
-	killStream(video);
-	AVIFileRelease(pAviFile);
-	AVIFileExit();
-#ifdef _MSC_VER
-	_unlink(videoFile);
-#else
-	unlink(videoFile)
-;
-#endif
-}
-
-#define COPYSIZE 256
-
-bool extractSlice(int fileNum, char *toName) {
-unsigned char buff[COPYSIZE];
-
-unsigned long fileLength = openFileFromNum(fileNum);
-if (!fileLength)
-	return false; // Error already displayed
-#if 0
-	FILE *copyVid = fopen(toName, "wb");
-	if (! copyVid) return fatal("Can't extract resource");
-
-	while (fileLength >= COPYSIZE) {
-		fread(buff, COPYSIZE, 1, bigDataFile);
-		if (fwrite(buff, 1, COPYSIZE, copyVid) != COPYSIZE) return fatal("Out of disk space extracting resource");
-		fileLength -= COPYSIZE;
-	}
-	if (fileLength) {
-		fread(buff, fileLength, 1, bigDataFile);
-		if (fwrite(buff, 1, fileLength, copyVid) != fileLength) return fatal("Out of disk space extracting resource");
-	}
-
-	fclose(copyVid);
-#endif
-finishAccess();
-
-return true;
-}
-
-bool startVideo(int fileNum) {
-
-setResourceForFatal(fileNum);
-
-AVIFILEINFO info;
-
-if (videoPlaying)
-	finishVideo();
-AVIFileInit();
-
-if (!extractSlice(fileNum, videoFile))
-	return false;
-if (AVIFileOpen(&pAviFile, videoFile, OF_READ, NULL))
-	return fatal(ERROR_AVI_FILE_ERROR);
-
-AVIFileInfo(pAviFile, &info, sizeof(info));
-
-if (!getStream(streamtypeAUDIO, audio))
-	return false;
-if (!getStream(streamtypeVIDEO, video))
-	return false;
-
-if (!video.got)
-	return fatal(ERROR_AVI_NO_STREAM);
-
-//	if (audio.got) handleAudio ();
-
-pgf = AVIStreamGetFrameOpen(video.got, NULL);
-if (!pgf)
-	return fatal(ERROR_AVI_ARGH);
-
-LPBITMAPINFO pInfo = (LPBITMAPINFO)(video.chunk);
-vidBytesPerPixel = pInfo->bmiHeader.biBitCount / 8;
-biSize = pInfo->bmiHeader.biSize;
-vidWidth = pInfo->bmiHeader.biWidth;
-vidHeight = pInfo->bmiHeader.biHeight;
-
-videoFrameNum = 0;
-videoPlaying = true;
-
-setResourceForFatal(-1);
-
-return true;
-}
-
-bool nextVideoFrame() {
-LPBITMAPINFOHEADER lpbi = (LPBITMAPINFOHEADER)AVIStreamGetFrame(pgf, videoFrameNum);
-if (!lpbi) {
-	finishVideo();
-	return false;
-}
-
-BYTE *pData = (((BYTE *)lpbi) + lpbi->biSize);
-
-int xOff = (winWidth - vidWidth) >> 1;
-int yOff = (winHeight + vidHeight) >> 1;
-unsigned short int *startingPoint = screen + xOff + (yOff * winWidth);
-
-for (int y = 0; y < vidHeight; y++) {
-	startingPoint -= winWidth;
-	unsigned short int *toHere = startingPoint;
-	for (int x = 0; x < vidWidth; x++) {
-		switch (vidBytesPerPixel) {
-			case 1:
-				(*toHere) = makeGrey(*pData);
-				break;
-
-			case 3:
-			case 4:
-				(*toHere) = makeColour(*(pData + 2), *(pData + 1), *pData);
-				break;
-
-			default: {
-				WORD Pixel16 = *((WORD *)pData);
-				(*toHere) = makeColour((((UINT)(Pixel16) >> 10) & 0x1F) << 3, (((UINT)(Pixel16) >> 5) & 0x1F) << 3, (((UINT)(Pixel16) >> 0) & 0x1F) << 3);
-			}
-				break;
-		}
-		pData += vidBytesPerPixel;
-		toHere++;
-	}
-}
-
-videoFrameNum++;
-
-return true;
-}
-
-} // End of namespace Sludge
diff --git a/engines/sludge/vid.h b/engines/sludge/vid.h
deleted file mode 100644
index 1d81daf..0000000
--- a/engines/sludge/vid.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-#ifndef SLUDGE_VID_H
-#define SLUDGE_VID_H
-
-namespace Sludge {
-
-bool startVideo(int fileNum);
-bool nextVideoFrame();
-void finishVideo();
-void initialiseMovieStuff();
-
-} // End of namespace Sludge
-
-#endif


Commit: cc727710b45a2d3d3c51139b76976c352d9e8449
    https://github.com/scummvm/scummvm/commit/cc727710b45a2d3d3c51139b76976c352d9e8449
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove define duplication

Changed paths:
    engines/sludge/allfiles.h


diff --git a/engines/sludge/allfiles.h b/engines/sludge/allfiles.h
index a08df72..2f6acff 100644
--- a/engines/sludge/allfiles.h
+++ b/engines/sludge/allfiles.h
@@ -28,10 +28,4 @@
 //#define debuggy2 int
 #define IN_THE_CENTRE 65535
 
-namespace Sludge {
-
-typedef unsigned char byte;
-
-} // End of namespace Sludge
-
 #endif


Commit: f8e1fe006433124f7cd82691d37011127297ec42
    https://github.com/scummvm/scummvm/commit/f8e1fe006433124f7cd82691d37011127297ec42
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: replace int types to scummvm defined ones

Changed paths:
    engines/sludge/backdrop.cpp
    engines/sludge/backdrop.h
    engines/sludge/bg_effects.cpp
    engines/sludge/builtin.cpp
    engines/sludge/fileset.cpp
    engines/sludge/fileset.h
    engines/sludge/fonttext.cpp
    engines/sludge/freeze.cpp
    engines/sludge/graphics.cpp
    engines/sludge/graphics.h
    engines/sludge/language.cpp
    engines/sludge/language.h
    engines/sludge/loadsave.cpp
    engines/sludge/moreio.cpp
    engines/sludge/moreio.h
    engines/sludge/movie.cpp
    engines/sludge/objtypes.h
    engines/sludge/people.cpp
    engines/sludge/people.h
    engines/sludge/savedata.cpp
    engines/sludge/sludger.cpp
    engines/sludge/sludger.h
    engines/sludge/sound.cpp
    engines/sludge/sound.h
    engines/sludge/sprites.cpp
    engines/sludge/sprites.h
    engines/sludge/statusba.h
    engines/sludge/thumbnail.cpp
    engines/sludge/transition.cpp
    engines/sludge/utf8.cpp
    engines/sludge/variable.cpp
    engines/sludge/variable.h


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index 8ab4c6f..bda9f55 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -70,9 +70,9 @@ int lightMapMode = LIGHTMAPMODE_PIXEL;
 parallaxLayer *parallaxStuff = NULL;
 int cameraPX = 0, cameraPY = 0;
 
-unsigned int sceneWidth, sceneHeight;
+uint sceneWidth, sceneHeight;
 int lightMapNumber;
-unsigned int currentBlankColour = TS_ARGB(255, 0, 0, 0);
+uint currentBlankColour = TS_ARGB(255, 0, 0, 0);
 
 extern int cameraX, cameraY;
 extern float cameraZoom;
@@ -147,14 +147,14 @@ bool snapshot() {
 }
 
 bool restoreSnapshot(Common::SeekableReadStream *stream) {
-	unsigned int picWidth = stream->readUint16BE();
-	unsigned int picHeight = stream->readUint16BE();
+	uint picWidth = stream->readUint16BE();
+	uint picHeight = stream->readUint16BE();
 
 	if ((picWidth != winWidth) || (picHeight != winHeight))
 		return false;
 
-	unsigned int t1, t2, n;
-	unsigned short c;
+	uint t1, t2, n;
+	uint16 c;
 #if 0
 	GLubyte *target;
 	if (!NPOT_textures) {
@@ -170,7 +170,7 @@ bool restoreSnapshot(Common::SeekableReadStream *stream) {
 	for (t2 = 0; t2 < winHeight; t2++) {
 		t1 = 0;
 		while (t1 < winWidth) {
-			c = (unsigned short)stream->readUint16BE();
+			c = (uint16)stream->readUint16BE();
 			if (c & 32) {
 				n = stream->readByte() + 1;
 				c -= 32;
@@ -416,11 +416,11 @@ void hardScroll(int distance) {
 
 	setPixelCoords(true);
 
-	unsigned int xoffset = 0;
+	uint xoffset = 0;
 	while (xoffset < sceneWidth) {
 		int w = (sceneWidth - xoffset < viewportWidth) ? sceneWidth - xoffset : viewportWidth;
 
-		unsigned int yoffset = 0;
+		uint yoffset = 0;
 		while (yoffset < sceneHeight) {
 			int h = (sceneHeight - yoffset < viewportHeight) ? sceneHeight - yoffset : viewportHeight;
 
@@ -457,11 +457,11 @@ void hardScroll(int distance) {
 #endif
 }
 
-void drawVerticalLine(unsigned int x, unsigned int y1, unsigned int y2) {
+void drawVerticalLine(uint x, uint y1, uint y2) {
 	drawLine(x, y1, x, y2);
 }
 
-void drawHorizontalLine(unsigned int x1, unsigned int y, unsigned int x2) {
+void drawHorizontalLine(uint x1, uint y, uint x2) {
 	drawLine(x1, y, x2, y);
 }
 
@@ -652,7 +652,7 @@ void reloadParallaxTextures() {
 #endif
 }
 
-bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY) {
+bool loadParallax(uint16 v, uint16 fracX, uint16 fracY) {
 	setResourceForFatal(v);
 	if (!openFileFromNum(v))
 		return fatal("Can't open parallax image");
@@ -1055,7 +1055,7 @@ void saveCoreHSI(Common::WriteStream *stream, GLuint texture, int w, int h) {
 	setPixelCoords(false);
 
 	int x, y, lookAhead;
-	unsigned short int *fromHere, *lookPointer;
+	uint16 *fromHere, *lookPointer;
 
 	stream->writeUint16BE(w);
 	stream->writeUint16BE(h);
@@ -1101,7 +1101,7 @@ void saveParallaxRecursive(parallaxLayer *me, Common::WriteStream *stream) {
 	}
 }
 
-bool getRGBIntoStack(unsigned int x, unsigned int y, stackHandler *sH) {
+bool getRGBIntoStack(uint x, uint y, stackHandler *sH) {
 #if 0
 	if (x >= sceneWidth || y >= sceneHeight) {
 		return fatal("Co-ordinates are outside current scene!");
diff --git a/engines/sludge/backdrop.h b/engines/sludge/backdrop.h
index 216b656..dbab0df 100644
--- a/engines/sludge/backdrop.h
+++ b/engines/sludge/backdrop.h
@@ -35,14 +35,14 @@ enum {
 	LIGHTMAPMODE_NUM
 };
 
-extern unsigned int winWidth, winHeight, sceneWidth, sceneHeight;
+extern uint winWidth, winHeight, sceneWidth, sceneHeight;
 extern int lightMapMode;
 
 struct parallaxLayer {
 	Graphics::Surface surface;
 	int speedX, speedY;
 	bool wrapS, wrapT;
-	unsigned short fileNum, fractionX, fractionY;
+	uint16 fileNum, fractionX, fractionY;
 	int cameraX, cameraY;
 	parallaxLayer *next;
 	parallaxLayer *prev;
@@ -63,10 +63,10 @@ void saveCoreHSI(Common::WriteStream *stream, GLuint texture, int w, int h);
 #endif
 bool loadHSI(Common::SeekableReadStream *stream, int, int, bool);
 bool mixHSI(Common::SeekableReadStream *stream, int x = 0, int y = 0);
-void drawHorizontalLine(unsigned int, unsigned int, unsigned int);
-void drawVerticalLine(unsigned int, unsigned int, unsigned int);
+void drawHorizontalLine(uint, uint, uint);
+void drawVerticalLine(uint, uint, uint);
 void hardScroll(int distance);
-bool getRGBIntoStack(unsigned int x, unsigned int y, stackHandler *sH);
+bool getRGBIntoStack(uint x, uint y, stackHandler *sH);
 
 // Also the light map stuff
 
@@ -78,7 +78,7 @@ extern Graphics::Surface lightMap;
 // And background parallax scrolling
 
 void killParallax();
-bool loadParallax(unsigned short v, unsigned short fracX, unsigned short fracY);
+bool loadParallax(uint16 v, uint16 fracX, uint16 fracY);
 void saveParallaxRecursive(parallaxLayer *me, Common::WriteStream *fp);
 void reloadParallaxTextures();
 
diff --git a/engines/sludge/bg_effects.cpp b/engines/sludge/bg_effects.cpp
index 6929915..916c8e3 100644
--- a/engines/sludge/bg_effects.cpp
+++ b/engines/sludge/bg_effects.cpp
@@ -32,7 +32,7 @@
 namespace Sludge {
 
 #if 0
-//extern unsigned short int * * backDropImage;
+//extern uint16 * * backDropImage;
 extern GLuint backdropTextureName;
 #endif
 
@@ -147,7 +147,7 @@ void blur_loadSettings(Common::SeekableReadStream *stream) {
 	s_matrixEffectBase = stream->readUint32LE();
 
 	if (blur_allocateMemoryForEffect()) {
-		size_t bytes_read = stream->read(s_matrixEffectData, sizeof(int) * s_matrixEffectWidth * s_matrixEffectHeight);
+		uint bytes_read = stream->read(s_matrixEffectData, sizeof(int) * s_matrixEffectWidth * s_matrixEffectHeight);
 		if (bytes_read != sizeof(int) * s_matrixEffectWidth * s_matrixEffectHeight && stream->err()) {
 			debug("Reading error in blur_loadSettings.");
 		}
@@ -254,7 +254,7 @@ static inline int clampi(int i, int min, int max) {
 	return (i >= max) ? max : ((i <= min) ? min : i);
 }
 
-static inline void blur_createSourceLine(unsigned char *createLine, unsigned char *fromLine, int overlapOnLeft, int width) {
+static inline void blur_createSourceLine(byte *createLine, byte *fromLine, int overlapOnLeft, int width) {
 	int miniX;
 	memcpy(createLine + overlapOnLeft * 4, fromLine, width * 4);
 
@@ -274,13 +274,13 @@ static inline void blur_createSourceLine(unsigned char *createLine, unsigned cha
 bool blurScreen() {
 #if 0
 	if (s_matrixEffectWidth && s_matrixEffectHeight && s_matrixEffectDivide && s_matrixEffectData) {
-		unsigned char *thisLine;
+		byte *thisLine;
 		int y, x;
 		bool ok = true;
 		int overlapOnLeft = s_matrixEffectWidth / 2;
 		int overlapAbove = s_matrixEffectHeight / 2;
 
-		unsigned char **sourceLine = new unsigned char *[s_matrixEffectHeight];
+		byte **sourceLine = new byte *[s_matrixEffectHeight];
 		if (!checkNew(sourceLine))
 			return false;
 
@@ -296,7 +296,7 @@ bool blurScreen() {
 		saveTexture(backdropTextureName, backdropTexture);
 
 		for (y = 0; y < s_matrixEffectHeight; y++) {
-			sourceLine[y] = new unsigned char[(s_matrixEffectWidth - 1 + picWidth) * 4];
+			sourceLine[y] = new byte[(s_matrixEffectWidth - 1 + picWidth) * 4];
 			ok &= (sourceLine[y] != NULL);
 		}
 
@@ -313,7 +313,7 @@ bool blurScreen() {
 				//-------------------------
 				// Scroll source lines
 				//-------------------------
-				unsigned char *tempLine = sourceLine[0];
+				byte *tempLine = sourceLine[0];
 				for (int miniY = 0; miniY < s_matrixEffectHeight - 1; miniY++) {
 					sourceLine[miniY] = sourceLine[miniY + 1];
 				}
@@ -330,7 +330,7 @@ bool blurScreen() {
 					int totalBlue = 0;
 					int *matrixElement = s_matrixEffectData;
 					for (int miniY = 0; miniY < s_matrixEffectHeight; ++miniY) {
-						unsigned char *pixel = &sourceLine[miniY][x * 4];
+						byte *pixel = &sourceLine[miniY][x * 4];
 						for (int miniX = 0; miniX < s_matrixEffectWidth; ++miniX) {
 
 							totalRed += pixel[0] * *matrixElement;
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 299ef35..1226b1a 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -66,13 +66,13 @@ variable *launchResult = NULL;
 extern int lastFramesPerSecond, thumbWidth, thumbHeight;
 extern bool allowAnyFilename;
 extern bool captureAllKeys;
-extern short fontSpace;
+extern int16 fontSpace;
 extern eventHandlers *currentEvents;
 extern variableStack *noStack;
 extern statusStuff *nowStatus;
 extern screenRegion *overRegion;
 extern HWND hMainWindow;
-extern unsigned int sceneWidth, sceneHeight;
+extern uint sceneWidth, sceneHeight;
 extern int numBIFNames, numUserFunc;
 extern char builtInFunctionNames[][25];
 
@@ -86,13 +86,13 @@ extern GLuint backdropTextureName;
 #endif
 
 extern float speechSpeed;
-extern unsigned char brightnessLevel;
-extern unsigned char fadeMode;
-extern unsigned short saveEncoding;
+extern byte brightnessLevel;
+extern byte fadeMode;
+extern uint16 saveEncoding;
 extern frozenStuffStruct *frozenStuff;
-extern unsigned int currentBlankColour;
-extern unsigned int languageID;
-extern unsigned char currentBurnR, currentBurnG, currentBurnB;
+extern uint currentBlankColour;
+extern uint languageID;
+extern byte currentBurnR, currentBurnG, currentBurnB;
 
 int paramNum[] = { -1, 0, 1, 1, -1, -1, 1, 3, 4, 1, 0, 0, 8, -1,    // SAY->MOVEMOUSE
                    -1, 0, 0, -1, -1, 1, 1, 1, 1, 4, 1, 1, 2, 1,// FOCUS->REMOVEREGION
@@ -1633,7 +1633,7 @@ builtIn(setScale) {
 	if (!getValueType(val1, SVT_INT, fun->stack->thisVar))
 		return BR_ERROR;
 	trimStack(fun->stack);
-	setScale((short int)val1, (short int)val2);
+	setScale((int16)val1, (int16)val2);
 	return BR_CONTINUE;
 }
 
@@ -1898,7 +1898,7 @@ builtIn(alignStatus) {
 	if (!getValueType(val, SVT_INT, fun->stack->thisVar))
 		return BR_ERROR;
 	trimStack(fun->stack);
-	nowStatus->alignStatus = (short)val;
+	nowStatus->alignStatus = (int16)val;
 	return BR_CONTINUE;
 }
 
diff --git a/engines/sludge/fileset.cpp b/engines/sludge/fileset.cpp
index c138bb5..35b9d3b 100644
--- a/engines/sludge/fileset.cpp
+++ b/engines/sludge/fileset.cpp
@@ -74,7 +74,7 @@ bool openObjectSlice(int num) {
 	return sliceBusy = true;
 }
 
-unsigned int openFileFromNum(int num) {
+uint openFileFromNum(int num) {
 //	FILE * dbug = fopen ("debuggy.txt", "at");
 
 	if (sliceBusy) {
@@ -124,16 +124,16 @@ char *convertString(char *s) {
 		}
 	}
 
-	size_t len1 = strlen(s) + 1;
-	size_t len2 = 65535;
-	size_t iconv_value =
+	uint len1 = strlen(s) + 1;
+	uint len2 = 65535;
+	uint iconv_value =
 #ifdef _WIN32
 	iconv(convert, (const char **) tmp1, &len1, tmp2, &len2);
 #else
 	iconv(convert, (char **) tmp1, &len1, tmp2, &len2);
 #endif
 
-	if (iconv_value == (size_t) - 1) {
+	if (iconv_value == (uint) - 1) {
 		switch (errno) {
 			/* See "man 3 iconv" for an explanation. */
 			case EILSEQ:
@@ -190,7 +190,7 @@ void finishAccess() {
 
 int32_t startIndex;
 
-void setFileIndices(Common::File *fp, int numLanguages, unsigned int skipBefore) {
+void setFileIndices(Common::File *fp, int numLanguages, uint skipBefore) {
 	if (fp) {
 		// Keep hold of the file handle, and let things get at it
 		bigDataFile = fp;
diff --git a/engines/sludge/fileset.h b/engines/sludge/fileset.h
index 2dec0d3..61ab417 100644
--- a/engines/sludge/fileset.h
+++ b/engines/sludge/fileset.h
@@ -28,9 +28,9 @@ namespace Sludge {
 
 extern Common::File *bigDataFile;
 
-void setFileIndices(Common::File *fp, int, unsigned int);
+void setFileIndices(Common::File *fp, int, uint);
 
-unsigned int openFileFromNum(int num);
+uint openFileFromNum(int num);
 bool openSubSlice(int num);
 bool openObjectSlice(int num);
 char *getNumberedString(int value);
diff --git a/engines/sludge/fonttext.cpp b/engines/sludge/fonttext.cpp
index b0324d3..161c357 100644
--- a/engines/sludge/fonttext.cpp
+++ b/engines/sludge/fonttext.cpp
@@ -33,7 +33,7 @@ namespace Sludge {
 spriteBank theFont;
 int fontHeight = 0, numFontColours, loadedFontNum;
 Common::U32String fontOrderString;
-short fontSpace = -1;
+int16 fontSpace = -1;
 
 uint32 *fontTable = NULL;
 uint fontTableSize = 0;
diff --git a/engines/sludge/freeze.cpp b/engines/sludge/freeze.cpp
index 2f80157..deaa4eb 100644
--- a/engines/sludge/freeze.cpp
+++ b/engines/sludge/freeze.cpp
@@ -51,12 +51,12 @@ extern eventHandlers *currentEvents;
 extern personaAnimation *mouseCursorAnim;
 extern int mouseCursorFrameNum;
 extern int cameraX, cameraY;
-extern unsigned int sceneWidth, sceneHeight;
+extern uint sceneWidth, sceneHeight;
 extern float cameraZoom;
 extern zBufferData zBuffer;
 extern bool backdropExists;
 frozenStuffStruct *frozenStuff = NULL;
-extern unsigned int sceneWidth, sceneHeight;
+extern uint sceneWidth, sceneHeight;
 Graphics::Surface freezeSurface;
 
 void shufflePeople();
diff --git a/engines/sludge/graphics.cpp b/engines/sludge/graphics.cpp
index dbcb691..7211979 100644
--- a/engines/sludge/graphics.cpp
+++ b/engines/sludge/graphics.cpp
@@ -33,7 +33,7 @@
 
 namespace Sludge {
 
-unsigned int winWidth, winHeight;
+uint winWidth, winHeight;
 int viewportHeight, viewportWidth;
 int viewportOffsetX = 0, viewportOffsetY = 0;
 
@@ -45,7 +45,7 @@ extern int specialSettings;
 
 void setMovieViewport();
 
-extern unsigned int sceneWidth, sceneHeight;
+extern uint sceneWidth, sceneHeight;
 extern zBufferData zBuffer;
 extern int lightMapNumber;
 
diff --git a/engines/sludge/graphics.h b/engines/sludge/graphics.h
index c03d194..463d384 100644
--- a/engines/sludge/graphics.h
+++ b/engines/sludge/graphics.h
@@ -26,7 +26,7 @@
 
 namespace Sludge {
 
-extern unsigned int winWidth, winHeight;
+extern uint winWidth, winHeight;
 extern int viewportHeight, viewportWidth;
 extern int viewportOffsetX, viewportOffsetY;
 extern int realWinWidth, realWinHeight;
diff --git a/engines/sludge/language.cpp b/engines/sludge/language.cpp
index ebf4367..b7a45ed 100644
--- a/engines/sludge/language.cpp
+++ b/engines/sludge/language.cpp
@@ -36,7 +36,7 @@ int *languageTable;
 char **languageName;
 settingsStruct gameSettings;
 
-unsigned int stringToInt(char *s) {
+uint stringToInt(char *s) {
 	int i = 0;
 	bool negative = false;
 	for (;;) {
@@ -103,7 +103,7 @@ void readIniFile(const char *filename) {
 
 	char lineSoFar[257] = "";
 	char secondSoFar[257] = "";
-	unsigned char here = 0;
+	byte here = 0;
 	char readChar = ' ';
 	bool keepGoing = true;
 	bool doingSecond = false;
@@ -186,7 +186,7 @@ void makeLanguageTable(Common::File *table) {
 	if (!checkNew(languageName))
 		return;
 
-	for (unsigned int i = 0; i <= gameSettings.numLanguages; i++) {
+	for (uint i = 0; i <= gameSettings.numLanguages; i++) {
 		languageTable[i] = i ? table->readUint16BE() : 0;
 		debug(kSludgeDebugDataLoad, "languageTable %i: %i", i, languageTable[i]);
 		languageName[i] = 0;
@@ -202,7 +202,7 @@ void makeLanguageTable(Common::File *table) {
 int getLanguageForFileB() {
 	int indexNum = -1;
 
-	for (unsigned int i = 0; i <= gameSettings.numLanguages; i++) {
+	for (uint i = 0; i <= gameSettings.numLanguages; i++) {
 		if (languageTable[i] == gameSettings.languageID)
 			indexNum = i;
 	}
diff --git a/engines/sludge/language.h b/engines/sludge/language.h
index 85d50bb..c38ac7c 100644
--- a/engines/sludge/language.h
+++ b/engines/sludge/language.h
@@ -29,10 +29,10 @@
 namespace Sludge {
 
 struct settingsStruct {
-	unsigned int languageID;
-	unsigned int numLanguages;
+	uint languageID;
+	uint numLanguages;
 	bool userFullScreen;
-	unsigned int refreshRate;
+	uint refreshRate;
 	int antiAlias;
 	bool fixedPixels;
 	bool noStartWindow;
diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index e9daa9b..41e0cdb 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -67,17 +67,17 @@ extern char *fontOrderString;                       // "    "   "
 extern FILETIME fileTime;                           // In sludger.cpp
 extern int speechMode;                              // "    "   "
 extern int lightMapNumber;                          // In backdrop.cpp
-extern unsigned int sceneWidth, sceneHeight;        // "    "   "
+extern uint sceneWidth, sceneHeight;        // "    "   "
 extern int cameraX, cameraY;                        // "    "   "
 extern float cameraZoom;
-extern unsigned char brightnessLevel;               // "    "   "
-extern short fontSpace;                             // in textfont.cpp
-extern unsigned char fadeMode;                      // In transition.cpp
+extern byte brightnessLevel;               // "    "   "
+extern int16 fontSpace;                             // in textfont.cpp
+extern byte fadeMode;                      // In transition.cpp
 extern bool captureAllKeys;
 extern bool allowAnyFilename;
-extern unsigned short saveEncoding;                 // in savedata.cpp
-extern unsigned char currentBurnR, currentBurnG, currentBurnB;
-extern unsigned int currentBlankColour;             // in backdrop.cpp
+extern uint16 saveEncoding;                 // in savedata.cpp
+extern byte currentBurnR, currentBurnG, currentBurnB;
+extern uint currentBlankColour;             // in backdrop.cpp
 extern parallaxLayer *parallaxStuff;                //      "
 extern int lightMapMode;                    //      "
 extern int languageNum;
diff --git a/engines/sludge/moreio.cpp b/engines/sludge/moreio.cpp
index f76b919..138f709 100644
--- a/engines/sludge/moreio.cpp
+++ b/engines/sludge/moreio.cpp
@@ -65,7 +65,7 @@ char *readString(Common::SeekableReadStream *stream) {
 float floatSwap(float f) {
 	union {
 		float f;
-		unsigned char b[4];
+		byte b[4];
 	} dat1, dat2;
 
 	dat1.f = f;
@@ -78,7 +78,7 @@ float floatSwap(float f) {
 
 float getFloat(Common::SeekableReadStream *stream) {
 	float f;
-	size_t bytes_read = stream->read(&f, sizeof(float));
+	uint bytes_read = stream->read(&f, sizeof(float));
 	if (bytes_read != sizeof(float) && stream->err()) {
 		debug("Reading error in getFloat.\n");
 	}
@@ -97,8 +97,8 @@ void putFloat(float f, Common::WriteStream *stream) {
 	stream->write(&f, sizeof(float));
 }
 
-short shortSwap(short s) {
-	unsigned char b1, b2;
+int16 shortSwap(int16 s) {
+	byte b1, b2;
 
 	b1 = s & 255;
 	b2 = (s >> 8) & 255;
@@ -106,10 +106,10 @@ short shortSwap(short s) {
 	return (b1 << 8) + b2;
 }
 
-short getSigned(Common::SeekableReadStream *stream) {
-	short f;
-	size_t bytes_read = stream->read(&f, sizeof(short));
-	if (bytes_read != sizeof(short) && stream->err()) {
+int16 getSigned(Common::SeekableReadStream *stream) {
+	int16 f;
+	uint bytes_read = stream->read(&f, sizeof(int16));
+	if (bytes_read != sizeof(int16) && stream->err()) {
 		debug("Reading error in getSigned.\n");
 	}
 #ifdef  __BIG_ENDIAN__
@@ -118,11 +118,11 @@ short getSigned(Common::SeekableReadStream *stream) {
 	return f;
 }
 
-void putSigned(short f, Common::WriteStream *stream) {
+void putSigned(int16 f, Common::WriteStream *stream) {
 #ifdef  __BIG_ENDIAN__
 	f = shortSwap(f);
 #endif
-	stream->write(&f, sizeof(short));
+	stream->write(&f, sizeof(int16));
 }
 
 char *encodeFilename(char *nameIn) {
diff --git a/engines/sludge/moreio.h b/engines/sludge/moreio.h
index 7ca59ec..5cf01a2 100644
--- a/engines/sludge/moreio.h
+++ b/engines/sludge/moreio.h
@@ -27,12 +27,12 @@ namespace Sludge {
 // Read
 char *readString(Common::SeekableReadStream *stream);
 float getFloat(Common::SeekableReadStream *stream);
-short getSigned(Common::SeekableReadStream *stream);
+int16 getSigned(Common::SeekableReadStream *stream);
 
 // Write
 void writeString(char *s, Common::WriteStream *stream);
 void putFloat(float f, Common::WriteStream *stream);
-void putSigned(short f, Common::WriteStream *stream);
+void putSigned(int16 f, Common::WriteStream *stream);
 
 char *encodeFilename(char *nameIn);
 char *decodeFilename(char *nameIn);
diff --git a/engines/sludge/movie.cpp b/engines/sludge/movie.cpp
index 2d431e8..da6eb7f 100644
--- a/engines/sludge/movie.cpp
+++ b/engines/sludge/movie.cpp
@@ -69,7 +69,7 @@ float movieAspect = 1.6;
 #if 0
 typedef struct audioBuffers {
 	char *buffer;
-	unsigned int size;
+	uint size;
 	audioBuffers *next;
 	Uint32 time_ms;
 }audioBuffers;
@@ -120,7 +120,7 @@ void audio_queue_init(audioQueue *q) {
 	q->cond = SDL_CreateCond();
 
 }
-int audio_queue_put(audioQueue *q, char *buffer, unsigned int size, long long time_ms) {
+int audio_queue_put(audioQueue *q, char *buffer, uint size, long long time_ms) {
 
 	audioBuffers *audioBuf = new audioBuffers;
 	if (!audioBuf)
@@ -275,10 +275,10 @@ void setMovieViewport() {
 	}
 }
 
-static uint64_t xiph_lace_value(unsigned char **np) {
+static uint64_t xiph_lace_value(byte **np) {
 	uint64_t lace;
 	uint64_t value;
-	unsigned char *p = *np;
+	byte *p = *np;
 
 	lace = *p++;
 	value = lace;
@@ -300,8 +300,8 @@ bool fakeAudio = false;
 // send audio to audio device...
 ALuint feedAudio(void *userdata, ALubyte *data, ALuint length) {
 	static char *buffer = NULL;
-	static unsigned int bufOffset = 0;
-	static unsigned int bufSize = 0;
+	static uint bufOffset = 0;
+	static uint bufSize = 0;
 
 	ALuint got = 0;
 	int bufLen;
@@ -443,8 +443,8 @@ int playMovie(int fileNumber) {
 			audioBitDepth = pAudioTrack->GetBitDepth();
 			audioSampleRate = pAudioTrack->GetSamplingRate();
 
-			size_t audioHeaderSize;
-			const unsigned char *audioHeader = pAudioTrack->GetCodecPrivate(audioHeaderSize);
+			uint audioHeaderSize;
+			const byte *audioHeader = pAudioTrack->GetCodecPrivate(audioHeaderSize);
 
 			if (audioHeaderSize < 1) {
 				warning("Strange audio track in movie.");
@@ -452,9 +452,9 @@ int playMovie(int fileNumber) {
 				continue;
 			}
 
-			unsigned char *p = (unsigned char *)audioHeader;
+			byte *p = (byte *)audioHeader;
 
-			unsigned int count = *p++ + 1;
+			uint count = *p++ + 1;
 			if (count != 3) {
 				warning("Strange audio track in movie.");
 				audioTrack = -1;
@@ -529,7 +529,7 @@ int playMovie(int fileNumber) {
 	if (vpx_codec_dec_init(&codec, interface, NULL, 0))
 	die_codec(&codec, "Failed to initialize decoder for movie.");
 
-	unsigned char *frame = new unsigned char[256 * 1024];
+	byte *frame = new byte[256 * 1024];
 	if (! checkNew(frame)) return false;
 
 	const mkvparser::Cluster *pCluster = pSegment->GetFirst();
@@ -647,7 +647,7 @@ int playMovie(int fileNumber) {
 
 				if (size > sizeof(frame)) {
 					if (frame) delete [] frame;
-					frame = new unsigned char[size];
+					frame = new byte[size];
 					if (! checkNew(frame)) return 0;
 				}
 				/*
@@ -673,7 +673,7 @@ int playMovie(int fileNumber) {
 						if (img->fmt != VPX_IMG_FMT_I420)
 						fatal("Movie error. The movie is not in I420 colour format, which is the only one I can hanlde at the moment.");
 
-						unsigned int y;
+						uint y;
 
 						GLubyte *ytex = NULL;
 						GLubyte *utex = NULL;
@@ -688,7 +688,7 @@ int playMovie(int fileNumber) {
 
 						}
 
-						unsigned char *buf = img->planes[0];
+						byte *buf = img->planes[0];
 						for (y = 0; y < img->d_h; y++) {
 							memcpy(ytex + y * img->d_w, buf, img->d_w);
 							buf += img->stride[0];
@@ -762,7 +762,7 @@ int playMovie(int fileNumber) {
 										vorbis_fpu_setround(&fpu);
 										for (i = 0; i < audioChannels; i++) { /* It's faster in this order */
 											float *src = pcm[i];
-											short *dest = ((short *)buffer) + i;
+											int16 *dest = ((int16 *)buffer) + i;
 											for (j = 0; j < numSamples; j++) {
 												val = vorbis_ftoi(src[j] * 32768.f);
 												if (val > 32767)val = 32767;
@@ -778,7 +778,7 @@ int playMovie(int fileNumber) {
 										vorbis_fpu_setround(&fpu);
 										for (i = 0; i < audioChannels; i++) {
 											float *src = pcm[i];
-											short *dest = ((short *)buffer) + i;
+											int16 *dest = ((int16 *)buffer) + i;
 											for (j = 0; j < numSamples; j++) {
 												val = vorbis_ftoi(src[j] * 32768.f);
 												if (val > 32767)val = 32767;
diff --git a/engines/sludge/objtypes.h b/engines/sludge/objtypes.h
index 0bd785a..f111606 100644
--- a/engines/sludge/objtypes.h
+++ b/engines/sludge/objtypes.h
@@ -32,10 +32,10 @@ struct objectType {
 	char *screenName;
 	int objectNum;
 	objectType *next;
-	unsigned char r, g, b;
+	byte r, g, b;
 	int numCom;
 	int speechGap, walkSpeed, wrapSpeech, spinSpeed;
-	unsigned short int flags;
+	uint16 flags;
 	combination *allCombis;
 };
 
diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index 43adbd9..1a03284 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -57,8 +57,8 @@ extern flor *currentFloor;
 
 extern inputType input;
 onScreenPerson *allPeople = NULL;
-short int scaleHorizon = 75;
-short int scaleDivide = 150;
+int16 scaleHorizon = 75;
+int16 scaleDivide = 150;
 extern screenRegion *allScreenRegions;
 
 #define TF_max(a, b) ((a > b) ? a : b)
@@ -225,7 +225,7 @@ bool setPersonExtra(int thisNum, int extra) {
 	return false;
 }
 
-void setScale(short int h, short int d) {
+void setScale(int16 h, int16 d) {
 	scaleHorizon = h;
 	scaleDivide = d;
 }
@@ -397,7 +397,7 @@ void setDrawMode(int h, int ob) {
 	setMyDrawMode(moveMe, h);
 }
 
-void setPersonTransparency(int ob, unsigned char x) {
+void setPersonTransparency(int ob, byte x) {
 	onScreenPerson *moveMe = findPerson(ob);
 	if (!moveMe)
 		return;
@@ -407,7 +407,7 @@ void setPersonTransparency(int ob, unsigned char x) {
 	moveMe->transparency = x;
 }
 
-void setPersonColourise(int ob, unsigned char r, unsigned char g, unsigned char b, unsigned char colourmix) {
+void setPersonColourise(int ob, byte r, byte g, byte b, byte colourmix) {
 	onScreenPerson *moveMe = findPerson(ob);
 	if (!moveMe)
 		return;
diff --git a/engines/sludge/people.h b/engines/sludge/people.h
index 45ba55a..b02bc1c 100644
--- a/engines/sludge/people.h
+++ b/engines/sludge/people.h
@@ -67,7 +67,7 @@ struct onScreenPerson {
 	int direction, directionWhenDoneWalking;
 	struct objectType *thisType;
 	int extra, spinSpeed;
-	unsigned char r, g, b, colourmix, transparency;
+	byte r, g, b, colourmix, transparency;
 };
 
 // Initialisation and creation
@@ -85,15 +85,15 @@ void removeOneCharacter(int i);
 
 // Things which affect or use all characters
 onScreenPerson *findPerson(int v);
-void setScale(short int h, short int d);
+void setScale(int16 h, int16 d);
 
 // Things which affect one character
 void makeTalker(onScreenPerson &me);
 void makeSilent(onScreenPerson &me);
 void setShown(bool h, int ob);
 void setDrawMode(int h, int ob);
-void setPersonTransparency(int ob, unsigned char x);
-void setPersonColourise(int ob, unsigned char r, unsigned char g, unsigned char b, unsigned char colourmix);
+void setPersonTransparency(int ob, byte x);
+void setPersonColourise(int ob, byte r, byte g, byte b, byte colourmix);
 
 // Moving 'em
 void movePerson(int x, int y, int objNum);
diff --git a/engines/sludge/savedata.cpp b/engines/sludge/savedata.cpp
index 081798f..1059cc1 100644
--- a/engines/sludge/savedata.cpp
+++ b/engines/sludge/savedata.cpp
@@ -31,7 +31,7 @@
 
 namespace Sludge {
 
-unsigned short saveEncoding = false;
+uint16 saveEncoding = false;
 char encode1 = 0;
 char encode2 = 0;
 
@@ -106,7 +106,7 @@ char *readTextPlain(Common::File *fp) {
 		reply = new char[stringSize + 1];
 		if (reply == NULL)
 			return NULL;
-		size_t bytes_read = fp->read(reply, stringSize);
+		uint bytes_read = fp->read(reply, stringSize);
 		if (bytes_read != stringSize && fp->err()) {
 			warning("Reading error in readTextPlain.");
 		}
@@ -147,8 +147,8 @@ bool fileToStack(char *filename, stackHandler *sH) {
 		return fatal("No such file", filename); //TODO: false value
 	}
 
-	encode1 = (unsigned char)saveEncoding & 255;
-	encode2 = (unsigned char)(saveEncoding >> 8);
+	encode1 = (byte)saveEncoding & 255;
+	encode2 = (byte)(saveEncoding >> 8);
 
 	while (*checker) {
 		if (fd.readByte() != *checker) {
@@ -227,8 +227,8 @@ bool stackToFile(char *filename, const variable &from) {
 
 	variableStack *hereWeAre = from.varData.theStack -> first;
 
-	encode1 = (unsigned char) saveEncoding & 255;
-	encode2 = (unsigned char)(saveEncoding >> 8);
+	encode1 = (byte)saveEncoding & 255;
+	encode2 = (byte)(saveEncoding >> 8);
 
 	if (saveEncoding) {
 		fprintf(fp, "[Custom data (encoded)]\r\n");
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index ac60420..22e1926 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -57,7 +57,7 @@ namespace Sludge {
 extern personaAnimation *mouseCursorAnim;
 extern spritePalette pastePalette;
 extern int dialogValue;
-extern unsigned int sceneWidth, sceneHeight;
+extern uint sceneWidth, sceneHeight;
 extern char *launchMe;
 extern variable *launchResult;
 
@@ -73,10 +73,10 @@ char * *allResourceNames = NULL;
 int selectedLanguage = 0;
 int languageNum = -1;
 
-unsigned char *gameIcon = NULL;
+byte *gameIcon = NULL;
 int iconW = 0, iconH = 0;
 
-unsigned char *gameLogo = NULL;
+byte *gameLogo = NULL;
 int logoW = 0, logoH = 0;
 
 int gameVersion;
@@ -85,7 +85,7 @@ FILETIME fileTime;
 extern int desiredfps;
 bool captureAllKeys = false;
 
-unsigned char brightnessLevel = 255;
+byte brightnessLevel = 255;
 
 eventHandlers mainHandlers;
 eventHandlers *currentEvents = &mainHandlers;
@@ -237,7 +237,7 @@ bool initSludge(const char *filename) {
 
 	delete[] readString(fp);  // Unused - was used for registration purposes.
 
-	size_t bytes_read = fp->read(&fileTime, sizeof(FILETIME));
+	uint bytes_read = fp->read(&fileTime, sizeof(FILETIME));
 	if (bytes_read != sizeof(FILETIME) && fp->err()) {
 		debug("Reading error in initSludge.");
 	}
@@ -268,7 +268,7 @@ bool initSludge(const char *filename) {
 	delete[] checker;
 	checker = NULL;
 
-	unsigned char customIconLogo = fp->readByte();
+	byte customIconLogo = fp->readByte();
 	debug(kSludgeDebugDataLoad, "Game icon type: %i", customIconLogo);
 
 	if (customIconLogo & 1) {
@@ -341,14 +341,14 @@ bool initSludge(const char *filename) {
 
 		}
 
-		gameIcon = new unsigned char [iconW * iconH * 4];
+		gameIcon = new byte [iconW * iconH * 4];
 		if (!gameIcon) return fatal("Can't reserve memory for game icon.");
 
 		int32_t transCol = 63519;
 		Uint8 *p = (Uint8 *) gameIcon;
 
 		if (fileIsPNG) {
-			unsigned char *row_pointers[iconH];
+			byte *row_pointers[iconH];
 			for (int i = 0; i < iconH; i++)
 			row_pointers[i] = p + 4 * i * iconW;
 
@@ -360,7 +360,7 @@ bool initSludge(const char *filename) {
 			for (int t2 = 0; t2 < iconH; t2 ++) {
 				int t1 = 0;
 				while (t1 < iconW) {
-					unsigned short c = (unsigned short) fp->readUint16BE();
+					uint16 c = (uint16) fp->readUint16BE();
 					if (c & 32) {
 						n = fgetc(fp) + 1;
 						c -= 32;
@@ -452,14 +452,14 @@ bool initSludge(const char *filename) {
 
 		if ((logoW != 310) || (logoH != 88)) return fatal("Game logo have wrong dimensions. (Should be 310x88)");
 
-		gameLogo = new unsigned char [logoW * logoH * 4];
+		gameLogo = new byte [logoW * logoH * 4];
 		if (!gameLogo) return fatal("Can't reserve memory for game logo.");
 
 		// int32_t transCol = 63519;
 		Uint8 *p = (Uint8 *) gameLogo;
 
 		if (fileIsPNG) {
-			unsigned char *row_pointers[logoH];
+			byte *row_pointers[logoH];
 			for (int i = 0; i < logoH; i++)
 			row_pointers[i] = p + 4 * i * logoW;
 
@@ -471,7 +471,7 @@ bool initSludge(const char *filename) {
 			for (int t2 = 0; t2 < logoH; t2 ++) {
 				int t1 = 0;
 				while (t1 < logoW) {
-					unsigned short c = (unsigned short) fp->readUint16BE();
+					uint16 c = (uint16) fp->readUint16BE();
 					if (c & 32) {
 						n = fgetc(fp) + 1;
 						c -= 32;
@@ -701,7 +701,7 @@ void unfreezeSubs() {
 bool continueFunction(loadedFunction *fun) {
 	bool keepLooping = true;
 	bool advanceNow;
-	unsigned int param;
+	uint param;
 	sludgeCommand com;
 
 	if (fun->cancelMe) {
@@ -1219,7 +1219,7 @@ bool runSludge() {
 bool loadFunctionCode(loadedFunction *newFunc) {
 
 	debug(kSludgeDebugDataLoad, "Current address: %i", bigDataFile->pos());
-	unsigned int numLines, numLinesRead;
+	uint numLines, numLinesRead;
 
 	if (!openSubSlice(newFunc->originalNumber))
 		return false;
@@ -1256,7 +1256,7 @@ bool loadFunctionCode(loadedFunction *newFunc) {
 	return true;
 }
 
-int startNewFunctionNum(unsigned int funcNum, unsigned int numParamsExpected,
+int startNewFunctionNum(uint funcNum, uint numParamsExpected,
 		loadedFunction *calledBy, variableStack *&vStack, bool returnSommet) {
 	loadedFunction *newFunc = new loadedFunction;
 	checkNew(newFunc);
diff --git a/engines/sludge/sludger.h b/engines/sludge/sludger.h
index 10c1794..19c6f53 100644
--- a/engines/sludge/sludger.h
+++ b/engines/sludge/sludger.h
@@ -61,11 +61,11 @@ struct loadedFunction {
 	variable *localVars;
 	variableStack *stack;
 	variable reg;
-	unsigned int runThisLine;
+	uint runThisLine;
 	loadedFunction *calledBy;
 	loadedFunction *next;
 	bool returnSomething, isSpeech, unfreezable, cancelMe;
-	unsigned char freezerLevel;
+	byte freezerLevel;
 };
 
 struct inputType {
@@ -73,13 +73,13 @@ struct inputType {
 	int mouseX, mouseY, keyPressed;
 };
 
-extern unsigned char *gameIcon;
+extern byte *gameIcon;
 extern int iconW, iconH;
 
 bool initSludge(const char *);
 void displayBase();
 void sludgeDisplay();
-int startNewFunctionNum(unsigned int, unsigned int, loadedFunction *, variableStack*&, bool = true);
+int startNewFunctionNum(uint, uint, loadedFunction *, variableStack*&, bool = true);
 bool handleInput();
 void restartFunction(loadedFunction *fun);
 bool loadFunctionCode(loadedFunction *newFunc);
diff --git a/engines/sludge/sound.cpp b/engines/sludge/sound.cpp
index a92a51c..d77f3d4 100644
--- a/engines/sludge/sound.cpp
+++ b/engines/sludge/sound.cpp
@@ -267,8 +267,8 @@ bool playMOD(int f, int a, int fromTrack) {
 		return false;
 	}
 
-	unsigned char *memImage;
-	memImage = (unsigned char *) loadEntireFileToMemory(bigDataFile, length);
+	byte *memImage;
+	memImage = (byte *) loadEntireFileToMemory(bigDataFile, length);
 	if (! memImage) return fatal(ERROR_MUSIC_MEMORY_LOW);
 
 	modCache[a].stream = alureCreateStreamFromMemory(memImage, length, 19200, 0, NULL);
@@ -641,7 +641,7 @@ int initMovieSound(int f, ALenum format, int audioChannels, ALuint samplerate,
 }
 #endif
 
-unsigned int getSoundSource(int index) {
+uint getSoundSource(int index) {
 	return 0; /*soundCache[index].playingOnSource;*/ //TODO:false value
 }
 
diff --git a/engines/sludge/sound.h b/engines/sludge/sound.h
index 05db6a4..3255c31 100644
--- a/engines/sludge/sound.h
+++ b/engines/sludge/sound.h
@@ -69,7 +69,7 @@ void debugSounds();
 void loadSounds(Common::SeekableReadStream *stream);
 void saveSounds(Common::WriteStream *stream);
 
-unsigned int getSoundSource(int index);
+uint getSoundSource(int index);
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index 9790193..bba4ca3 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -70,7 +70,7 @@ extern float cameraZoom;
 extern Graphics::Surface renderSurface;
 extern Graphics::Surface backdropSurface;
 
-unsigned char currentBurnR = 0, currentBurnG = 0, currentBurnB = 0;
+byte currentBurnR = 0, currentBurnG = 0, currentBurnB = 0;
 
 void forgetSpriteBank(spriteBank &forgetme) {
 	if (forgetme.myPalette.pal) {
@@ -104,17 +104,17 @@ bool reserveSpritePal(spritePalette &sP, int n) {
 		delete[] sP.b;
 	}
 
-	sP.pal = new unsigned short int[n];
+	sP.pal = new uint16[n];
 	if (!checkNew(sP.pal))
 		return false;
 
-	sP.r = new unsigned char[n];
+	sP.r = new byte[n];
 	if (!checkNew(sP.r))
 		return false;
-	sP.g = new unsigned char[n];
+	sP.g = new byte[n];
 	if (!checkNew(sP.g))
 		return false;
-	sP.b = new unsigned char[n];
+	sP.b = new byte[n];
 	if (!checkNew(sP.b))
 		return false;
 	sP.total = n;
@@ -222,7 +222,7 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 				}
 			}
 		} else { // RAW DATA
-			size_t bytes_read = bigDataFile->read(data, picwidth * picheight);
+			uint bytes_read = bigDataFile->read(data, picwidth * picheight);
 			if (bytes_read != picwidth * picheight && bigDataFile->err()) {
 				warning("Reading error in loadSpriteBank.");
 			}
@@ -256,7 +256,7 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 		int transColour = -1;
 		int size = loadhere.sprites[i].surface.w * loadhere.sprites[i].surface.h;
 		while (fromhere < size) {
-			unsigned char s = spriteData[i][fromhere++];
+			byte s = spriteData[i][fromhere++];
 			if (s) {
 				transColour = s;
 				break;
@@ -266,7 +266,7 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 		for (int y = 0; y < loadhere.sprites[i].surface.h; y++) {
 			for (int x = 0; x < loadhere.sprites[i].surface.w; x++) {
 				byte *target = (byte *)loadhere.sprites[i].surface.getBasePtr(x, y);
-				unsigned char s = spriteData[i][fromhere++];
+				byte s = spriteData[i][fromhere++];
 				if (s) {
 					target[0] = (byte)255;
 					target[1] = (byte)loadhere.myPalette.b[s];
@@ -589,7 +589,7 @@ void flipFontSprite(int x, int y, sprite &single, const spritePalette &fontPal)
 	fontSprite(true, x, y, single, fontPal);
 }
 
-unsigned char curLight[3];
+byte curLight[3];
 
 void setDrawMode(onScreenPerson *thisPerson) {
 #if 0
diff --git a/engines/sludge/sprites.h b/engines/sludge/sprites.h
index effb512..fd1b347 100644
--- a/engines/sludge/sprites.h
+++ b/engines/sludge/sprites.h
@@ -38,11 +38,11 @@ struct sprite {
 
 class spritePalette {
 public:
-	unsigned short int *pal;
-	unsigned char *r;
-	unsigned char *g;
-	unsigned char *b;
-	unsigned char originalRed, originalGreen, originalBlue, total;
+	uint16 *pal;
+	byte *r;
+	byte *g;
+	byte *b;
+	byte originalRed, originalGreen, originalBlue, total;
 
 	spritePalette() : pal(0), r(0), g(0), b(0), total(0) {
 		originalRed = originalGreen = originalBlue = 255;
diff --git a/engines/sludge/statusba.h b/engines/sludge/statusba.h
index 03c61cf..b6c0c78 100644
--- a/engines/sludge/statusba.h
+++ b/engines/sludge/statusba.h
@@ -31,7 +31,7 @@ struct statusBar {
 
 struct statusStuff {
 	statusBar *firstStatusBar;
-	unsigned short alignStatus;
+	uint16 alignStatus;
 	int litStatus;
 	int statusX, statusY;
 	int statusR, statusG, statusB;
@@ -44,8 +44,8 @@ void setStatusBar(char *txt);
 void clearStatusBar();
 void addStatusBar();
 void killLastStatus();
-void statusBarColour(unsigned char r, unsigned char g, unsigned char b);
-void statusBarLitColour(unsigned char r, unsigned char g, unsigned char b);
+void statusBarColour(byte r, byte g, byte b);
+void statusBarLitColour(byte r, byte g, byte b);
 void setLitStatus(int i);
 const char *statusBarText();
 void positionStatus(int, int);
diff --git a/engines/sludge/thumbnail.cpp b/engines/sludge/thumbnail.cpp
index 74c77ff..f28035b 100644
--- a/engines/sludge/thumbnail.cpp
+++ b/engines/sludge/thumbnail.cpp
@@ -158,12 +158,12 @@ void showThumbnail(char *filename, int atX, int atY) {
 		if (thumbnailTexture == NULL) return;
 
 		int t1, t2;
-		unsigned short c;
+		uint16 c;
 		GLubyte *target;
 		for (t2 = 0; t2 < fileHeight; t2++) {
 			t1 = 0;
 			while (t1 < fileWidth) {
-				c = (unsigned short) fp->readUint16BE();
+				c = (uint16) fp->readUint16BE();
 				target = thumbnailTexture + 4 * picWidth * t2 + t1 * 4;
 				target[0] = (GLubyte) redValue(c);
 				target[1] = (GLubyte) greenValue(c);
diff --git a/engines/sludge/transition.cpp b/engines/sludge/transition.cpp
index 207eca6..e43f8b5 100644
--- a/engines/sludge/transition.cpp
+++ b/engines/sludge/transition.cpp
@@ -31,11 +31,11 @@ extern GLuint snapshotTextureName;
 
 namespace Sludge {
 
-extern unsigned char brightnessLevel;
+extern byte brightnessLevel;
 
 extern float snapTexW, snapTexH;
 
-unsigned char fadeMode = 2;
+byte fadeMode = 2;
 
 //----------------------------------------------------
 // PROPER BRIGHTNESS FADING
diff --git a/engines/sludge/utf8.cpp b/engines/sludge/utf8.cpp
index 95f9e91..61c2975 100644
--- a/engines/sludge/utf8.cpp
+++ b/engines/sludge/utf8.cpp
@@ -51,7 +51,7 @@ uint32 UTF8Converter::nextchar(const char *s, int *i) {
 
 	do {
 		ch <<= 6;
-		ch += (unsigned char)s[(*i)++];
+		ch += (byte)s[(*i)++];
 		sz++;
 	} while (s[*i] && !isutf(s[*i]));
 	ch -= offsetsFromUTF8[sz - 1];
diff --git a/engines/sludge/variable.cpp b/engines/sludge/variable.cpp
index 9792dbf..30686e4 100644
--- a/engines/sludge/variable.cpp
+++ b/engines/sludge/variable.cpp
@@ -456,7 +456,7 @@ bool copyVariable(const variable &from, variable &to) {
 	return copyMain(from, to);
 }
 
-variable *fastArrayGetByIndex(fastArrayHandler *vS, unsigned int theIndex) {
+variable *fastArrayGetByIndex(fastArrayHandler *vS, uint theIndex) {
 	if (theIndex < 0 || theIndex >= vS->size)
 		return NULL;
 	return &vS->fastVariables[theIndex];
@@ -535,7 +535,7 @@ bool addVarToStackQuick(variable &va, variableStack *&thisStack) {
 	return true;
 }
 
-bool stackSetByIndex(variableStack *vS, unsigned int theIndex, const variable &va) {
+bool stackSetByIndex(variableStack *vS, uint theIndex, const variable &va) {
 	while (theIndex--) {
 		vS = vS->next;
 		if (!vS)
@@ -544,7 +544,7 @@ bool stackSetByIndex(variableStack *vS, unsigned int theIndex, const variable &v
 	return copyVariable(va, vS->thisVar);
 }
 
-variable *stackGetByIndex(variableStack *vS, unsigned int theIndex) {
+variable *stackGetByIndex(variableStack *vS, uint theIndex) {
 	while (theIndex--) {
 		vS = vS->next;
 		if (!vS) {
diff --git a/engines/sludge/variable.h b/engines/sludge/variable.h
index 295473e..f36e4e7 100644
--- a/engines/sludge/variable.h
+++ b/engines/sludge/variable.h
@@ -108,13 +108,13 @@ int deleteVarFromStack(const variable &va, variableStack *&thisStack,
 variableStack *stackFindLast(variableStack *hunt);
 bool copyStack(const variable &from, variable &to);
 int stackSize(const stackHandler *me);
-bool stackSetByIndex(variableStack *, unsigned int, const variable &);
-variable *stackGetByIndex(variableStack *, unsigned int);
+bool stackSetByIndex(variableStack *, uint, const variable &);
+variable *stackGetByIndex(variableStack *, uint);
 bool getSavedGamesStack(stackHandler *sH, char *ext);
 
 bool makeFastArrayFromStack(variable &to, const stackHandler *stacky);
 bool makeFastArraySize(variable &to, int size);
-variable *fastArrayGetByIndex(fastArrayHandler *vS, unsigned int theIndex);
+variable *fastArrayGetByIndex(fastArrayHandler *vS, uint theIndex);
 
 #define DEBUG_STACKINESS    0
 


Commit: 2563180f11589213a816a2a6c3482ce308df922b
    https://github.com/scummvm/scummvm/commit/2563180f11589213a816a2a6c3482ce308df922b
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove math functions defined in sludge

Changed paths:
    engines/sludge/people.cpp
    engines/sludge/talk.cpp


diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index 1a03284..a477fbe 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -61,12 +61,6 @@ int16 scaleHorizon = 75;
 int16 scaleDivide = 150;
 extern screenRegion *allScreenRegions;
 
-#define TF_max(a, b) ((a > b) ? a : b)
-
-inline int TF_abs(int a) {
-	return (a > 0) ? a : -a;
-}
-
 void setFrames(onScreenPerson &m, int a) {
 	m.myAnim = m.myPersona->animation[(a * m.myPersona->numDirections) + m.direction];
 }
@@ -649,9 +643,9 @@ bool walkMe(onScreenPerson *thisPerson, bool move = true) {
 		if (s < 0.2)
 			s = 0.2;
 
-		maxDiff = (TF_abs(xDiff) >= TF_abs(yDiff)) ? TF_abs(xDiff) : TF_abs(yDiff);
+		maxDiff = (abs(xDiff) >= abs(yDiff)) ? abs(xDiff) : abs(yDiff);
 
-		if (TF_abs(maxDiff) > s) {
+		if (abs(maxDiff) > s) {
 			if (thisPerson->spinning) {
 				spinStep(thisPerson);
 				setFrames(*thisPerson, ANI_WALK);
diff --git a/engines/sludge/talk.cpp b/engines/sludge/talk.cpp
index ce9bd0b..8f3dd02 100644
--- a/engines/sludge/talk.cpp
+++ b/engines/sludge/talk.cpp
@@ -75,9 +75,6 @@ void killAllSpeech() {
 	}
 }
 
-#define TF_max(a, b) ((a > b) ? a : b)
-#define TF_min(a, b) ((a > b) ? b : a)
-
 inline void setObjFontColour(objectType *t) {
 	setFontColour(speech->talkCol, t->r, t->g, t->b);
 }


Commit: 389bd92ab9aedae14d6ce18a88153212ecb705b2
    https://github.com/scummvm/scummvm/commit/389bd92ab9aedae14d6ce18a88153212ecb705b2
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: correct #define in header to match file name

Changed paths:
    engines/sludge/language.h
    engines/sludge/sludge.h
    engines/sludge/sprites.h


diff --git a/engines/sludge/language.h b/engines/sludge/language.h
index c38ac7c..57bc97e 100644
--- a/engines/sludge/language.h
+++ b/engines/sludge/language.h
@@ -19,8 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#ifndef LANGUAGE_H
-#define LANGUAGE_H
+#ifndef SLUDGE_LANGUAGE_H
+#define SLUDGE_LANGUAGE_H
 
 #include "common/file.h"
 
diff --git a/engines/sludge/sludge.h b/engines/sludge/sludge.h
index 5ec197f..03297ff 100644
--- a/engines/sludge/sludge.h
+++ b/engines/sludge/sludge.h
@@ -20,8 +20,8 @@
  *
  */
 
-#ifndef SLUDGE_H
-#define SLUDGE_H
+#ifndef SLUDGE_SLUDGE_H
+#define SLUDGE_SLUDGE_H
 
 #include "common/random.h"
 #include "engines/engine.h"
diff --git a/engines/sludge/sprites.h b/engines/sludge/sprites.h
index fd1b347..80a3493 100644
--- a/engines/sludge/sprites.h
+++ b/engines/sludge/sprites.h
@@ -19,8 +19,8 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
  */
-#ifndef SLUDGE_SPRITE_H
-#define SLUDGE_SPRITE_H
+#ifndef SLUDGE_SPRITES_H
+#define SLUDGE_SPRITES_H
 
 #include "graphics/surface.h"
 #include "graphics/transparent_surface.h"


Commit: 076f841526a1cef90fecf3c54bd5a0b4cb1981d8
    https://github.com/scummvm/scummvm/commit/076f841526a1cef90fecf3c54bd5a0b4cb1981d8
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: fix u32string saving error

Changed paths:
    engines/sludge/fonttext.cpp
    engines/sludge/loadsave.cpp
    engines/sludge/moreio.cpp
    engines/sludge/moreio.h
    engines/sludge/utf8.h


diff --git a/engines/sludge/fonttext.cpp b/engines/sludge/fonttext.cpp
index 161c357..7219689 100644
--- a/engines/sludge/fonttext.cpp
+++ b/engines/sludge/fonttext.cpp
@@ -32,7 +32,7 @@ namespace Sludge {
 
 spriteBank theFont;
 int fontHeight = 0, numFontColours, loadedFontNum;
-Common::U32String fontOrderString;
+UTF8Converter fontOrder;
 int16 fontSpace = -1;
 
 uint32 *fontTable = NULL;
@@ -57,7 +57,7 @@ bool isInFont(char *theText) {
 	uint32 c = str32[0];
 
 	// check if font order contains the utf8 char
-	return fontOrderString.contains(c);
+	return fontOrder.getU32String().contains(c);
 }
 
 int stringLength(char *theText) {
@@ -161,14 +161,14 @@ void setFontColour(spritePalette &sP, byte r, byte g, byte b) {
 }
 
 bool loadFont(int filenum, const char *charOrder, int h) {
-	fontOrderString.clear();
-	fontOrderString = UTF8Converter::convertUtf8ToUtf32(charOrder);
+	fontOrder.setUTF8String(charOrder);
 
 	forgetSpriteBank(theFont);
 
 	loadedFontNum = filenum;
 
 	// get max value among all utf8 chars
+	Common::U32String fontOrderString = fontOrder.getU32String();
 	fontTableSize = 0;
 	for (uint32 i = 0; i < fontOrderString.size(); ++i) {
 		uint32 c = fontOrderString[i];
diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index 41e0cdb..df7bf9b 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -44,6 +44,7 @@
 #include "sludge/loadsave.h"
 #include "sludge/bg_effects.h"
 #include "sludge/thumbnail.h"
+#include "sludge/utf8.h"
 #include "sludge/CommonCode/version.h"
 
 namespace Sludge {
@@ -63,7 +64,7 @@ extern personaAnimation *mouseCursorAnim;           // In cursor.cpp
 extern int mouseCursorFrameNum;                     // "    "   "
 extern int loadedFontNum, fontHeight, fontTableSize;    // In fonttext.cpp
 extern int numFontColours;                          // "    "   "
-extern char *fontOrderString;                       // "    "   "
+extern UTF8Converter fontOrder;                       // "    "   "
 extern FILETIME fileTime;                           // In sludger.cpp
 extern int speechMode;                              // "    "   "
 extern int lightMapNumber;                          // In backdrop.cpp
@@ -410,7 +411,7 @@ bool saveGame(char *fname) {
 	if (fontTableSize > 0) {
 		fp->writeUint16BE(loadedFontNum);
 		fp->writeUint16BE(fontHeight);
-		writeString(fontOrderString, fp);
+		writeString(fontOrder.getUTF8String(), fp);
 	}
 	putSigned(fontSpace, fp);
 
diff --git a/engines/sludge/moreio.cpp b/engines/sludge/moreio.cpp
index 138f709..0102b31 100644
--- a/engines/sludge/moreio.cpp
+++ b/engines/sludge/moreio.cpp
@@ -40,8 +40,8 @@ namespace Sludge {
 
 bool allowAnyFilename = true;
 
-void writeString(char *s, Common::WriteStream *stream) {
-	int a, len = strlen(s);
+void writeString(Common::String s, Common::WriteStream *stream) {
+	int a, len = s.size();
 	stream->writeUint16BE(len);
 	for (a = 0; a < len; a++) {
 		stream->writeByte(s[a] + 1);
diff --git a/engines/sludge/moreio.h b/engines/sludge/moreio.h
index 5cf01a2..462d005 100644
--- a/engines/sludge/moreio.h
+++ b/engines/sludge/moreio.h
@@ -30,7 +30,7 @@ float getFloat(Common::SeekableReadStream *stream);
 int16 getSigned(Common::SeekableReadStream *stream);
 
 // Write
-void writeString(char *s, Common::WriteStream *stream);
+void writeString(Common::String s, Common::WriteStream *stream);
 void putFloat(float f, Common::WriteStream *stream);
 void putSigned(int16 f, Common::WriteStream *stream);
 
diff --git a/engines/sludge/utf8.h b/engines/sludge/utf8.h
index 4595a6b..26a2542 100644
--- a/engines/sludge/utf8.h
+++ b/engines/sludge/utf8.h
@@ -70,7 +70,12 @@ public:
 	/**
 	 * get converted U32String
 	 */
-	Common::U32String getU32String() { return _str32; };
+	Common::U32String getU32String() const { return _str32; };
+
+	/**
+	 * get origin UTF8String
+	 */
+	Common::String getUTF8String() const { return _str; };
 
 	/** Convert UTF8 String to UTF32 String
 	 */


Commit: d37888ad5f7f3eb7df834e31f4dd11b785f7dc66
    https://github.com/scummvm/scummvm/commit/d37888ad5f7f3eb7df834e31f4dd11b785f7dc66
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: use read/writeSint16LE instead of get/putSigned

Changed paths:
    engines/sludge/loadsave.cpp
    engines/sludge/moreio.cpp
    engines/sludge/moreio.h
    engines/sludge/people.cpp
    engines/sludge/sprites.cpp
    engines/sludge/statusba.cpp


diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index df7bf9b..d1fd187 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -413,7 +413,7 @@ bool saveGame(char *fname) {
 		fp->writeUint16BE(fontHeight);
 		writeString(fontOrder.getUTF8String(), fp);
 	}
-	putSigned(fontSpace, fp);
+	fp->writeSint16LE(fontSpace);
 
 	// Save backdrop
 	fp->writeUint16BE(cameraX);
@@ -595,7 +595,7 @@ bool loadGame(char *fname) {
 	loadFont(fontNum, charOrder, fontHeight);
 	delete []charOrder;
 
-	fontSpace = getSigned(fp);
+	fontSpace = fp->readSint16LE();
 
 	killAllPeople();
 	killAllRegions();
diff --git a/engines/sludge/moreio.cpp b/engines/sludge/moreio.cpp
index 0102b31..874254c 100644
--- a/engines/sludge/moreio.cpp
+++ b/engines/sludge/moreio.cpp
@@ -97,34 +97,6 @@ void putFloat(float f, Common::WriteStream *stream) {
 	stream->write(&f, sizeof(float));
 }
 
-int16 shortSwap(int16 s) {
-	byte b1, b2;
-
-	b1 = s & 255;
-	b2 = (s >> 8) & 255;
-
-	return (b1 << 8) + b2;
-}
-
-int16 getSigned(Common::SeekableReadStream *stream) {
-	int16 f;
-	uint bytes_read = stream->read(&f, sizeof(int16));
-	if (bytes_read != sizeof(int16) && stream->err()) {
-		debug("Reading error in getSigned.\n");
-	}
-#ifdef  __BIG_ENDIAN__
-	f = shortSwap(f);
-#endif
-	return f;
-}
-
-void putSigned(int16 f, Common::WriteStream *stream) {
-#ifdef  __BIG_ENDIAN__
-	f = shortSwap(f);
-#endif
-	stream->write(&f, sizeof(int16));
-}
-
 char *encodeFilename(char *nameIn) {
 	if (!nameIn)
 		return NULL;
diff --git a/engines/sludge/moreio.h b/engines/sludge/moreio.h
index 462d005..b22b76a 100644
--- a/engines/sludge/moreio.h
+++ b/engines/sludge/moreio.h
@@ -27,12 +27,10 @@ namespace Sludge {
 // Read
 char *readString(Common::SeekableReadStream *stream);
 float getFloat(Common::SeekableReadStream *stream);
-int16 getSigned(Common::SeekableReadStream *stream);
 
 // Write
 void writeString(Common::String s, Common::WriteStream *stream);
 void putFloat(float f, Common::WriteStream *stream);
-void putSigned(int16 f, Common::WriteStream *stream);
 
 char *encodeFilename(char *nameIn);
 char *decodeFilename(char *nameIn);
diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index a477fbe..276edf5 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -1049,8 +1049,8 @@ bool savePeople(Common::WriteStream *stream) {
 	onScreenPerson *me = allPeople;
 	int countPeople = 0, a;
 
-	putSigned(scaleHorizon, stream);
-	putSigned(scaleDivide, stream);
+	stream->writeSint16LE(scaleHorizon);
+	stream->writeSint16LE(scaleDivide);
 
 	while (me) {
 		countPeople++;
@@ -1081,7 +1081,7 @@ bool savePeople(Common::WriteStream *stream) {
 		stream->writeUint16BE(me->frameTick);
 		stream->writeUint16BE(me->walkSpeed);
 		stream->writeUint16BE(me->spinSpeed);
-		putSigned(me->floaty, stream);
+		stream->writeSint16LE(me->floaty);
 		stream->writeByte(me->show);
 		stream->writeByte(me->walking);
 		stream->writeByte(me->spinning);
@@ -1095,9 +1095,9 @@ bool savePeople(Common::WriteStream *stream) {
 		stream->writeUint16BE(me->angle);
 		stream->writeUint16BE(me->angleOffset);
 		stream->writeUint16BE(me->wantAngle);
-		putSigned(me->directionWhenDoneWalking, stream);
-		putSigned(me->inPoly, stream);
-		putSigned(me->walkToPoly, stream);
+		stream->writeSint16LE(me->directionWhenDoneWalking);
+		stream->writeSint16LE(me->inPoly);
+		stream->writeSint16LE(me->walkToPoly);
 
 		stream->writeByte(me->r);
 		stream->writeByte(me->g);
@@ -1116,8 +1116,8 @@ bool loadPeople(Common::SeekableReadStream *stream) {
 	onScreenPerson * * pointy = &allPeople;
 	onScreenPerson *me;
 
-	scaleHorizon = getSigned(stream);
-	scaleDivide = getSigned(stream);
+	scaleHorizon = stream->readSint16LE();
+	scaleDivide = stream->readSint16LE();
 
 	int countPeople = stream->readUint16BE();
 	int a;
@@ -1156,7 +1156,7 @@ bool loadPeople(Common::SeekableReadStream *stream) {
 		me->frameTick = stream->readUint16BE();
 		me->walkSpeed = stream->readUint16BE();
 		me->spinSpeed = stream->readUint16BE();
-		me->floaty = getSigned(stream);
+		me->floaty = stream->readSint16LE();
 		me->show = stream->readByte();
 		me->walking = stream->readByte();
 		me->spinning = stream->readByte();
@@ -1175,9 +1175,9 @@ bool loadPeople(Common::SeekableReadStream *stream) {
 			me->angleOffset = 0;
 		}
 		me->wantAngle = stream->readUint16BE();
-		me->directionWhenDoneWalking = getSigned(stream);
-		me->inPoly = getSigned(stream);
-		me->walkToPoly = getSigned(stream);
+		me->directionWhenDoneWalking = stream->readSint16LE();
+		me->inPoly = stream->readSint16LE();
+		me->walkToPoly = stream->readSint16LE();
 		if (ssgVersion >= VERSION(2, 0)) {
 			me->r = stream->readByte();
 			me->g = stream->readByte();
diff --git a/engines/sludge/sprites.cpp b/engines/sludge/sprites.cpp
index bba4ca3..43bc590 100644
--- a/engines/sludge/sprites.cpp
+++ b/engines/sludge/sprites.cpp
@@ -165,8 +165,8 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 	if (spriteBankVersion == 3) {
 		debug(kSludgeDebugGraphics, "png sprite");
 		for (int i = 0; i < total; i++) {
-			loadhere.sprites[i].xhot = getSigned(bigDataFile);
-			loadhere.sprites[i].yhot = getSigned(bigDataFile);
+			loadhere.sprites[i].xhot = bigDataFile->readSint16LE();
+			loadhere.sprites[i].yhot = bigDataFile->readSint16LE();
 			if (!ImgLoader::loadPNGImage(bigDataFile, &loadhere.sprites[i].surface, false)) {
 				return fatal("fail to read png sprite");
 			}
@@ -183,8 +183,8 @@ bool loadSpriteBank(int fileNum, spriteBank &loadhere, bool isFont) {
 		if (spriteBankVersion == 2) {
 			picwidth = bigDataFile->readUint16BE();
 			picheight = bigDataFile->readUint16BE();
-			loadhere.sprites[i].xhot = getSigned(bigDataFile);
-			loadhere.sprites[i].yhot = getSigned(bigDataFile);
+			loadhere.sprites[i].xhot = bigDataFile->readSint16LE();
+			loadhere.sprites[i].yhot = bigDataFile->readSint16LE();
 		} else {
 			picwidth = (byte)bigDataFile->readByte();
 			picheight = (byte)bigDataFile->readByte();
diff --git a/engines/sludge/statusba.cpp b/engines/sludge/statusba.cpp
index 9af0f3f..577e82b 100644
--- a/engines/sludge/statusba.cpp
+++ b/engines/sludge/statusba.cpp
@@ -178,7 +178,7 @@ void saveStatusBars(Common::WriteStream *stream) {
 	statusBar *viewLine = nowStatus->firstStatusBar;
 
 	stream->writeUint16BE(nowStatus->alignStatus);
-	putSigned(nowStatus->litStatus, stream);
+	stream->writeSint16LE(nowStatus->litStatus);
 	stream->writeUint16BE(nowStatus->statusX);
 	stream->writeUint16BE(nowStatus->statusY);
 
@@ -202,7 +202,7 @@ bool loadStatusBars(Common::SeekableReadStream *stream) {
 	clearStatusBar();
 
 	nowStatus->alignStatus = stream->readUint16BE();
-	nowStatus->litStatus = getSigned(stream);
+	nowStatus->litStatus = stream->readSint16LE();
 	nowStatus->statusX = stream->readUint16BE();
 	nowStatus->statusY = stream->readUint16BE();
 


Commit: 8f2a177cef73403ec65cac8430b3a0cae0249d37
    https://github.com/scummvm/scummvm/commit/8f2a177cef73403ec65cac8430b3a0cae0249d37
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
STREAM: add read/write functions for float LE/BE

Changed paths:
    common/stream.h


diff --git a/common/stream.h b/common/stream.h
index 0ff430f..6932c7d 100644
--- a/common/stream.h
+++ b/common/stream.h
@@ -185,6 +185,32 @@ public:
 	}
 #endif
 
+
+	/**
+	 * Write the given 32-bit floating point value stored
+	 * in little endian(LSB first) order into the stream.
+	 */
+	FORCEINLINE void writeFloatLE(float value) {
+		uint32 n;
+
+		memcpy(&n, &value, 4);
+
+		writeUint32LE(n);
+	}
+
+
+	/**
+	 * Write the given 32-bit floating point value stored
+	 * in big endian order into the stream.
+	 */
+	FORCEINLINE void writeFloatBE(float value) {
+		uint32 n;
+
+		memcpy(&n, &value, 4);
+
+		writeUint32BE(n);
+	}
+
 	/**
 	 * Write the given string to the stream.
 	 * This writes str.size() characters, but no terminating zero byte.
@@ -418,6 +444,22 @@ public:
 	}
 
 	/**
+	 * Read a 32-bit floating point value stored in big endian
+	 * order from the stream and return it.
+	 * Performs no error checking. The return value is undefined
+	 * if a read error occurred (for which client code can check by
+	 * calling err() and eos() ).
+	 */
+	FORCEINLINE float readFloatBE() {
+		uint32 n = readUint32BE();
+		float f;
+
+		memcpy(&f, &n, 4);
+
+		return f;
+	}
+
+	/**
 	 * Read the specified amount of data into a malloc'ed buffer
 	 * which then is wrapped into a MemoryReadStream.
 	 * The returned stream might contain less data than requested,


Commit: 38262ad6301953b373e3ef4341c2d1050bcd6981
    https://github.com/scummvm/scummvm/commit/38262ad6301953b373e3ef4341c2d1050bcd6981
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: use write/readFloatLB instead of Sludge get/putFloat

Changed paths:
    engines/sludge/loadsave.cpp
    engines/sludge/moreio.cpp
    engines/sludge/moreio.h
    engines/sludge/objtypes.cpp
    engines/sludge/people.cpp
    engines/sludge/sludger.cpp
    engines/sludge/talk.cpp


diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index d1fd187..e735d60 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -418,7 +418,7 @@ bool saveGame(char *fname) {
 	// Save backdrop
 	fp->writeUint16BE(cameraX);
 	fp->writeUint16BE(cameraY);
-	putFloat(cameraZoom, fp);
+	fp->writeFloatLE(cameraZoom);
 
 	fp->writeByte(brightnessLevel);
 	saveHSI(fp);
@@ -604,7 +604,7 @@ bool loadGame(char *fname) {
 	int camerY = fp->readUint16BE();
 	float camerZ;
 	if (ssgVersion >= VERSION(2, 0)) {
-		camerZ = getFloat(fp);
+		camerZ = fp->readFloatLE();
 	} else {
 		camerZ = 1.0;
 	}
@@ -672,8 +672,8 @@ bool loadGame(char *fname) {
 		if (ssgVersion < VERSION(2, 0)) {
 			// aaLoad
 			fp->readByte();
-			getFloat(fp);
-			getFloat(fp);
+			fp->readFloatLE();
+			fp->readFloatLE();
 		}
 
 		blur_loadSettings(fp);
diff --git a/engines/sludge/moreio.cpp b/engines/sludge/moreio.cpp
index 874254c..6635c3d 100644
--- a/engines/sludge/moreio.cpp
+++ b/engines/sludge/moreio.cpp
@@ -29,13 +29,6 @@
 #include "sludge/stringy.h"
 #include "sludge/sludge.h"
 
-#if defined __unix__ && !(defined __APPLE__)
-#include <endian.h>
-#if __BYTE_ORDER == __BIG_ENDIAN
-#define __BIG_ENDIAN__
-#endif
-#endif
-
 namespace Sludge {
 
 bool allowAnyFilename = true;
@@ -62,41 +55,6 @@ char *readString(Common::SeekableReadStream *stream) {
 	return s;
 }
 
-float floatSwap(float f) {
-	union {
-		float f;
-		byte b[4];
-	} dat1, dat2;
-
-	dat1.f = f;
-	dat2.b[0] = dat1.b[3];
-	dat2.b[1] = dat1.b[2];
-	dat2.b[2] = dat1.b[1];
-	dat2.b[3] = dat1.b[0];
-	return dat2.f;
-}
-
-float getFloat(Common::SeekableReadStream *stream) {
-	float f;
-	uint bytes_read = stream->read(&f, sizeof(float));
-	if (bytes_read != sizeof(float) && stream->err()) {
-		debug("Reading error in getFloat.\n");
-	}
-
-#ifdef  __BIG_ENDIAN__
-	return floatSwap(f);
-#else
-	return f;
-#endif
-}
-
-void putFloat(float f, Common::WriteStream *stream) {
-#ifdef  __BIG_ENDIAN__
-	f = floatSwap(f);
-#endif
-	stream->write(&f, sizeof(float));
-}
-
 char *encodeFilename(char *nameIn) {
 	if (!nameIn)
 		return NULL;
diff --git a/engines/sludge/moreio.h b/engines/sludge/moreio.h
index b22b76a..94c82f2 100644
--- a/engines/sludge/moreio.h
+++ b/engines/sludge/moreio.h
@@ -24,13 +24,9 @@
 
 namespace Sludge {
 
-// Read
+// Read & Write
 char *readString(Common::SeekableReadStream *stream);
-float getFloat(Common::SeekableReadStream *stream);
-
-// Write
 void writeString(Common::String s, Common::WriteStream *stream);
-void putFloat(float f, Common::WriteStream *stream);
 
 char *encodeFilename(char *nameIn);
 char *decodeFilename(char *nameIn);
diff --git a/engines/sludge/objtypes.cpp b/engines/sludge/objtypes.cpp
index 8b660fc..ebb9056 100644
--- a/engines/sludge/objtypes.cpp
+++ b/engines/sludge/objtypes.cpp
@@ -69,8 +69,8 @@ objectType *loadObjectType(int i) {
 			if (gameVersion >= VERSION(1, 6)) {
 				// aaLoad
 				bigDataFile->readByte();
-				getFloat(bigDataFile);
-				getFloat(bigDataFile);
+				bigDataFile->readFloatLE();
+				bigDataFile->readFloatLE();
 			}
 
 			if (gameVersion >= VERSION(1, 4)) {
diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index 276edf5..dca541b 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -1062,14 +1062,14 @@ bool savePeople(Common::WriteStream *stream) {
 	me = allPeople;
 	for (a = 0; a < countPeople; a++) {
 
-		putFloat(me->x, stream);
-		putFloat(me->y, stream);
+		stream->writeFloatLE(me->x);
+		stream->writeFloatLE(me->y);
 
 		saveCostume(me->myPersona, stream);
 		saveAnim(me->myAnim, stream);
 		stream->writeByte(me->myAnim == me->lastUsedAnim);
 
-		putFloat(me->scale, stream);
+		stream->writeFloatLE(me->scale);
 
 		stream->writeUint16BE(me->extra);
 		stream->writeUint16BE(me->height);
@@ -1136,15 +1136,15 @@ bool loadPeople(Common::SeekableReadStream *stream) {
 		if (!checkNew(me->myAnim))
 			return false;
 
-		me->x = getFloat(stream);
-		me->y = getFloat(stream);
+		me->x = stream->readFloatLE();
+		me->y = stream->readFloatLE();
 
 		loadCostume(me->myPersona, stream);
 		loadAnim(me->myAnim, stream);
 
 		me->lastUsedAnim = stream->readByte() ? me->myAnim : NULL;
 
-		me->scale = getFloat(stream);
+		me->scale = stream->readFloatLE();
 
 		me->extra = stream->readUint16BE();
 		me->height = stream->readUint16BE();
@@ -1194,8 +1194,8 @@ bool loadPeople(Common::SeekableReadStream *stream) {
 			if (ssgVersion < VERSION(2, 0)) {
 				// aaLoad
 				stream->readByte();
-				getFloat(stream);
-				getFloat(stream);
+				stream->readFloatLE();
+				stream->readFloatLE();
 			}
 		}
 
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index 22e1926..a4ae34d 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -256,8 +256,8 @@ bool initSludge(const char *filename) {
 		fp->readByte();
 		// aaLoad
 		fp->readByte();
-		getFloat(fp);
-		getFloat(fp);
+		fp->readFloatLE();
+		fp->readFloatLE();
 	}
 
 	char *checker = readString(fp);
diff --git a/engines/sludge/talk.cpp b/engines/sludge/talk.cpp
index 8f3dd02..12f6d8e 100644
--- a/engines/sludge/talk.cpp
+++ b/engines/sludge/talk.cpp
@@ -216,7 +216,7 @@ void saveSpeech(speechStruct *sS, Common::WriteStream *stream) {
 	stream->writeByte(sS->talkCol.originalGreen);
 	stream->writeByte(sS->talkCol.originalBlue);
 
-	putFloat(speechSpeed, stream);
+	stream->writeFloatLE(speechSpeed);
 
 	// Write y co-ordinate
 	stream->writeUint16BE(sS->speechY);
@@ -248,7 +248,7 @@ bool loadSpeech(speechStruct *sS, Common::SeekableReadStream *stream) {
 	byte b = stream->readByte();
 	setFontColour(sS->talkCol, r, g, b);
 
-	speechSpeed = getFloat(stream);
+	speechSpeed = stream->readFloatLE();
 
 	// Read y co-ordinate
 	sS->speechY = stream->readUint16BE();


Commit: 9d349e794e272b6e7d8fe1655b7cc3bfa2253efb
    https://github.com/scummvm/scummvm/commit/9d349e794e272b6e7d8fe1655b7cc3bfa2253efb
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: code formatting for **

Changed paths:
    engines/sludge/bg_effects.cpp
    engines/sludge/builtin.cpp
    engines/sludge/floor.cpp
    engines/sludge/floor.h
    engines/sludge/loadsave.cpp
    engines/sludge/newfatal.cpp
    engines/sludge/objtypes.cpp
    engines/sludge/people.cpp
    engines/sludge/people.h
    engines/sludge/region.cpp
    engines/sludge/sludger.cpp
    engines/sludge/statusba.cpp
    engines/sludge/talk.cpp
    engines/sludge/variable.cpp


diff --git a/engines/sludge/bg_effects.cpp b/engines/sludge/bg_effects.cpp
index 916c8e3..40f60e3 100644
--- a/engines/sludge/bg_effects.cpp
+++ b/engines/sludge/bg_effects.cpp
@@ -32,7 +32,7 @@
 namespace Sludge {
 
 #if 0
-//extern uint16 * * backDropImage;
+//extern uint16 **backDropImage;
 extern GLuint backdropTextureName;
 #endif
 
@@ -333,9 +333,9 @@ bool blurScreen() {
 						byte *pixel = &sourceLine[miniY][x * 4];
 						for (int miniX = 0; miniX < s_matrixEffectWidth; ++miniX) {
 
-							totalRed += pixel[0] * *matrixElement;
-							totalGreen += pixel[1] * *matrixElement;
-							totalBlue += pixel[2] * *matrixElement;
+							totalRed += pixel[0] **matrixElement;
+							totalGreen += pixel[1] **matrixElement;
+							totalBlue += pixel[2] **matrixElement;
 							++matrixElement;
 							pixel += 4;
 						}
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 1226b1a..3a79590 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -76,8 +76,8 @@ extern uint sceneWidth, sceneHeight;
 extern int numBIFNames, numUserFunc;
 extern char builtInFunctionNames[][25];
 
-extern char * *allUserFunc;
-extern char * *allBIFNames;
+extern char **allUserFunc;
+extern char **allBIFNames;
 extern inputType input;
 extern char *loadNow;
 
diff --git a/engines/sludge/floor.cpp b/engines/sludge/floor.cpp
index 15da333..591a5ff 100644
--- a/engines/sludge/floor.cpp
+++ b/engines/sludge/floor.cpp
@@ -174,7 +174,7 @@ bool setFloor(int fileNum) {
 	// Now build the movement martix
 
 	currentFloor->matrix = new int *[currentFloor->numPolygons];
-	int * * distanceMatrix = new int *[currentFloor->numPolygons];
+	int **distanceMatrix = new int *[currentFloor->numPolygons];
 
 	if (!checkNew(currentFloor->matrix))
 		return false;
diff --git a/engines/sludge/floor.h b/engines/sludge/floor.h
index b1de826..c543c3f 100644
--- a/engines/sludge/floor.h
+++ b/engines/sludge/floor.h
@@ -36,7 +36,7 @@ struct flor {
 	Common::Point *vertex;
 	int numPolygons;
 	floorPolygon *polygon;
-	int * *matrix;
+	int **matrix;
 };
 
 bool initFloor();
diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index e735d60..893d2a8 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -122,7 +122,7 @@ variableStack *loadStack(Common::SeekableReadStream *stream, variableStack **las
 	int elements = stream->readUint16BE();
 	int a;
 	variableStack *first = NULL;
-	variableStack * * changeMe = &first;
+	variableStack **changeMe = &first;
 
 	for (a = 0; a < elements; a++) {
 		variableStack *nS = new variableStack;
diff --git a/engines/sludge/newfatal.cpp b/engines/sludge/newfatal.cpp
index d0e5184..5223400 100644
--- a/engines/sludge/newfatal.cpp
+++ b/engines/sludge/newfatal.cpp
@@ -38,7 +38,7 @@ static Common::String fatalMessage;
 static Common::String fatalInfo = "Initialisation error! Something went wrong before we even got started!";
 
 extern int numResourceNames /* = 0*/;
-extern char * *allResourceNames /*= NULL*/;
+extern char **allResourceNames /*= NULL*/;
 
 int resourceForFatal = -1;
 
diff --git a/engines/sludge/objtypes.cpp b/engines/sludge/objtypes.cpp
index ebb9056..ddb7553 100644
--- a/engines/sludge/objtypes.cpp
+++ b/engines/sludge/objtypes.cpp
@@ -157,7 +157,7 @@ int getCombinationFunction(int withThis, int thisObject) {
 }
 
 void removeObjectType(objectType *oT) {
-	objectType * * huntRegion = &allObjectTypes;
+	objectType **huntRegion = &allObjectTypes;
 
 	while (*huntRegion) {
 		if ((*huntRegion) == oT) {
diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index dca541b..1fd6931 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -415,7 +415,7 @@ void setPersonColourise(int ob, byte r, byte g, byte b, byte colourmix) {
 extern screenRegion *overRegion;
 
 void shufflePeople() {
-	onScreenPerson * * thisReference = &allPeople;
+	onScreenPerson **thisReference = &allPeople;
 	onScreenPerson *A, *B;
 
 	if (!allPeople)
@@ -855,7 +855,7 @@ bool addPerson(int x, int y, int objNum, persona *p) {
 	}
 
 	// NOW ADD IT IN THE RIGHT PLACE
-	onScreenPerson * * changethat = &allPeople;
+	onScreenPerson **changethat = &allPeople;
 
 	while (((*changethat) != NULL) && ((*changethat)->y < y))
 		changethat = &((*changethat)->next);
@@ -918,7 +918,7 @@ void killAllPeople() {
 
 void killMostPeople() {
 	onScreenPerson *killPeople;
-	onScreenPerson * * lookyHere = &allPeople;
+	onScreenPerson **lookyHere = &allPeople;
 
 	while (*lookyHere) {
 		if ((*lookyHere)->extra & EXTRA_NOREMOVE) {
@@ -950,7 +950,7 @@ void removeOneCharacter(int i) {
 		if (p->continueAfterWalking)
 			abortFunction(p->continueAfterWalking);
 		p->continueAfterWalking = NULL;
-		onScreenPerson * * killPeople;
+		onScreenPerson **killPeople;
 
 		for (killPeople = &allPeople; *killPeople != p; killPeople = &((*killPeople)->next)) {
 			;
@@ -1113,7 +1113,7 @@ bool savePeople(Common::WriteStream *stream) {
 }
 
 bool loadPeople(Common::SeekableReadStream *stream) {
-	onScreenPerson * * pointy = &allPeople;
+	onScreenPerson **pointy = &allPeople;
 	onScreenPerson *me;
 
 	scaleHorizon = stream->readSint16LE();
diff --git a/engines/sludge/people.h b/engines/sludge/people.h
index b02bc1c..eb19e4f 100644
--- a/engines/sludge/people.h
+++ b/engines/sludge/people.h
@@ -47,7 +47,7 @@ struct personaAnimation {
 };
 
 struct persona {
-	personaAnimation * *animation;
+	personaAnimation **animation;
 	int numDirections;
 };
 
diff --git a/engines/sludge/region.cpp b/engines/sludge/region.cpp
index c6fa06e..e43cd57 100644
--- a/engines/sludge/region.cpp
+++ b/engines/sludge/region.cpp
@@ -48,7 +48,7 @@ void showBoxes() {
 }
 
 void removeScreenRegion(int objectNum) {
-	screenRegion ** huntRegion = &allScreenRegions;
+	screenRegion **huntRegion = &allScreenRegions;
 	screenRegion *killMe;
 
 	while (*huntRegion) {
@@ -93,7 +93,7 @@ void loadRegions(Common::SeekableReadStream *stream) {
 	int numRegions = stream->readUint16BE();
 
 	screenRegion *newRegion;
-	screenRegion * * pointy = &allScreenRegions;
+	screenRegion **pointy = &allScreenRegions;
 
 	while (numRegions--) {
 		newRegion = new screenRegion;
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index a4ae34d..5c5e6c6 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -65,11 +65,11 @@ extern bool reallyWantToQuit;
 extern Graphics::Surface renderSurface;
 
 int numBIFNames = 0;
-char * *allBIFNames = NULL;
+char **allBIFNames = NULL;
 int numUserFunc = 0;
-char * *allUserFunc = NULL;
+char **allUserFunc = NULL;
 int numResourceNames = 0;
-char * *allResourceNames = NULL;
+char **allResourceNames = NULL;
 int selectedLanguage = 0;
 int languageNum = -1;
 
@@ -585,7 +585,7 @@ void sludgeDisplay() {
 }
 
 void pauseFunction(loadedFunction *fun) {
-	loadedFunction * * huntAndDestroy = &allRunningFunctions;
+	loadedFunction **huntAndDestroy = &allRunningFunctions;
 	while (*huntAndDestroy) {
 		if (fun == *huntAndDestroy) {
 			(*huntAndDestroy) = (*huntAndDestroy)->next;
diff --git a/engines/sludge/statusba.cpp b/engines/sludge/statusba.cpp
index 577e82b..2f1eb6f 100644
--- a/engines/sludge/statusba.cpp
+++ b/engines/sludge/statusba.cpp
@@ -216,7 +216,7 @@ bool loadStatusBars(Common::SeekableReadStream *stream) {
 	setFontColour(verbLinePalette, nowStatus->statusR, nowStatus->statusG, nowStatus->statusB);
 	setFontColour(litVerbLinePalette, nowStatus->statusLR, nowStatus->statusLG, nowStatus->statusLB);
 	// Read what's being said
-	statusBar * * viewLine = & (nowStatus->firstStatusBar);
+	statusBar **viewLine = & (nowStatus->firstStatusBar);
 	statusBar *newOne;
 	while (stream->readByte()) {
 		newOne = new statusBar;
diff --git a/engines/sludge/talk.cpp b/engines/sludge/talk.cpp
index 12f6d8e..d72db2c 100644
--- a/engines/sludge/talk.cpp
+++ b/engines/sludge/talk.cpp
@@ -263,7 +263,7 @@ bool loadSpeech(speechStruct *sS, Common::SeekableReadStream *stream) {
 	}
 
 	// Read what's being said
-	speechLine * * viewLine = &sS->allSpeech;
+	speechLine **viewLine = &sS->allSpeech;
 	speechLine *newOne;
 	speech->lastFile = -1;
 	while (stream->readByte()) {
diff --git a/engines/sludge/variable.cpp b/engines/sludge/variable.cpp
index 30686e4..eee9d07 100644
--- a/engines/sludge/variable.cpp
+++ b/engines/sludge/variable.cpp
@@ -555,7 +555,7 @@ variable *stackGetByIndex(variableStack *vS, uint theIndex) {
 }
 
 int deleteVarFromStack(const variable &va, variableStack *&thisStack, bool allOfEm) {
-	variableStack * * huntVar = &thisStack;
+	variableStack **huntVar = &thisStack;
 	variableStack *killMe;
 	int reply = 0;
 


Commit: ae8df00f56521841ba438f28c84bf1e2a7a4a1bd
    https://github.com/scummvm/scummvm/commit/ae8df00f56521841ba438f28c84bf1e2a7a4a1bd
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: replace abs() by scummvm ABS()

Changed paths:
    engines/sludge/backdrop.cpp
    engines/sludge/builtin.cpp
    engines/sludge/line.cpp
    engines/sludge/movie.cpp
    engines/sludge/people.cpp


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index bda9f55..aada7f1 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -399,7 +399,7 @@ void blankScreen(int x1, int y1, int x2, int y2) {
 }
 
 void hardScroll(int distance) {
-	if (abs(distance) >= sceneHeight) {
+	if (ABS(distance) >= sceneHeight) {
 		blankScreen(0, 0, sceneWidth, sceneHeight);
 		return;
 	}
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 3a79590..123841c 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -1667,7 +1667,7 @@ builtIn(pasteCharacter) {
 		}
 
 		int fNum = myAnim->frames[thisPerson->frameNum].frameNum;
-		fixScaleSprite(thisPerson->x, thisPerson->y, myAnim->theSprites->bank.sprites[abs(fNum)], myAnim->theSprites->bank.myPalette, thisPerson, 0, 0, fNum < 0);
+		fixScaleSprite(thisPerson->x, thisPerson->y, myAnim->theSprites->bank.sprites[ABS(fNum)], myAnim->theSprites->bank.myPalette, thisPerson, 0, 0, fNum < 0);
 		setVariable(fun->reg, SVT_INT, 1);
 	} else {
 		setVariable(fun->reg, SVT_INT, 0);
diff --git a/engines/sludge/line.cpp b/engines/sludge/line.cpp
index 2262d92..58fd64a 100644
--- a/engines/sludge/line.cpp
+++ b/engines/sludge/line.cpp
@@ -63,8 +63,8 @@ void drawLine(int x1, int y1, int x2, int y2) {
 	} else
 		y = y1;
 
-	int diffX = abs(x2 - x1);
-	int diffY = abs(y2 - y1);
+	int diffX = ABS(x2 - x1);
+	int diffY = ABS(y2 - y1);
 
 	if (!diffX) {
 		diffX = 1;
diff --git a/engines/sludge/movie.cpp b/engines/sludge/movie.cpp
index da6eb7f..06defc4 100644
--- a/engines/sludge/movie.cpp
+++ b/engines/sludge/movie.cpp
@@ -155,7 +155,7 @@ inline static int audio_queue_get(audioQueue *q, char **buffer) {
 	if (audioBuf) {
 		// Synch video timer to audio
 		Uint32 tick = SDL_GetTicks() + 100;
-		if (abs((long int)((tick - movieStartTick) - (audioBuf->time_ms))) > 300) {
+		if (ABS((long int)((tick - movieStartTick) - (audioBuf->time_ms))) > 300) {
 			movieStartTick = tick - audioBuf->time_ms;
 		}
 
diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index 1fd6931..94663ee 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -471,7 +471,7 @@ void drawPeople() {
 			}
 			int fNumSign = myAnim->frames[thisPerson->frameNum].frameNum;
 			int m = fNumSign < 0;
-			int fNum = abs(fNumSign);
+			int fNum = ABS(fNumSign);
 			if (fNum >= myAnim->theSprites->bank.total) {
 				fNum = 0;
 				m = 2 - m;
@@ -643,9 +643,9 @@ bool walkMe(onScreenPerson *thisPerson, bool move = true) {
 		if (s < 0.2)
 			s = 0.2;
 
-		maxDiff = (abs(xDiff) >= abs(yDiff)) ? abs(xDiff) : abs(yDiff);
+		maxDiff = (ABS(xDiff) >= ABS(yDiff)) ? ABS(xDiff) : ABS(yDiff);
 
-		if (abs(maxDiff) > s) {
+		if (ABS(maxDiff) > s) {
 			if (thisPerson->spinning) {
 				spinStep(thisPerson);
 				setFrames(*thisPerson, ANI_WALK);


Commit: 59ea5e5834d107d98101fb016686f0a4e8f30218
    https://github.com/scummvm/scummvm/commit/59ea5e5834d107d98101fb016686f0a4e8f30218
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: use Graphics::Surface::drawLine instead of sludge defined drawLine

Changed paths:
  R engines/sludge/line.cpp
  R engines/sludge/line.h
    engines/sludge/backdrop.cpp
    engines/sludge/floor.cpp
    engines/sludge/module.mk


diff --git a/engines/sludge/backdrop.cpp b/engines/sludge/backdrop.cpp
index aada7f1..82260b9 100644
--- a/engines/sludge/backdrop.cpp
+++ b/engines/sludge/backdrop.cpp
@@ -34,7 +34,6 @@
 #include "sludge/moreio.h"
 #include "sludge/zbuffer.h"
 #include "sludge/graphics.h"
-#include "sludge/line.h"
 #include "sludge/sludge.h"
 #include "sludge/sludger.h"
 #include "sludge/variable.h"
@@ -458,11 +457,11 @@ void hardScroll(int distance) {
 }
 
 void drawVerticalLine(uint x, uint y1, uint y2) {
-	drawLine(x, y1, x, y2);
+	backdropSurface.drawLine(x, y1, x, y2, backdropSurface.format.ARGBToColor(255, 0, 0, 0));
 }
 
 void drawHorizontalLine(uint x1, uint y, uint x2) {
-	drawLine(x1, y, x2, y);
+	backdropSurface.drawLine(x1, y, x2, y, backdropSurface.format.ARGBToColor(255, 0, 0, 0));
 }
 
 void darkScreen() {
diff --git a/engines/sludge/floor.cpp b/engines/sludge/floor.cpp
index 591a5ff..7e9677a 100644
--- a/engines/sludge/floor.cpp
+++ b/engines/sludge/floor.cpp
@@ -20,15 +20,18 @@
  *
  */
 
+#include "graphics/surface.h"
+
 #include "sludge/allfiles.h"
 #include "sludge/newfatal.h"
 #include "sludge/fileset.h"
 #include "sludge/moreio.h"
 #include "sludge/floor.h"
-#include "sludge/line.h"
 
 namespace Sludge {
 
+extern Graphics::Surface backdropSurface;
+
 flor *currentFloor = NULL;
 
 bool pointInFloorPolygon(floorPolygon &floorPoly, int x, int y) {
@@ -245,15 +248,16 @@ bool setFloor(int fileNum) {
 void drawFloor() {
 	int i, j, nV;
 	for (i = 0; i < currentFloor->numPolygons; i++) {
-//		drawLine (i, 0, i + 5, 100);
 		nV = currentFloor->polygon[i].numVertices;
 		if (nV > 1) {
 			for (j = 1; j < nV; j++) {
-				drawLine(currentFloor->vertex[currentFloor->polygon[i].vertexID[j - 1]].x, currentFloor->vertex[currentFloor->polygon[i].vertexID[j - 1]].y,
-						currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].x, currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].y);
+				backdropSurface.drawLine(currentFloor->vertex[currentFloor->polygon[i].vertexID[j - 1]].x, currentFloor->vertex[currentFloor->polygon[i].vertexID[j - 1]].y,
+						currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].x, currentFloor->vertex[currentFloor->polygon[i].vertexID[j]].y,
+						backdropSurface.format.ARGBToColor(255, 0, 0, 0));
 			}
-			drawLine(currentFloor->vertex[currentFloor->polygon[i].vertexID[0]].x, currentFloor->vertex[currentFloor->polygon[i].vertexID[0]].y,
-					currentFloor->vertex[currentFloor->polygon[i].vertexID[nV - 1]].x, currentFloor->vertex[currentFloor->polygon[i].vertexID[nV - 1]].y);
+			backdropSurface.drawLine(currentFloor->vertex[currentFloor->polygon[i].vertexID[0]].x, currentFloor->vertex[currentFloor->polygon[i].vertexID[0]].y,
+					currentFloor->vertex[currentFloor->polygon[i].vertexID[nV - 1]].x, currentFloor->vertex[currentFloor->polygon[i].vertexID[nV - 1]].y,
+					backdropSurface.format.ARGBToColor(255, 0, 0, 0));
 		}
 	}
 }
diff --git a/engines/sludge/line.cpp b/engines/sludge/line.cpp
deleted file mode 100644
index 58fd64a..0000000
--- a/engines/sludge/line.cpp
+++ /dev/null
@@ -1,140 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-
-#include "sludge/graphics.h"
-#include "sludge/allfiles.h"
-
-namespace Sludge {
-
-extern int sceneWidth, sceneHeight;
-#if 0
-extern GLuint backdropTextureName;
-#endif
-
-void drawLine(int x1, int y1, int x2, int y2) {
-	int x, y;
-	bool backwards = false;
-#if 0
-	if (x1 < 0)
-		x1 = 0;
-	if (y1 < 0)
-		y1 = 0;
-	if (x2 < 0)
-		x2 = 0;
-	if (y2 < 0)
-		y2 = 0;
-	if (x1 > sceneWidth)
-		x1 = sceneWidth - 1;
-	if (x2 > sceneWidth)
-		x2 = sceneWidth - 1;
-	if (y1 > sceneHeight)
-		y1 = sceneHeight - 1;
-	if (y2 > sceneHeight)
-		y2 = sceneHeight - 1;
-
-	if (x1 > x2) {
-		x = x2;
-		backwards = !backwards;
-	} else
-		x = x1;
-
-	if (y1 > y2) {
-		y = y2;
-		backwards = !backwards;
-	} else
-		y = y1;
-
-	int diffX = ABS(x2 - x1);
-	int diffY = ABS(y2 - y1);
-
-	if (!diffX) {
-		diffX = 1;
-		if (x == sceneWidth - 1)
-			x = sceneWidth - 2;
-	}
-	if (!diffY) {
-		diffY = 1;
-		if (y == sceneHeight - 1)
-			y = sceneHeight - 2;
-	}
-	setPixelCoords(true);
-
-	glLineWidth(2.0);
-
-	int xoffset = 0;
-	while (xoffset < diffX) {
-		int w = (diffX - xoffset < viewportWidth) ? diffX - xoffset : viewportWidth;
-
-		int yoffset = 0;
-		while (yoffset < diffY) {
-			int h = (diffY - yoffset < viewportHeight) ? diffY - yoffset : viewportHeight;
-
-			// Render the scene - first the old backdrop
-			glBindTexture(GL_TEXTURE_2D, backdropTextureName);
-			//glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
-			const GLfloat vertices[] = { (GLfloat)-x - xoffset, (GLfloat)1 - y - yoffset, 0., (GLfloat)sceneWidth - x - xoffset, (GLfloat)1 - y - yoffset, 0., (GLfloat)-x - xoffset,
-					(GLfloat)sceneHeight - y - yoffset, 0., (GLfloat)sceneWidth - x - xoffset, (GLfloat)sceneHeight - y - yoffset, 0. };
-
-			const GLfloat texCoords[] = { 0.0f, 0.0f, backdropTexW, 0.0f, 0.0f, backdropTexH, backdropTexW, backdropTexH };
-
-			glUseProgram(shader.texture);
-
-			setPMVMatrix(shader.texture);
-			drawQuad(shader.texture, vertices, 1, texCoords);
-
-			// Then the line
-			//FIXME:Removing the lines doesn't work, but also didn't work properly before.
-
-			GLint xo1 = -xoffset, xo2 = -xoffset;
-			if (!backwards) {
-				xo2 += diffX;
-			} else {
-				xo1 += diffX;
-			}
-			const GLint lineVertices[] = { xo1, -yoffset, 0, xo2, -yoffset + diffY, 0, };
-
-			glUseProgram(shader.color);
-
-			setPMVMatrix(shader.color);
-
-			glUniform4f(glGetUniformLocation(shader.color, "myColor"), 0.0f, 0.0f, 0.0f, 1.0f);
-
-			int vertexLoc = glGetAttribLocation(shader.color, "myVertex");
-			glEnableVertexAttribArray(vertexLoc);
-			glVertexAttribPointer(vertexLoc, 3, GL_INT, GL_FALSE, 0, lineVertices);
-			glDrawArrays(GL_LINES, 0, 2);
-			glDisableVertexAttribArray(vertexLoc);
-
-			glUseProgram(0);
-
-			// Copy Our ViewPort To The Texture
-			copyTexSubImage2D(GL_TEXTURE_2D, 0, x + xoffset, y + yoffset, viewportOffsetX, viewportOffsetY, w, h, backdropTextureName);
-
-			yoffset += viewportHeight;
-		}
-		xoffset += viewportWidth;
-	}
-	setPixelCoords(false);
-#endif
-}
-
-} // End of namespace Sludge
diff --git a/engines/sludge/line.h b/engines/sludge/line.h
deleted file mode 100644
index 49e895f..0000000
--- a/engines/sludge/line.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-#ifndef SLUDGE_LINE_H
-#define SLUDGE_LINE_H
-
-namespace Sludge {
-
-void drawLine(int x1, int y1, int x2, int y2);
-
-} // End of namespace Sludge
-
-#endif
diff --git a/engines/sludge/module.mk b/engines/sludge/module.mk
index ac5529f..03bcc72 100644
--- a/engines/sludge/module.mk
+++ b/engines/sludge/module.mk
@@ -16,7 +16,6 @@ MODULE_OBJS := \
 	hsi.o \
 	imgloader.o \
 	language.o \
-	line.o \
 	loadsave.o \
 	main_loop.o \
 	memwatch.o \


Commit: 19ff9f419baae348b153c45c2857a7cccb33f725
    https://github.com/scummvm/scummvm/commit/19ff9f419baae348b153c45c2857a7cccb33f725
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: correct loadfile existence check

Changed paths:
    engines/sludge/builtin.cpp


diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 123841c..225c2f1 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -20,6 +20,8 @@
  *
  */
 
+#include "common/savefile.h"
+
 #include "sludge/allfiles.h"
 #include "sludge/sludger.h"
 #include "sludge/builtin.h"
@@ -356,6 +358,9 @@ builtIn(loadGame) {
 	Common::File fd;
 	if (fd.open(loadNow)) {
 		fd.close();
+	Common::InSaveFile *fp = g_system->getSavefileManager()->openForLoading(loadNow);
+	if (fp) {
+		delete fp;
 		return BR_KEEP_AND_PAUSE;
 	}
 	delete []loadNow;


Commit: 800987ab95c4faa5532d735a85516fd09f5de724
    https://github.com/scummvm/scummvm/commit/800987ab95c4faa5532d735a85516fd09f5de724
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: replace char *by Common::String

Changed paths:
  R engines/sludge/stringy.cpp
  R engines/sludge/stringy.h
    engines/sludge/bg_effects.cpp
    engines/sludge/builtin.cpp
    engines/sludge/builtin.h
    engines/sludge/fileset.cpp
    engines/sludge/fileset.h
    engines/sludge/fonttext.cpp
    engines/sludge/fonttext.h
    engines/sludge/graphics.cpp
    engines/sludge/language.cpp
    engines/sludge/language.h
    engines/sludge/loadsave.cpp
    engines/sludge/loadsave.h
    engines/sludge/main_loop.cpp
    engines/sludge/module.mk
    engines/sludge/moreio.cpp
    engines/sludge/moreio.h
    engines/sludge/newfatal.cpp
    engines/sludge/newfatal.h
    engines/sludge/objtypes.cpp
    engines/sludge/objtypes.h
    engines/sludge/people.cpp
    engines/sludge/savedata.cpp
    engines/sludge/savedata.h
    engines/sludge/sludger.cpp
    engines/sludge/sludger.h
    engines/sludge/statusba.cpp
    engines/sludge/statusba.h
    engines/sludge/talk.cpp
    engines/sludge/talk.h
    engines/sludge/thumbnail.cpp
    engines/sludge/thumbnail.h
    engines/sludge/variable.cpp
    engines/sludge/variable.h


diff --git a/engines/sludge/bg_effects.cpp b/engines/sludge/bg_effects.cpp
index 40f60e3..0ec538d 100644
--- a/engines/sludge/bg_effects.cpp
+++ b/engines/sludge/bg_effects.cpp
@@ -158,7 +158,7 @@ void blur_loadSettings(Common::SeekableReadStream *stream) {
 
 bool blur_createSettings(int numParams, variableStack *&stack) {
 	bool createNullThing = true;
-	const char *error = NULL;
+	Common::String error = "";
 
 	if (numParams >= 3) {
 		// PARAMETERS: base, divide, stack (, stack (, stack...))
@@ -187,18 +187,18 @@ bool blur_createSettings(int numParams, variableStack *&stack) {
 			}
 		}
 
-		if (width == 0 && !error) {
+		if (width == 0 && error.empty()) {
 			error = "Empty arrays found in setBackgroundEffect parameters";
 		}
 
-		if (!error) {
+		if (error.empty()) {
 			s_matrixEffectWidth = width;
 			s_matrixEffectHeight = height;
 
 			if (blur_allocateMemoryForEffect()) {
 				for (int y = height - 1; y >= 0; y--) {
 					variableStack *eachNumber = stack->thisVar.varData.theStack->first;
-					if (!error) {
+					if (error.empty()) {
 						for (int x = 0; x < width; x++) {
 							int arraySlot = x + (y * width);
 //							s_matrixEffectData[arraySlot] = (rand() % 4);
@@ -211,13 +211,13 @@ bool blur_createSettings(int numParams, variableStack *&stack) {
 						trimStack(stack);
 					}
 				}
-				if (!error && !getValueType(s_matrixEffectDivide, SVT_INT, stack->thisVar))
+				if (error.empty() && !getValueType(s_matrixEffectDivide, SVT_INT, stack->thisVar))
 					error = "";
 				trimStack(stack);
-				if (!error && !getValueType(s_matrixEffectBase, SVT_INT, stack->thisVar))
+				if (error.empty() && !getValueType(s_matrixEffectBase, SVT_INT, stack->thisVar))
 					error = "";
 				trimStack(stack);
-				if (!error) {
+				if (error.empty()) {
 					if (s_matrixEffectDivide) {
 						createNullThing = false;
 					} else {
@@ -243,7 +243,7 @@ bool blur_createSettings(int numParams, variableStack *&stack) {
 		s_matrixEffectData = NULL;
 	}
 
-	if (error && error[0]) {
+	if (!error.empty()) {
 		fatal(error);
 	}
 
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 225c2f1..6d7ee42 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -25,7 +25,6 @@
 #include "sludge/allfiles.h"
 #include "sludge/sludger.h"
 #include "sludge/builtin.h"
-#include "sludge/stringy.h"
 #include "sludge/newfatal.h"
 #include "sludge/cursors.h"
 #include "sludge/statusba.h"
@@ -55,14 +54,14 @@
 
 namespace Sludge {
 
-extern char *gamePath;
+extern Common::String gamePath;
 
 int speechMode = 0;
 int cameraX, cameraY;
 float cameraZoom = 1.0;
 spritePalette pastePalette;
 
-char *launchMe = NULL;
+Common::String launchMe = NULL;
 variable *launchResult = NULL;
 
 extern int lastFramesPerSecond, thumbWidth, thumbHeight;
@@ -78,10 +77,10 @@ extern uint sceneWidth, sceneHeight;
 extern int numBIFNames, numUserFunc;
 extern char builtInFunctionNames[][25];
 
-extern char **allUserFunc;
-extern char **allBIFNames;
+extern Common::String *allUserFunc;
+extern Common::String *allBIFNames;
 extern inputType input;
-extern char *loadNow;
+extern Common::String loadNow;
 
 #if 0
 extern GLuint backdropTextureName;
@@ -121,14 +120,12 @@ int paramNum[] = { -1, 0, 1, 1, -1, -1, 1, 3, 4, 1, 0, 0, 8, -1,    // SAY->MOVE
                    1, 0, 0                                     // playMovie, stopMovie, pauseMovie
                  };
 
-bool failSecurityCheck(char *fn) {
-	if (fn == NULL)
+bool failSecurityCheck(const Common::String &fn) {
+	if (fn.empty())
 		return true;
 
-	int a = 0;
-
-	while (fn[a]) {
-		switch (fn[a]) {
+	for (int i = 0; i < fn.size(); ++i) {
+		switch (fn[i]) {
 			case ':':
 			case '\\':
 			case '/':
@@ -141,7 +138,6 @@ bool failSecurityCheck(char *fn) {
 				fatal("Filenames may not contain the following characters: \n\n\\  /  :  \"  <  >  |  ?  *\n\nConsequently, the following filename is not allowed:", fn);
 				return true;
 		}
-		a++;
 	}
 	return false;
 }
@@ -158,7 +154,7 @@ struct builtInFunctionData {
 
 static builtReturn sayCore(int numParams, loadedFunction *fun, bool sayIt) {
 	int fileNum = -1;
-	char *newText;
+	Common::String newText;
 	int objT, p;
 	killSpeechTimers();
 
@@ -171,8 +167,6 @@ static builtReturn sayCore(int numParams, loadedFunction *fun, bool sayIt) {
 
 		case 2:
 			newText = getTextFromAnyVar(fun->stack->thisVar);
-			if (!newText)
-				return BR_ERROR;
 			trimStack(fun->stack);
 			if (!getValueType(objT, SVT_OBJTYPE, fun->stack->thisVar))
 				return BR_ERROR;
@@ -181,8 +175,6 @@ static builtReturn sayCore(int numParams, loadedFunction *fun, bool sayIt) {
 			fun->timeLeft = p;
 			//debugOut ("BUILTIN: sayCore: %s (%i)\n", newText, p);
 			fun->isSpeech = true;
-			delete[] newText;
-			newText = NULL;
 			return BR_KEEP_AND_PAUSE;
 	}
 
@@ -264,9 +256,7 @@ builtIn(getStatusText) {
 
 builtIn(getMatchingFiles) {
 	UNUSEDALL
-	char *newText = getTextFromAnyVar(fun->stack->thisVar);
-	if (!newText)
-		return BR_ERROR;
+	Common::String newText = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
 	unlinkVar(fun->reg);
 
@@ -280,8 +270,6 @@ builtIn(getMatchingFiles) {
 	fun->reg.varData.theStack->timesUsed = 1;
 	if (!getSavedGamesStack(fun->reg.varData.theStack, newText))
 		return BR_ERROR;
-	delete newText;
-	newText = NULL;
 	return BR_CONTINUE;
 }
 
@@ -295,13 +283,12 @@ builtIn(saveGame) {
 	loadNow = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
 
-	char *aaaaa = encodeFilename(loadNow);
-	delete[] loadNow;
+	Common::String aaaaa = encodeFilename(loadNow);
+	loadNow.clear();
 	if (failSecurityCheck(aaaaa))
 		return BR_ERROR;      // Won't fail if encoded, how cool is that? OK, not very.
 
-	loadNow = joinStrings(":", aaaaa);
-	delete[] aaaaa;
+	loadNow = ":" + aaaaa;
 
 	setVariable(fun->reg, SVT_INT, 0);
 	saverFunc = fun;
@@ -312,8 +299,8 @@ builtIn(fileExists) {
 	UNUSEDALL
 	loadNow = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
-	char *aaaaa = encodeFilename(loadNow);
-	delete loadNow;
+	Common::String aaaaa = encodeFilename(loadNow);
+	loadNow.clear();
 	if (failSecurityCheck(aaaaa))
 		return BR_ERROR;
 #if 0
@@ -345,28 +332,24 @@ builtIn(fileExists) {
 
 builtIn(loadGame) {
 	UNUSEDALL
-	char *aaaaa = getTextFromAnyVar(fun->stack->thisVar);
+	Common::String aaaaa = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
+	loadNow.clear();
 	loadNow = encodeFilename(aaaaa);
-	delete []aaaaa;
 
 	if (frozenStuff) {
 		fatal("Can't load a saved game while the engine is frozen");
 	}
 	if (failSecurityCheck(loadNow))
 		return BR_ERROR;
-	Common::File fd;
-	if (fd.open(loadNow)) {
-		fd.close();
 	Common::InSaveFile *fp = g_system->getSavefileManager()->openForLoading(loadNow);
 	if (fp) {
 		delete fp;
 		return BR_KEEP_AND_PAUSE;
 	}
-	delete []loadNow;
-	loadNow = NULL;
-
 	debug("not find sav file");
+
+	loadNow.clear();
 	return BR_CONTINUE;
 }
 
@@ -547,8 +530,7 @@ builtIn(pickOne) {
 
 builtIn(substring) {
 	UNUSEDALL
-	char *wholeString;
-	char *newString;
+	Common::String wholeString;
 	int start, length;
 
 	//debugOut ("BUILTIN: substring\n");
@@ -562,12 +544,13 @@ builtIn(substring) {
 	wholeString = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
 
-	UTF8Converter convert(wholeString);
+	UTF8Converter convert;
+	convert.setUTF8String(wholeString);
 	Common::U32String str32 = convert.getU32String();
 
-	if (str32.size() < start + length) {
+	if ((int)str32.size() < start + length) {
 		length = str32.size() - start;
-		if (str32.size() < start) {
+		if ((int)str32.size() < start) {
 			start = 0;
 		}
 	}
@@ -578,25 +561,17 @@ builtIn(substring) {
 	int startoffset = convert.getOriginOffset(start);
 	int endoffset = convert.getOriginOffset(start + length);
 
-	newString = new char[endoffset - startoffset + 1];
-	if (!checkNew(newString)) {
-		return BR_ERROR;
-	}
-
-	memcpy(newString, wholeString + startoffset, endoffset - startoffset);
-	newString[endoffset - startoffset] = 0;
+	Common::String newString(wholeString.begin() + startoffset, wholeString.begin() + endoffset);
 
 	makeTextVar(fun->reg, newString);
-	delete []newString;
 	return BR_CONTINUE;
 }
 
 builtIn(stringLength) {
 	UNUSEDALL
-	char *newText = getTextFromAnyVar(fun->stack->thisVar);
+	Common::String newText = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
 	setVariable(fun->reg, SVT_INT, stringLength(newText));
-	delete[] newText;
 	return BR_CONTINUE;
 }
 
@@ -883,9 +858,7 @@ builtIn(setFont) {
 		return BR_ERROR;
 	//              newDebug ("  Height:", newHeight);
 	trimStack(fun->stack);
-	char *newText = getTextFromAnyVar(fun->stack->thisVar);
-	if (!newText)
-		return BR_ERROR;
+	Common::String newText = getTextFromAnyVar(fun->stack->thisVar);
 	//              newDebug ("  Character supported:", newText);
 	trimStack(fun->stack);
 	if (!getValueType(fileNumber, SVT_FILE, fun->stack->thisVar))
@@ -895,27 +868,22 @@ builtIn(setFont) {
 	if (!loadFont(fileNumber, newText, newHeight))
 		return BR_ERROR;
 	//              newDebug ("  Done!");
-	delete[] newText;
-
 	return BR_CONTINUE;
 }
 
 builtIn(inFont) {
 	UNUSEDALL
-	char *newText = getTextFromAnyVar(fun->stack->thisVar);
-	if (!newText)
-		return BR_ERROR;
+	Common::String newText = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
 
 	// Return value
-
 	setVariable(fun->reg, SVT_INT, isInFont(newText));
 	return BR_CONTINUE;
 }
 
 builtIn(pasteString) {
 	UNUSEDALL
-	char *newText = getTextFromAnyVar(fun->stack->thisVar);
+	Common::String newText = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
 	int y, x;
 	if (!getValueType(y, SVT_INT, fun->stack->thisVar))
@@ -928,7 +896,6 @@ builtIn(pasteString) {
 		x = (winWidth - stringWidth(newText)) >> 1;
 	fixFont(pastePalette);
 	pasteStringToBackdrop(newText, x, y, pastePalette);
-	delete[] newText;
 	return BR_CONTINUE;
 }
 
@@ -986,26 +953,24 @@ builtIn(costume) {
 
 builtIn(launch) {
 	UNUSEDALL
-	char *newTextA = getTextFromAnyVar(fun->stack->thisVar);
-	if (!newTextA)
-		return BR_ERROR;
+	Common::String newTextA = getTextFromAnyVar(fun->stack->thisVar);
 
-	char *newText = encodeFilename(newTextA);
+	Common::String newText = encodeFilename(newTextA);
 
 	trimStack(fun->stack);
 	if (newTextA[0] == 'h' && newTextA[1] == 't' && newTextA[2] == 't' && newTextA[3] == 'p' && (newTextA[4] == ':' || (newTextA[4] == 's' && newTextA[5] == ':'))) {
 
 		// IT'S A WEBSITE!
-		launchMe = copyString(newTextA);
+		launchMe.clear();
+		launchMe = newTextA;
 	} else {
-		char *gameDir;
-		gameDir = joinStrings(gamePath, "/");
-		launchMe = joinStrings(gameDir, newText);
-		delete newText;
-		if (!launchMe)
+		Common::String gameDir = gamePath;
+		gameDir += "/";
+		launchMe.clear();
+		launchMe = gameDir + newText;
+		if (launchMe.empty())
 			return BR_ERROR;
 	}
-	delete newTextA;
 	setGraphicsWindow(false);
 	setVariable(fun->reg, SVT_INT, 1);
 	launchResult = &fun->reg;
@@ -1421,16 +1386,14 @@ builtIn(getOverObject) {
 
 builtIn(rename) {
 	UNUSEDALL
-	char *newText = getTextFromAnyVar(fun->stack->thisVar);
+	Common::String newText = getTextFromAnyVar(fun->stack->thisVar);
 	int objT;
-	if (!newText)
-		return BR_ERROR;
 	trimStack(fun->stack);
 	if (!getValueType(objT, SVT_OBJTYPE, fun->stack->thisVar))
 		return BR_ERROR;
 	trimStack(fun->stack);
 	objectType *o = findObjectType(objT);
-	delete o->screenName;
+	o->screenName.clear();
 	o->screenName = newText;
 	return BR_CONTINUE;
 }
@@ -1865,12 +1828,9 @@ builtIn(addStatus) {
 
 builtIn(statusText) {
 	UNUSEDALL
-	char *newText = getTextFromAnyVar(fun->stack->thisVar);
-	if (!newText)
-		return BR_ERROR;
+	Common::String newText = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
 	setStatusBar(newText);
-	delete[] newText;
 	return BR_CONTINUE;
 }
 
@@ -2024,14 +1984,11 @@ builtIn(cancelSub) {
 
 builtIn(stringWidth) {
 	UNUSEDALL
-	char *theText = getTextFromAnyVar(fun->stack->thisVar);
-	if (!theText)
-		return BR_ERROR;
+	Common::String theText = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
 
 	// Return value
 	setVariable(fun->reg, SVT_INT, stringWidth(theText));
-	delete theText;
 	return BR_CONTINUE;
 }
 
@@ -2207,39 +2164,36 @@ builtIn(fetchEvent) {
 builtIn(deleteFile) {
 	UNUSEDALL
 
-	char *namNormal = getTextFromAnyVar(fun->stack->thisVar);
+	Common::String namNormal = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
-	char *nam = encodeFilename(namNormal);
-	delete namNormal;
+	Common::String nam = encodeFilename(namNormal);
+	namNormal.clear();
 	if (failSecurityCheck(nam))
 		return BR_ERROR;
-	setVariable(fun->reg, SVT_INT, remove(nam));
-	delete nam;
+	setVariable(fun->reg, SVT_INT, remove(nam.c_str()));
 
 	return BR_CONTINUE;
 }
 
 builtIn(renameFile) {
 	UNUSEDALL
-	char *temp;
+	Common::String temp;
 
+	temp.clear();
 	temp = getTextFromAnyVar(fun->stack->thisVar);
-	char *newnam = encodeFilename(temp);
+	Common::String newnam = encodeFilename(temp);
 	trimStack(fun->stack);
 	if (failSecurityCheck(newnam))
 		return BR_ERROR;
-	delete temp;
+	temp.clear();
 
 	temp = getTextFromAnyVar(fun->stack->thisVar);
-	char *nam = encodeFilename(temp);
+	Common::String nam = encodeFilename(temp);
 	trimStack(fun->stack);
 	if (failSecurityCheck(nam))
 		return BR_ERROR;
-	delete temp;
 
-	setVariable(fun->reg, SVT_INT, rename(nam, newnam));
-	delete nam;
-	delete newnam;
+	setVariable(fun->reg, SVT_INT, rename(nam.c_str(), newnam.c_str()));
 
 	return BR_CONTINUE;
 }
@@ -2257,7 +2211,7 @@ builtIn(cacheSound) {
 
 builtIn(burnString) {
 	UNUSEDALL
-	char *newText = getTextFromAnyVar(fun->stack->thisVar);
+	Common::String newText = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
 	int y, x;
 	if (!getValueType(y, SVT_INT, fun->stack->thisVar))
@@ -2270,7 +2224,6 @@ builtIn(burnString) {
 		x = (winWidth - stringWidth(newText)) >> 1;
 	fixFont(pastePalette);
 	burnStringToBackdrop(newText, x, y, pastePalette);
-	delete[] newText;
 	return BR_CONTINUE;
 }
 
@@ -2352,12 +2305,9 @@ builtIn(getSoundCache) {
 builtIn(saveCustomData) {
 	UNUSEDALL
 	// saveCustomData (thisStack, fileName);
-	char *fileNameB = getTextFromAnyVar(fun->stack->thisVar);
-	if (!checkNew(fileNameB))
-		return BR_ERROR;
+	Common::String fileNameB = getTextFromAnyVar(fun->stack->thisVar);
 
-	char *fileName = encodeFilename(fileNameB);
-	delete fileNameB;
+	Common::String fileName = encodeFilename(fileNameB);
 
 	if (failSecurityCheck(fileName))
 		return BR_ERROR;
@@ -2370,19 +2320,15 @@ builtIn(saveCustomData) {
 	if (!stackToFile(fileName, fun->stack->thisVar))
 		return BR_ERROR;
 	trimStack(fun->stack);
-	delete fileName;
 	return BR_CONTINUE;
 }
 
 builtIn(loadCustomData) {
 	UNUSEDALL
 
-	char *newTextA = getTextFromAnyVar(fun->stack->thisVar);
-	if (!checkNew(newTextA))
-		return BR_ERROR;
+	Common::String newTextA = getTextFromAnyVar(fun->stack->thisVar);
 
-	char *newText = encodeFilename(newTextA);
-	delete newTextA;
+	Common::String newText = encodeFilename(newTextA);
 
 	if (failSecurityCheck(newText))
 		return BR_ERROR;
@@ -2398,7 +2344,6 @@ builtIn(loadCustomData) {
 	fun->reg.varData.theStack->timesUsed = 1;
 	if (!fileToStack(newText, fun->reg.varData.theStack))
 		return BR_ERROR;
-	delete newText;
 	return BR_CONTINUE;
 }
 
@@ -2553,17 +2498,10 @@ builtIn(showThumbnail) {
 	trimStack(fun->stack);
 
 	// Encode the name!Encode the name!
-	char *aaaaa = getTextFromAnyVar(fun->stack->thisVar);
-	//              deb ("Got name:", aaaaa;)
-	trimStack(fun->stack);
-	//              deb ("About to encode", aaaaa);
-	char *file = encodeFilename(aaaaa);
-	//              deb ("Made new name", file);
-	//              deb ("aaaaa is still ", aaaaa);
-	delete[] aaaaa;
-	//              deb ("Deleted", "aaaaa");
+	Common::String aaaaa = getTextFromAnyVar(fun->stack->thisVar);
+	trimStack(fun->stack);
+	Common::String file = encodeFilename(aaaaa);
 	showThumbnail(file, x, y);
-	delete[] file;
 	return BR_CONTINUE;
 }
 
@@ -2631,7 +2569,7 @@ builtIn(_rem_registryGetString) {
 
 builtIn(quitWithFatalError) {
 	UNUSEDALL
-	char *mess = getTextFromAnyVar(fun->stack->thisVar);
+	Common::String mess = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
 	fatal(mess);
 	return BR_ERROR;
@@ -2693,12 +2631,7 @@ char builtInFunctionNames[][25] = {
 #define NUM_FUNCS           (sizeof (builtInFunctionArray) / sizeof (builtInFunctionArray[0]))
 
 builtReturn callBuiltIn(int whichFunc, int numParams, loadedFunction *fun) {
-	// fprintf (stderr, "Calling function %d: %s\n", whichFunc, builtInFunctionNames[whichFunc]);    fflush (stderr);
 	if (numBIFNames) {
-
-		//      deb ("IN:", (fun->originalNumber < numUserFunc) ? allUserFunc[fun->originalNumber] : "Unknown user function");
-		//      deb ("GO:", (whichFunc < numBIFNames) ? allBIFNames[whichFunc] : "Unknown built-in function");
-
 		setFatalInfo((fun->originalNumber < numUserFunc) ? allUserFunc[fun->originalNumber] : "Unknown user function",
 				(whichFunc < numBIFNames) ? allBIFNames[whichFunc] : "Unknown built-in function");
 	}
@@ -2708,8 +2641,8 @@ builtReturn callBuiltIn(int whichFunc, int numParams, loadedFunction *fun) {
 			if (paramNum[whichFunc] != numParams) {
 				char buff[100];
 				sprintf(buff, "Built in function must have %i parameter%s", paramNum[whichFunc], (paramNum[whichFunc] == 1) ? "" : "s");
-
-				fatal(copyString(buff));
+				Common::String msg = buff;
+				fatal(msg);
 				return BR_ERROR;
 			}
 		}
diff --git a/engines/sludge/builtin.h b/engines/sludge/builtin.h
index 0fb15d1..3049268 100644
--- a/engines/sludge/builtin.h
+++ b/engines/sludge/builtin.h
@@ -34,7 +34,7 @@ enum builtReturn {
 	BR_ALREADY_GONE
 };
 
-bool failSecurityCheck(char *fn);
+bool failSecurityCheck(const Common::String &fn);
 builtReturn callBuiltIn(int whichFunc, int numParams, loadedFunction *fun);
 
 } // End of namespace Sludge
diff --git a/engines/sludge/fileset.cpp b/engines/sludge/fileset.cpp
index 35b9d3b..a019f82 100644
--- a/engines/sludge/fileset.cpp
+++ b/engines/sludge/fileset.cpp
@@ -23,7 +23,6 @@
 #include "common/file.h"
 #include "common/debug.h"
 
-#include "sludge/stringy.h"
 #include "sludge/allfiles.h"
 #include "sludge/moreio.h"
 #include "sludge/newfatal.h"
@@ -95,7 +94,7 @@ uint openFileFromNum(int num) {
 
 // Converts a string from Windows CP-1252 to UTF-8.
 // This is needed for old games.
-char *convertString(char *s) {
+Common::String convertString(const Common::String &s) {
 #if 0
 	static char *buf = NULL;
 
@@ -158,7 +157,7 @@ char *convertString(char *s) {
 	return s; //TODO: false value
 }
 
-char *getNumberedString(int value) {
+Common::String getNumberedString(int value) {
 
 	if (sliceBusy) {
 		fatal("Can't read from data file", "I'm already reading something");
@@ -169,7 +168,7 @@ char *getNumberedString(int value) {
 	value = bigDataFile->readUint32LE();
 	bigDataFile->seek(value, 0);
 
-	char *s = readString(bigDataFile);
+	Common::String s = readString(bigDataFile);
 
 	if (gameVersion < VERSION(2, 2)) {
 		// This is an older game - We need to convert the string to UTF-8
diff --git a/engines/sludge/fileset.h b/engines/sludge/fileset.h
index 61ab417..b18c87c 100644
--- a/engines/sludge/fileset.h
+++ b/engines/sludge/fileset.h
@@ -33,7 +33,7 @@ void setFileIndices(Common::File *fp, int, uint);
 uint openFileFromNum(int num);
 bool openSubSlice(int num);
 bool openObjectSlice(int num);
-char *getNumberedString(int value);
+Common::String getNumberedString(int value);
 
 bool startAccess();
 void finishAccess();
diff --git a/engines/sludge/fonttext.cpp b/engines/sludge/fonttext.cpp
index 7219689..591e4a3 100644
--- a/engines/sludge/fonttext.cpp
+++ b/engines/sludge/fonttext.cpp
@@ -21,7 +21,6 @@
  */
 
 #include "sludge/allfiles.h"
-#include "sludge/stringy.h"
 #include "sludge/sprites.h"
 #include "sludge/fonttext.h"
 #include "sludge/newfatal.h"
@@ -42,10 +41,10 @@ uint fontTableSize = 0;
 
 extern float cameraZoom;
 
-bool isInFont(char *theText) {
+bool isInFont(const Common::String &theText) {
 	if (!fontTableSize)
 		return 0;
-	if (!theText[0])
+	if (theText.empty())
 		return 0;
 
 	Common::U32String str32 = UTF8Converter::convertUtf8ToUtf32(theText);
@@ -60,12 +59,12 @@ bool isInFont(char *theText) {
 	return fontOrder.getU32String().contains(c);
 }
 
-int stringLength(char *theText) {
+int stringLength(const Common::String &theText) {
 	Common::U32String str32 = UTF8Converter::convertUtf8ToUtf32(theText);
 	return str32.size();
 }
 
-int stringWidth(char *theText) {
+int stringWidth(const Common::String &theText) {
 	int xOff = 0;
 
 	if (!fontTableSize)
@@ -81,7 +80,7 @@ int stringWidth(char *theText) {
 	return xOff;
 }
 
-void pasteString(char *theText, int xOff, int y, spritePalette &thePal) {
+void pasteString(const Common::String &theText, int xOff, int y, spritePalette &thePal) {
 	if (!fontTableSize)
 		return;
 
@@ -97,7 +96,7 @@ void pasteString(char *theText, int xOff, int y, spritePalette &thePal) {
 	}
 }
 
-void pasteStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal) {
+void pasteStringToBackdrop(const Common::String &theText, int xOff, int y, spritePalette &thePal) {
 	if (!fontTableSize)
 		return;
 
@@ -112,7 +111,7 @@ void pasteStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal
 	}
 }
 
-void burnStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal) {
+void burnStringToBackdrop(const Common::String &theText, int xOff, int y, spritePalette &thePal) {
 	if (!fontTableSize)
 		return;
 
@@ -160,7 +159,7 @@ void setFontColour(spritePalette &sP, byte r, byte g, byte b) {
 	sP.originalBlue = b;
 }
 
-bool loadFont(int filenum, const char *charOrder, int h) {
+bool loadFont(int filenum, const Common::String &charOrder, int h) {
 	fontOrder.setUTF8String(charOrder);
 
 	forgetSpriteBank(theFont);
diff --git a/engines/sludge/fonttext.h b/engines/sludge/fonttext.h
index cabb52d..63a38c7 100644
--- a/engines/sludge/fonttext.h
+++ b/engines/sludge/fonttext.h
@@ -26,15 +26,15 @@
 
 namespace Sludge {
 
-bool loadFont(int filenum, const char *charOrder, int);
-void pasteString(char *theText, int, int, spritePalette &);
+bool loadFont(int filenum, const Common::String &charOrder, int);
+void pasteString(const Common::String &theText, int, int, spritePalette &);
 void fixFont(spritePalette &spal);
 void setFontColour(spritePalette &sP, byte r, byte g, byte b);
-int stringWidth(char *theText);
-int stringLength(char *theText);
-void pasteStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal);
-void burnStringToBackdrop(char *theText, int xOff, int y, spritePalette &thePal);
-bool isInFont(char *theText);
+int stringWidth(const Common::String &theText);
+int stringLength(const Common::String &theText);
+void pasteStringToBackdrop(const Common::String &theText, int xOff, int y, spritePalette &thePal);
+void burnStringToBackdrop(const Common::String &theText, int xOff, int y, spritePalette &thePal);
+bool isInFont(const Common::String &theText);
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/graphics.cpp b/engines/sludge/graphics.cpp
index 7211979..3c7cdbf 100644
--- a/engines/sludge/graphics.cpp
+++ b/engines/sludge/graphics.cpp
@@ -28,7 +28,6 @@
 #include "sludge/zbuffer.h"
 #include "sludge/backdrop.h"
 #include "sludge/movie.h"
-#include "sludge/stringy.h"
 #include "sludge/CommonCode/specialsettings.h"
 
 namespace Sludge {
diff --git a/engines/sludge/language.cpp b/engines/sludge/language.cpp
index b7a45ed..2f37eb3 100644
--- a/engines/sludge/language.cpp
+++ b/engines/sludge/language.cpp
@@ -21,7 +21,6 @@
  */
 
 #include "sludge/allfiles.h"
-#include "sludge/stringy.h"
 #include "sludge/newfatal.h"
 #include "sludge/moreio.h"
 #include "sludge/language.h"
@@ -33,60 +32,39 @@
 namespace Sludge {
 
 int *languageTable;
-char **languageName;
+Common::String *languageName;
 settingsStruct gameSettings;
 
-uint stringToInt(char *s) {
-	int i = 0;
-	bool negative = false;
-	for (;;) {
-		if (*s >= '0' && *s <= '9') {
-			i *= 10;
-			i += *s - '0';
-			s++;
-		} else if (*s == '-') {
-			negative = !negative;
-			s++;
-		} else {
-			if (negative)
-				return -i;
-			return i;
-		}
-	}
-}
-
-char *getPrefsFilename(char *filename) {
+Common::String getPrefsFilename(Common::String filename) {
 	// Yes, this trashes the original string, but
 	// we also free it at the end (warning!)...
 
-	int n, i;
-
-	n = strlen(filename);
+	int n = filename.size();
 
 	if (n > 4 && filename[n - 4] == '.') {
-		filename[n - 4] = 0;
+		filename.setChar(0, n - 4);
 	}
 
-	char *f = filename;
-	for (i = 0; i < n; i++) {
+	// get file name from dir
+	int pos = 0;
+	for (int i = 0; i < n; i++) {
 		if (filename[i] == '/')
-			f = filename + i + 1;
+			pos = i + 1;
 	}
 
-	char *joined = joinStrings(f, ".ini");
+	Common::String f = filename.c_str() + pos;
+	Common::String joined = f + ".ini";
 
-	delete[] filename;
-	filename = NULL;
 	return joined;
 }
 
-void readIniFile(const char *filename) {
+void readIniFile(const Common::String &filename) {
 
-	char *langName = getPrefsFilename(copyString(filename));
+	Common::String langName = getPrefsFilename(filename);
 
 	Common::File fd;
 	if (!fd.open(langName)) {
-		debug(kSludgeDebugDataLoad, "Fail to open language file : %s", langName);
+		debug(kSludgeDebugDataLoad, "Fail to open language file : %s", langName.c_str());
 		return;
 	}
 
@@ -98,12 +76,8 @@ void readIniFile(const char *filename) {
 	gameSettings.noStartWindow = false;
 	gameSettings.debugMode = false;
 
-	delete langName;
-	langName = NULL;
-
-	char lineSoFar[257] = "";
-	char secondSoFar[257] = "";
-	byte here = 0;
+	Common::String lineSoFar = "";
+	Common::String secondSoFar = "";
 	char readChar = ' ';
 	bool keepGoing = true;
 	bool doingSecond = false;
@@ -118,40 +92,36 @@ void readIniFile(const char *filename) {
 			case '\n':
 			case '\r':
 				if (doingSecond) {
-					if (strcmp(lineSoFar, "LANGUAGE") == 0) {
-						gameSettings.languageID = stringToInt(secondSoFar);
-					} else if (strcmp(lineSoFar, "WINDOW") == 0) {
-						gameSettings.userFullScreen = !stringToInt(secondSoFar);
-					} else if (strcmp(lineSoFar, "REFRESH") == 0) {
-						gameSettings.refreshRate = stringToInt(secondSoFar);
-					} else if (strcmp(lineSoFar, "ANTIALIAS") == 0) {
-						gameSettings.antiAlias = stringToInt(secondSoFar);
-					} else if (strcmp(lineSoFar, "FIXEDPIXELS") == 0) {
-						gameSettings.fixedPixels = stringToInt(secondSoFar);
-					} else if (strcmp(lineSoFar, "NOSTARTWINDOW") == 0) {
-						gameSettings.noStartWindow = stringToInt(secondSoFar);
-					} else if (strcmp(lineSoFar, "DEBUGMODE") == 0) {
-						gameSettings.debugMode = stringToInt(secondSoFar);
+					if (lineSoFar == "LANGUAGE") {
+						gameSettings.languageID = (uint)secondSoFar.asUint64();
+					} else if (lineSoFar == "WINDOW") {
+						gameSettings.userFullScreen = !secondSoFar.asUint64();
+					} else if (lineSoFar == "REFRESH") {
+						gameSettings.refreshRate = (uint)secondSoFar.asUint64();
+					} else if (lineSoFar == "ANTIALIAS") {
+						gameSettings.antiAlias = (int)secondSoFar.asUint64();
+					} else if (lineSoFar == "FIXEDPIXELS") {
+						gameSettings.fixedPixels = secondSoFar.asUint64();
+					} else if (lineSoFar == "NOSTARTWINDOW") {
+						gameSettings.noStartWindow = secondSoFar.asUint64();
+					} else if (lineSoFar == "DEBUGMODE") {
+						gameSettings.debugMode = secondSoFar.asUint64();
 					}
 				}
-				here = 0;
 				doingSecond = false;
-				lineSoFar[0] = 0;
-				secondSoFar[0] = 0;
+				lineSoFar.clear();
+				secondSoFar.clear();
 				break;
 
 			case '=':
 				doingSecond = true;
-				here = 0;
 				break;
 
 			default:
 				if (doingSecond) {
-					secondSoFar[here++] = readChar;
-					secondSoFar[here] = 0;
+					secondSoFar += readChar;
 				} else {
-					lineSoFar[here++] = readChar;
-					lineSoFar[here] = 0;
+					lineSoFar += readChar;
 				}
 				break;
 		}
@@ -160,7 +130,7 @@ void readIniFile(const char *filename) {
 	fd.close();
 }
 
-void saveIniFile(const char *filename) {
+void saveIniFile(const Common::String &filename) {
 #if 0
 	char *langName = getPrefsFilename(copyString(filename));
 	FILE *fp = fopen(langName, "wt");
@@ -182,18 +152,18 @@ void makeLanguageTable(Common::File *table) {
 	if (!checkNew(languageTable))
 		return;
 
-	languageName = new char *[gameSettings.numLanguages + 1];
+	languageName = new Common::String[gameSettings.numLanguages + 1];
 	if (!checkNew(languageName))
 		return;
 
 	for (uint i = 0; i <= gameSettings.numLanguages; i++) {
 		languageTable[i] = i ? table->readUint16BE() : 0;
 		debug(kSludgeDebugDataLoad, "languageTable %i: %i", i, languageTable[i]);
-		languageName[i] = 0;
+		languageName[i].clear();
 		if (gameVersion >= VERSION(2, 0)) {
 			if (gameSettings.numLanguages) {
 				languageName[i] = readString(table);
-				debug(kSludgeDebugDataLoad, "languageName %i: %s\n", i, languageName[i]);
+				debug(kSludgeDebugDataLoad, "languageName %i: %s\n", i, languageName[i].c_str());
 			}
 		}
 	}
diff --git a/engines/sludge/language.h b/engines/sludge/language.h
index 57bc97e..5c2774f 100644
--- a/engines/sludge/language.h
+++ b/engines/sludge/language.h
@@ -41,8 +41,8 @@ struct settingsStruct {
 
 extern settingsStruct gameSettings;
 
-void readIniFile(const char *filename);
-void saveIniFile(const char *filename);
+void readIniFile(const Common::String &filename);
+void saveIniFile(const Common::String &filename);
 int getLanguageForFileB();
 
 void makeLanguageTable(Common::File *table);
diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index 893d2a8..ccd22f0 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -281,7 +281,7 @@ bool loadVariable(variable *to, Common::SeekableReadStream *stream) {
 			return true;
 
 		case SVT_STRING:
-			to->varData.theString = readString(stream);
+			to->varData.theString = createCString(readString(stream));
 			return true;
 
 		case SVT_STACK:
@@ -384,7 +384,7 @@ loadedFunction *loadFunction(Common::SeekableReadStream *stream) {
 // Save everything
 //----------------------------------------------------------------------
 
-bool saveGame(char *fname) {
+bool saveGame(const Common::String &fname) {
 	Common::OutSaveFile *fp = g_system->getSavefileManager()->openForSaving(fname);
 
 	if (fp == NULL)
@@ -511,7 +511,7 @@ bool saveGame(char *fname) {
 
 int ssgVersion;
 
-bool loadGame(char *fname) {
+bool loadGame(const Common::String &fname) {
 	Common::InSaveFile *fp = g_system->getSavefileManager()->openForLoading(fname);
 	FILETIME savedGameTime;
 
@@ -572,28 +572,25 @@ bool loadGame(char *fname) {
 
 	bool fontLoaded = fp->readByte();
 	int fontNum;
-	char *charOrder;
+	Common::String charOrder = "";
 	if (fontLoaded) {
 		fontNum = fp->readUint16BE();
 		fontHeight = fp->readUint16BE();
 
 		if (ssgVersion < VERSION(2, 2)) {
-			int x;
-			charOrder = new char[257];
-			if (!checkNew(charOrder))
-				return false;
-
+			char *tmp = new char[257];
 			for (int a = 0; a < 256; a++) {
-				x = fp->readByte();
-				charOrder[x] = a;
+				int x = fp->readByte();
+				tmp[x] = a;
 			}
-			charOrder[256] = 0;
+			tmp[256] = 0;
+			charOrder = tmp;
+			delete []tmp;
 		} else {
 			charOrder = readString(fp);
 		}
 	}
 	loadFont(fontNum, charOrder, fontHeight);
-	delete []charOrder;
 
 	fontSpace = fp->readSint16LE();
 
diff --git a/engines/sludge/loadsave.h b/engines/sludge/loadsave.h
index 87024f2..b02fd2d 100644
--- a/engines/sludge/loadsave.h
+++ b/engines/sludge/loadsave.h
@@ -24,8 +24,8 @@
 
 namespace Sludge {
 
-bool saveGame(char *fname);
-bool loadGame(char *fname);
+bool saveGame(const Common::String &fname);
+bool loadGame(const Common::String &fname);
 
 bool saveVariable(variable *from, Common::WriteStream *stream);
 bool loadVariable(variable *to, Common::SeekableReadStream *stream);
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index 4fbdad5..04d38f5 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -30,7 +30,6 @@
 
 #include "sludge/allfiles.h"
 #include "sludge/language.h"
-#include "sludge/stringy.h"
 #include "sludge/sludger.h"
 #include "sludge/backdrop.h"
 #include "sludge/language.h"
@@ -71,9 +70,9 @@ Graphics::Surface renderSurface;
 
 int dialogValue = 0;
 
-char *gameName = NULL;
-char *gamePath = NULL;
-char *bundleFolder;
+Common::String gameName = "";
+Common::String gamePath = "";
+Common::String bundleFolder = "";
 
 void setGameFilePath(char *f) {
 	char currentDir[1000];
@@ -329,8 +328,6 @@ int main_loop(const char *filename)
 		Wait_Frame();
 	}
 
-	delete[] gamePath;
-
 	killSoundStuff();
 
 #if 0
diff --git a/engines/sludge/module.mk b/engines/sludge/module.mk
index 03bcc72..f96a5b6 100644
--- a/engines/sludge/module.mk
+++ b/engines/sludge/module.mk
@@ -32,7 +32,6 @@ MODULE_OBJS := \
 	sprbanks.o \
 	sprites.o \
 	statusba.o \
-	stringy.o \
 	talk.o \
 	thumbnail.o \
 	timing.o \
diff --git a/engines/sludge/moreio.cpp b/engines/sludge/moreio.cpp
index 6635c3d..bc1c57e 100644
--- a/engines/sludge/moreio.cpp
+++ b/engines/sludge/moreio.cpp
@@ -26,7 +26,6 @@
 #include "sludge/allfiles.h"
 #include "sludge/moreio.h"
 #include "sludge/newfatal.h"
-#include "sludge/stringy.h"
 #include "sludge/sludge.h"
 
 namespace Sludge {
@@ -41,157 +40,132 @@ void writeString(Common::String s, Common::WriteStream *stream) {
 	}
 }
 
-char *readString(Common::SeekableReadStream *stream) {
-	int a, len = stream->readUint16BE();
-	char *s = new char[len + 1];
-	if (!checkNew(s)) {
-		return NULL;
+Common::String readString(Common::SeekableReadStream *stream) {
+	int len = stream->readUint16BE();
+	Common::String res = "";
+	for (int a = 0; a < len; a++) {
+		res += (char)(stream->readByte() - 1);
 	}
-	for (a = 0; a < len; a++) {
-		s[a] = (char)(stream->readByte() - 1);
-	}
-	s[len] = 0;
-	debug(kSludgeDebugDataLoad, "Read string of length %i: %s", len, s);
-	return s;
+	debug(kSludgeDebugDataLoad, "Read string of length %i: %s", len, res.c_str());
+	return res;
 }
 
-char *encodeFilename(char *nameIn) {
-	if (!nameIn)
-		return NULL;
+Common::String encodeFilename(const Common::String &nameIn) {
+	Common::String newName = "";
+	if (nameIn.empty())
+		return newName;
 	if (allowAnyFilename) {
-		char *newName = new char[strlen(nameIn) * 2 + 1];
-		if (!checkNew(newName))
-			return NULL;
-
-		int i = 0;
-		while (*nameIn) {
-			switch (*nameIn) {
+		for (uint i = 0; i < nameIn.size(); ++i) {
+			switch (nameIn[i]) {
 				case '<':
-					newName[i++] = '_';
-					newName[i++] = 'L';
+					newName += '_';
+					newName += 'L';
 					break;
 				case '>':
-					newName[i++] = '_';
-					newName[i++] = 'G';
+					newName += '_';
+					newName += 'G';
 					break;
 				case '|':
-					newName[i++] = '_';
-					newName[i++] = 'P';
+					newName += '_';
+					newName += 'P';
 					break;
 				case '_':
-					newName[i++] = '_';
-					newName[i++] = 'U';
+					newName += '_';
+					newName += 'U';
 					break;
 				case '\"':
-					newName[i++] = '_';
-					newName[i++] = 'S';
+					newName += '_';
+					newName += 'S';
 					break;
 				case '\\':
-					newName[i++] = '_';
-					newName[i++] = 'B';
+					newName += '_';
+					newName += 'B';
 					break;
 				case '/':
-					newName[i++] = '_';
-					newName[i++] = 'F';
+					newName += '_';
+					newName += 'F';
 					break;
 				case ':':
-					newName[i++] = '_';
-					newName[i++] = 'C';
+					newName += '_';
+					newName += 'C';
 					break;
 				case '*':
-					newName[i++] = '_';
-					newName[i++] = 'A';
+					newName += '_';
+					newName += 'A';
 					break;
 				case '?':
-					newName[i++] = '_';
-					newName[i++] = 'Q';
+					newName += '_';
+					newName += 'Q';
 					break;
 
 				default:
-					newName[i++] = *nameIn;
+					newName += nameIn[i];
 					break;
 			}
-			newName[i] = 0;
-			nameIn++;
 		}
-		return newName;
 	} else {
-		int a;
-		for (a = 0; nameIn[a]; a++) {
-			if (nameIn[a] == '\\')
-				nameIn[a] = '/';
+		newName.clear();
+		newName = nameIn;
+		for (uint i = 0; i < newName.size(); ++i) {
+			if (newName[i] == '\\')
+				newName.setChar('/', i);
 		}
-
-		return copyString(nameIn);
 	}
+	return newName;
 }
 
-char *decodeFilename(char *nameIn) {
+Common::String decodeFilename(const Common::String &nameIn) {
+	Common::String newName ="";
 	if (allowAnyFilename) {
-		char *newName = new char[strlen(nameIn) + 1];
-		if (!checkNew(newName))
-			return NULL;
-
-		int i = 0;
-		while (*nameIn) {
-			if (*nameIn == '_') {
-				nameIn++;
-				switch (*nameIn) {
+		for (uint i = 0; i < nameIn.size(); ++i) {
+			if (nameIn[i] == '_') {
+				++i;
+				switch (nameIn[i]) {
 					case 'L':
-						newName[i] = '<';
-						nameIn++;
+						newName += '<';
 						break;
 					case 'G':
-						newName[i] = '>';
-						nameIn++;
+						newName += '>';
 						break;
 					case 'P':
-						newName[i] = '|';
-						nameIn++;
+						newName += '|';
 						break;
 					case 'U':
-						newName[i] = '_';
-						nameIn++;
+						newName += '_';
 						break;
 					case 'S':
-						newName[i] = '\"';
-						nameIn++;
+						newName += '\"';
 						break;
 					case 'B':
-						newName[i] = '\\';
-						nameIn++;
+						newName += '\\';
 						break;
 					case 'F':
-						newName[i] = '/';
-						nameIn++;
+						newName += '/';
 						break;
 					case 'C':
-						newName[i] = ':';
-						nameIn++;
+						newName += ':';
 						break;
 					case 'A':
-						newName[i] = '*';
-						nameIn++;
+						newName += '*';
 						break;
 					case 'Q':
-						newName[i] = '?';
-						nameIn++;
+						newName += '?';
 						break;
 					default:
-						newName[i] = '_';
+						newName += '_';
+						--i;
+						break;
 				}
 			} else {
-				newName[i] = *nameIn;
-				nameIn++;
+				newName += nameIn[i];
 			}
-			i++;
-
 		}
-		newName[i] = 0;
 		return newName;
 	} else {
-		return copyString(nameIn);
+		newName.clear();
+		newName = nameIn;
 	}
+	return newName;
 }
 
 } // End of namespace Sludge
diff --git a/engines/sludge/moreio.h b/engines/sludge/moreio.h
index 94c82f2..09235ae 100644
--- a/engines/sludge/moreio.h
+++ b/engines/sludge/moreio.h
@@ -25,11 +25,11 @@
 namespace Sludge {
 
 // Read & Write
-char *readString(Common::SeekableReadStream *stream);
+Common::String readString(Common::SeekableReadStream *stream);
 void writeString(Common::String s, Common::WriteStream *stream);
 
-char *encodeFilename(char *nameIn);
-char *decodeFilename(char *nameIn);
+Common::String encodeFilename(const Common::String &nameIn);
+Common::String decodeFilename(const Common::String &nameIn);
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/newfatal.cpp b/engines/sludge/newfatal.cpp
index 5223400..e9cd860 100644
--- a/engines/sludge/newfatal.cpp
+++ b/engines/sludge/newfatal.cpp
@@ -24,7 +24,6 @@
 
 #include "sludge/allfiles.h"
 #include "sludge/sound.h"
-#include "sludge/stringy.h"
 #include "sludge/errors.h"
 #include "sludge/graphics.h"
 #include "sludge/sludge.h"
@@ -38,11 +37,11 @@ static Common::String fatalMessage;
 static Common::String fatalInfo = "Initialisation error! Something went wrong before we even got started!";
 
 extern int numResourceNames /* = 0*/;
-extern char **allResourceNames /*= NULL*/;
+extern Common::String *allResourceNames /*= ""*/;
 
 int resourceForFatal = -1;
 
-const char *resourceNameFromNum(int i) {
+const Common::String &resourceNameFromNum(int i) {
 	if (i == -1)
 		return NULL;
 	if (numResourceNames == 0)
diff --git a/engines/sludge/newfatal.h b/engines/sludge/newfatal.h
index 47d49e2..c26579a 100644
--- a/engines/sludge/newfatal.h
+++ b/engines/sludge/newfatal.h
@@ -37,7 +37,7 @@ void displayFatal();
 void registerWindowForFatal();
 void setFatalInfo(const Common::String &userFunc, const Common::String &BIF);
 void setResourceForFatal(int n);
-const char *resourceNameFromNum(int i);
+const Common::String &resourceNameFromNum(int i);
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/objtypes.cpp b/engines/sludge/objtypes.cpp
index ddb7553..bb9d707 100644
--- a/engines/sludge/objtypes.cpp
+++ b/engines/sludge/objtypes.cpp
@@ -118,7 +118,7 @@ objectType *loadObjectType(int i) {
 
 objectType *loadObjectRef(Common::SeekableReadStream *stream) {
 	objectType *r = loadObjectType(stream->readUint16BE());
-	delete r->screenName;
+	r->screenName.clear();
 	r->screenName = readString(stream);
 	return r;
 }
@@ -161,13 +161,8 @@ void removeObjectType(objectType *oT) {
 
 	while (*huntRegion) {
 		if ((*huntRegion) == oT) {
-//			FILE * debuggy2 = fopen ("debug.txt", "at");
-//			fprintf (debuggy2, "DELETING OBJECT TYPE: %p %s\n", oT, oT -> screenName);
-//			fclose (debuggy2);
-
 			*huntRegion = oT->next;
 			delete []oT->allCombis;
-			delete []oT->screenName;
 			delete oT;
 			return;
 		} else {
diff --git a/engines/sludge/objtypes.h b/engines/sludge/objtypes.h
index f111606..af9abe3 100644
--- a/engines/sludge/objtypes.h
+++ b/engines/sludge/objtypes.h
@@ -29,7 +29,7 @@ struct combination {
 };
 
 struct objectType {
-	char *screenName;
+	Common::String screenName;
 	int objectNum;
 	objectType *next;
 	byte r, g, b;
diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index 94663ee..9453b21 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -480,7 +480,7 @@ void drawPeople() {
 				bool r = false;
 				r = scaleSprite(myAnim->theSprites->bank.sprites[fNum], myAnim->theSprites->bank.myPalette, thisPerson, m);
 				if (r) {
-					if (thisPerson->thisType->screenName[0]) {
+					if (!thisPerson->thisType->screenName.empty()) {
 						if (personRegion.thisType != thisPerson->thisType)
 							lastRegion = NULL;
 						personRegion.thisType = thisPerson->thisType;
diff --git a/engines/sludge/savedata.cpp b/engines/sludge/savedata.cpp
index 1059cc1..c4e1915 100644
--- a/engines/sludge/savedata.cpp
+++ b/engines/sludge/savedata.cpp
@@ -35,7 +35,7 @@ uint16 saveEncoding = false;
 char encode1 = 0;
 char encode2 = 0;
 
-extern char *gamePath;
+extern Common::String gamePath;
 
 /*
  void loadSaveDebug (char * com) {
@@ -56,28 +56,25 @@ extern char *gamePath;
  fclose (ffpp);
  }
  */
-
-void writeStringEncoded(const char *s, Common::WriteStream *stream) {
-	int a, len = strlen(s);
+void writeStringEncoded(const Common::String &s, Common::WriteStream *stream) {
+	int len = s.size();
 
 	stream->writeUint16BE(len);
-	for (a = 0; a < len; a++) {
+	for (int a = 0; a < len; a++) {
 		stream->writeByte(s[a] ^ encode1);
 		encode1 += encode2;
 	}
 }
 
-char *readStringEncoded(Common::File *fp) {
-	int a, len = fp->readUint16BE();
-	char *s = new char[len + 1];
-	if (!checkNew(s))
-		return NULL;
-	for (a = 0; a < len; a++) {
-		s[a] = (char)(fp->readByte() ^ encode1);
+Common::String readStringEncoded(Common::File *fp) {
+	int len = fp->readUint16BE();
+	Common::String res = "";
+
+	for (int a = 0; a < len; a++) {
+		res += (char)(fp->readByte() ^ encode1);
 		encode1 += encode2;
 	}
-	s[len] = 0;
-	return s;
+	return res;
 }
 
 char *readTextPlain(Common::File *fp) {
@@ -117,11 +114,11 @@ char *readTextPlain(Common::File *fp) {
 	return reply;
 }
 
-bool fileToStack(char *filename, stackHandler *sH) {
+bool fileToStack(const Common::String &filename, stackHandler *sH) {
 
 	variable stringVar;
 	stringVar.varType = SVT_NULL;
-	const char *checker = saveEncoding ? "[Custom data (encoded)]\r\n" : "[Custom data (ASCII)]\n";
+	Common::String checker = saveEncoding ? "[Custom data (encoded)]\r\n" : "[Custom data (ASCII)]\n";
 
 	Common::File fd;
 
@@ -150,23 +147,20 @@ bool fileToStack(char *filename, stackHandler *sH) {
 	encode1 = (byte)saveEncoding & 255;
 	encode2 = (byte)(saveEncoding >> 8);
 
-	while (*checker) {
-		if (fd.readByte() != *checker) {
+	for (uint i = 0; i < checker.size(); ++i) {
+		if (fd.readByte() != checker[i]) {
 			fd.close();
 			return fatal(LOAD_ERROR "This isn't a SLUDGE custom data file:", filename);
 		}
-		checker++;
 	}
 
 	if (saveEncoding) {
-		char *checker = readStringEncoded(&fd);
-		if (strcmp(checker, "UN�LO�CKED")) {
+		checker = readStringEncoded(&fd);
+		if (checker == "UN�LO�CKED") {
 			fd.close();
 			return fatal(
 			LOAD_ERROR "The current file encoding setting does not match the encoding setting used when this file was created:", filename);
 		}
-		delete checker;
-		checker = NULL;
 	}
 
 	for (;;) {
@@ -177,9 +171,8 @@ bool fileToStack(char *filename, stackHandler *sH) {
 				break;
 			switch (i) {
 				case 0: {
-					char *g = readStringEncoded(&fd);
+					Common::String g = readStringEncoded(&fd);
 					makeTextVar(stringVar, g);
-					delete g;
 				}
 					break;
 
@@ -220,7 +213,7 @@ bool fileToStack(char *filename, stackHandler *sH) {
 	return true;
 }
 
-bool stackToFile(char *filename, const variable &from) {
+bool stackToFile(const Common::String &filename, const variable &from) {
 #if 0
 	FILE *fp = fopen(filename, saveEncoding ? "wb" : "wt");
 	if (!fp) return fatal("Can't create file", filename);
diff --git a/engines/sludge/savedata.h b/engines/sludge/savedata.h
index e6422b8..823d2dd 100644
--- a/engines/sludge/savedata.h
+++ b/engines/sludge/savedata.h
@@ -24,8 +24,8 @@
 
 namespace Sludge {
 
-bool fileToStack(char *filename, stackHandler *sH);
-bool stackToFile(char *filename, const variable &from);
+bool fileToStack(const Common::String &filename, stackHandler *sH);
+bool stackToFile(const Common::String &filename, const variable &from);
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index 5c5e6c6..bbec72f 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -33,7 +33,6 @@
 #include "sludge/people.h"
 #include "sludge/talk.h"
 #include "sludge/newfatal.h"
-#include "sludge/stringy.h"
 #include "sludge/moreio.h"
 #include "sludge/statusba.h"
 #include "sludge/builtin.h"
@@ -58,18 +57,18 @@ extern personaAnimation *mouseCursorAnim;
 extern spritePalette pastePalette;
 extern int dialogValue;
 extern uint sceneWidth, sceneHeight;
-extern char *launchMe;
+extern Common::String launchMe;
 extern variable *launchResult;
 
 extern bool reallyWantToQuit;
 extern Graphics::Surface renderSurface;
 
 int numBIFNames = 0;
-char **allBIFNames = NULL;
+Common::String *allBIFNames;
 int numUserFunc = 0;
-char **allUserFunc = NULL;
+Common::String *allUserFunc = NULL;
 int numResourceNames = 0;
-char **allResourceNames = NULL;
+Common::String *allResourceNames = NULL;
 int selectedLanguage = 0;
 int languageNum = -1;
 
@@ -99,7 +98,7 @@ extern loadedFunction *saverFunc;
 loadedFunction *allRunningFunctions = NULL;
 screenRegion *lastRegion = NULL;
 variableStack *noStack = NULL;
-char *loadNow = NULL;
+Common::String loadNow;
 inputType input;
 variable *globalVars;
 int numGlobals;
@@ -133,7 +132,7 @@ void saveHandlers(Common::WriteStream *stream) {
 	stream->writeUint16BE(currentEvents->spaceFunction);
 }
 
-Common::File *openAndVerify(const char *filename, char extra1, char extra2,
+Common::File *openAndVerify(const Common::String &filename, char extra1, char extra2,
 		const char *er, int &fileVersion) {
 	Common::File *fp = new Common::File();
 	if (!fp->open(filename)) {
@@ -184,12 +183,11 @@ Common::File *openAndVerify(const char *filename, char extra1, char extra2,
 	return fp;
 }
 
-bool initSludge(const char *filename) {
+bool initSludge(const Common::String &filename) {
 	int a = 0;
 	mouseCursorAnim = makeNullAnim();
 
-	Common::File *fp = openAndVerify(filename, 'G', 'E', ERROR_BAD_HEADER,
-			gameVersion);
+	Common::File *fp = openAndVerify(filename, 'G', 'E', ERROR_BAD_HEADER, gameVersion);
 	if (!fp)
 		return false;
 
@@ -197,31 +195,34 @@ bool initSludge(const char *filename) {
 	if (c) {
 		numBIFNames = fp->readUint16BE();
 		debug(kSludgeDebugDataLoad, "numBIFNames %i", numBIFNames);
-		allBIFNames = new char *[numBIFNames];
+		allBIFNames = new Common::String[numBIFNames];
 		if (!checkNew(allBIFNames))
 			return false;
 
 		for (int fn = 0; fn < numBIFNames; fn++) {
+			allBIFNames[fn].clear();
 			allBIFNames[fn] = readString(fp);
 		}
 		numUserFunc = fp->readUint16BE();
 		debug(kSludgeDebugDataLoad, "numUserFunc %i", numUserFunc);
-		allUserFunc = new char *[numUserFunc];
+		allUserFunc = new Common::String[numUserFunc];
 		if (!checkNew(allUserFunc))
 			return false;
 
 		for (int fn = 0; fn < numUserFunc; fn++) {
+			allUserFunc[fn].clear();
 			allUserFunc[fn] = readString(fp);
 		}
 		if (gameVersion >= VERSION(1, 3)) {
 			numResourceNames = fp->readUint16BE();
 			debug(kSludgeDebugDataLoad, "numResourceNames %i",
 					numResourceNames);
-			allResourceNames = new char *[numResourceNames];
+			allResourceNames = new Common::String[numResourceNames];
 			if (!checkNew(allResourceNames))
 				return false;
 
 			for (int fn = 0; fn < numResourceNames; fn++) {
+				allResourceNames[fn].clear();
 				allResourceNames[fn] = readString(fp);
 			}
 		}
@@ -235,17 +236,15 @@ bool initSludge(const char *filename) {
 	debug(kSludgeDebugDataLoad, "specialSettings : %i", specialSettings);
 	desiredfps = 1000 / fp->readByte();
 
-	delete[] readString(fp);  // Unused - was used for registration purposes.
+	readString(fp);  // Unused - was used for registration purposes.
 
 	uint bytes_read = fp->read(&fileTime, sizeof(FILETIME));
 	if (bytes_read != sizeof(FILETIME) && fp->err()) {
 		debug("Reading error in initSludge.");
 	}
 
-	char *dataFol =
-			(gameVersion >= VERSION(1, 3)) ?
-					readString(fp) : joinStrings("", "");
-	debug(kSludgeDebugDataLoad, "dataFol : %s", dataFol);
+	Common::String dataFol = (gameVersion >= VERSION(1, 3)) ? readString(fp) : "";
+	debug(kSludgeDebugDataLoad, "dataFol : %s", dataFol.c_str());
 
 	gameSettings.numLanguages =
 			(gameVersion >= VERSION(1, 3)) ? (fp->readByte()) : 0;
@@ -260,13 +259,11 @@ bool initSludge(const char *filename) {
 		fp->readFloatLE();
 	}
 
-	char *checker = readString(fp);
-	debug(kSludgeDebugDataLoad, "checker : %s", checker);
+	Common::String checker = readString(fp);
+	debug(kSludgeDebugDataLoad, "checker : %s", checker.c_str());
 
-	if (strcmp(checker, "okSoFar"))
+	if (checker != "okSoFar")
 		return fatal(ERROR_BAD_HEADER, filename);
-	delete[] checker;
-	checker = NULL;
 
 	byte customIconLogo = fp->readByte();
 	debug(kSludgeDebugDataLoad, "Game icon type: %i", customIconLogo);
@@ -504,11 +501,9 @@ bool initSludge(const char *filename) {
 	// Get the original (untranslated) name of the game and convert it to Unicode.
 	// We use this to find saved preferences and saved games.
 	setFileIndices(fp, gameSettings.numLanguages, 0);
-	char *gameNameOrig = getNumberedString(1);
+	Common::String gameNameOrig = getNumberedString(1);
 
-	char *gameName = encodeFilename(gameNameOrig);
-
-	delete[] gameNameOrig;
+	Common::String gameName = encodeFilename(gameNameOrig);
 
 #if 0
 	changeToUserDir();
@@ -517,7 +512,6 @@ bool initSludge(const char *filename) {
 
 	if (chdir(gameName)) return fatal("This game's preference folder is inaccessible!\nI can't access the following directory (maybe there's a file with the same name, or maybe it's read-protected):", gameName);
 #endif
-	delete[] gameName;
 
 	// Get user settings
 	readIniFile(filename);
@@ -533,14 +527,13 @@ bool initSludge(const char *filename) {
 		return fatal("Can't find the translation data specified!");
 	setFileIndices(NULL, gameSettings.numLanguages, languageNum);
 
-	if (dataFol[0]) {
-		char *dataFolder = encodeFilename(dataFol);
+	if (!dataFol.empty()) {
+		Common::String dataFolder = encodeFilename(dataFol);
 #if 0
 		mkdir(dataFolder, 0000777);
 
 		if (chdir(dataFolder)) return fatal("This game's data folder is inaccessible!\nI can't access the following directory (maybe there's a file with the same name, or maybe it's read-protected):", dataFolder);
 #endif
-		delete []dataFolder;
 	}
 
 	positionStatus(10, winHeight - 15);
@@ -647,10 +640,10 @@ void abortFunction(loadedFunction *fun) {
 	pauseFunction(fun);
 	while (fun->stack)
 		trimStack(fun->stack);
-	delete fun->compiledLines;
+	delete []fun->compiledLines;
 	for (a = 0; a < fun->numLocals; a++)
 		unlinkVar(fun->localVars[a]);
-	delete[] fun->localVars;
+	delete []fun->localVars;
 	unlinkVar(fun->reg);
 	if (fun->calledBy)
 		abortFunction(fun->calledBy);
@@ -1201,16 +1194,15 @@ bool runSludge() {
 		thisFunction = nextFunction;
 	}
 
-	if (loadNow) {
+	if (!loadNow.empty()) {
 		if (loadNow[0] == ':') {
-			saveGame(loadNow + 1);
+			saveGame(loadNow.c_str() + 1);
 			setVariable(saverFunc->reg, SVT_INT, 1);
 		} else {
 			if (!loadGame(loadNow))
 				return false;
 		}
-		delete loadNow;
-		loadNow = NULL;
+		loadNow.clear();
 	}
 
 	return true;
@@ -1315,14 +1307,14 @@ bool handleInput() {
 	}
 //	lastFramesPerSecond = theTime.wSecond;
 #endif
-	if (launchMe) {
+	if (!launchMe.empty()) {
 		if (l) {
 			// Still paused because of spawned thingy...
 		} else {
 			l = 1;
 
 			setVariable(*launchResult, SVT_INT, 0/*launch(launchMe) > 31*/); //TODO:false value
-			launchMe = NULL;
+			launchMe.clear();
 			launchResult = NULL;
 		}
 		return true;
@@ -1379,19 +1371,19 @@ bool handleInput() {
 			return false;
 	}
 	if (input.keyPressed && currentEvents->spaceFunction) {
-		char *tempString = NULL;
+		Common::String tempString = "";
 		switch (input.keyPressed) {
 		case 127:
-			tempString = copyString("BACKSPACE");
+			tempString = "BACKSPACE";
 			break;
 		case 9:
-			tempString = copyString("TAB");
+			tempString = "TAB";
 			break;
 		case 13:
-			tempString = copyString("ENTER");
+			tempString = "ENTER";
 			break;
 		case 27:
-			tempString = copyString("ESCAPE");
+			tempString = "ESCAPE";
 			break;
 			/*
 			 case 1112:  tempString = copyString ("ALT+F1");     break;
@@ -1410,90 +1402,89 @@ bool handleInput() {
 			 case 2019:  tempString = copyString ("PAUSE");      break;
 			 */
 		case 63276:
-			tempString = copyString("PAGE UP");
+			tempString = "PAGE UP";
 			break;
 		case 63277:
-			tempString = copyString("PAGE DOWN");
+			tempString = "PAGE DOWN";
 			break;
 		case 63275:
-			tempString = copyString("END");
+			tempString = "END";
 			break;
 		case 63273:
-			tempString = copyString("HOME");
+			tempString = "HOME";
 			break;
 		case 63234:
-			tempString = copyString("LEFT");
+			tempString = "LEFT";
 			break;
 		case 63232:
-			tempString = copyString("UP");
+			tempString = "UP";
 			break;
 		case 63235:
-			tempString = copyString("RIGHT");
+			tempString = "RIGHT";
 			break;
 		case 63233:
-			tempString = copyString("DOWN");
+			tempString = "DOWN";
 			break;
 			/*
 			 case 2045:   tempString = copyString ("INSERT");     break;
 			 case 2046:   tempString = copyString ("DELETE");     break;
 			 */
 		case 63236:
-			tempString = copyString("F1");
+			tempString = "F1";
 			break;
 		case 63237:
-			tempString = copyString("F2");
+			tempString = "F2";
 			break;
 		case 63238:
-			tempString = copyString("F3");
+			tempString = "F3";
 			break;
 		case 63239:
-			tempString = copyString("F4");
+			tempString = "F4";
 			break;
 		case 63240:
-			tempString = copyString("F5");
+			tempString = "F5";
 			break;
 		case 63241:
-			tempString = copyString("F6");
+			tempString = "F6";
 			break;
 		case 63242:
-			tempString = copyString("F7");
+			tempString = "F7";
 			break;
 		case 63243:
-			tempString = copyString("F8");
+			tempString = "F8";
 			break;
 		case 63244:
-			tempString = copyString("F9");
+			tempString = "F9";
 			break;
 		case 63245:
-			tempString = copyString("F10");
+			tempString = "F10";
 			break;
 		case 63246:
-			tempString = copyString("F11");
+			tempString = "F11";
 			break;
 		case 63247:
-			tempString = copyString("F12");
+			tempString = "F12";
 			break;
 
 		default:
 			if (input.keyPressed >= 256) {
-				//if (captureAllKeys) {
-				tempString = copyString("ABCDEF");
-				sprintf(tempString, "%i", input.keyPressed);
+				char tmp[7] = "ABCDEF";
+				sprintf(tmp, "%i", input.keyPressed);
+				tempString = tmp;
 				//}
 			} else {
-				tempString = copyString(" ");
-				tempString[0] = input.keyPressed;
+				char tmp[2] = " ";
+				tmp[0] = input.keyPressed;
+				tempString = tmp;
 			}
 		}
 
-		if (tempString) {
+		if (!tempString.empty()) {
 			variableStack *tempStack = new variableStack;
 			if (!checkNew(tempStack))
 				return false;
 			initVarNew(tempStack->thisVar);
 			makeTextVar(tempStack->thisVar, tempString);
-			delete tempString;
-			tempString = NULL;
 			tempStack->next = NULL;
 			if (!startNewFunctionNum(currentEvents->spaceFunction, 1, NULL, tempStack))
 				return false;
diff --git a/engines/sludge/sludger.h b/engines/sludge/sludger.h
index 19c6f53..02dd107 100644
--- a/engines/sludge/sludger.h
+++ b/engines/sludge/sludger.h
@@ -76,7 +76,7 @@ struct inputType {
 extern byte *gameIcon;
 extern int iconW, iconH;
 
-bool initSludge(const char *);
+bool initSludge(const Common::String &);
 void displayBase();
 void sludgeDisplay();
 int startNewFunctionNum(uint, uint, loadedFunction *, variableStack*&, bool = true);
@@ -88,7 +88,7 @@ void saveHandlers(Common::WriteStream *stream);
 
 void finishFunction(loadedFunction *fun);
 void abortFunction(loadedFunction *fun);
-Common::File *openAndVerify(const char *filename, char extra1, char extra2, const char *er, int &fileVersion);
+Common::File *openAndVerify(const Common::String &filename, char extra1, char extra2, const char *er, int &fileVersion);
 
 void freezeSubs();
 void unfreezeSubs();
diff --git a/engines/sludge/statusba.cpp b/engines/sludge/statusba.cpp
index 2f1eb6f..de434ae 100644
--- a/engines/sludge/statusba.cpp
+++ b/engines/sludge/statusba.cpp
@@ -27,7 +27,6 @@
 #include "sludge/sprites.h"
 #include "sludge/fonttext.h"
 #include "sludge/moreio.h"
-#include "sludge/stringy.h"
 #include "sludge/newfatal.h"
 #include "sludge/statusba.h"
 
@@ -49,7 +48,6 @@ void killLastStatus() {
 	if (nowStatus->firstStatusBar) {
 		statusBar *kill = nowStatus->firstStatusBar;
 		nowStatus->firstStatusBar = kill->next;
-		delete kill->text;
 		delete kill;
 	}
 }
@@ -61,7 +59,6 @@ void clearStatusBar() {
 	while (stat) {
 		kill = stat;
 		stat = stat->next;
-		delete kill->text;
 		delete kill;
 	}
 	nowStatus->firstStatusBar = NULL;
@@ -71,15 +68,15 @@ void addStatusBar() {
 	statusBar *newStat = new statusBar;
 	if (checkNew(newStat)) {
 		newStat->next = nowStatus->firstStatusBar;
-		newStat->text = copyString("");
+		newStat->text.clear();
 		nowStatus->firstStatusBar = newStat;
 	}
 }
 
-void setStatusBar(char *txt) {
+void setStatusBar(Common::String &txt) {
 	if (nowStatus->firstStatusBar) {
-		delete[] nowStatus->firstStatusBar->text;
-		nowStatus->firstStatusBar->text = copyString(txt);
+		nowStatus->firstStatusBar->text.clear();
+		nowStatus->firstStatusBar->text = txt;
 	}
 }
 
@@ -166,7 +163,7 @@ void initStatusBar() {
 	statusBarLitColour(255, 255, 128);
 }
 
-const char *statusBarText() {
+const Common::String &statusBarText() {
 	if (nowStatus->firstStatusBar) {
 		return nowStatus->firstStatusBar->text;
 	} else {
diff --git a/engines/sludge/statusba.h b/engines/sludge/statusba.h
index b6c0c78..65895f3 100644
--- a/engines/sludge/statusba.h
+++ b/engines/sludge/statusba.h
@@ -22,10 +22,12 @@
 #ifndef SLUDGE_STATUSBA_H
 #define SLUDGE_STATUSBA_H
 
+#include "common/str.h"
+
 namespace Sludge {
 
 struct statusBar {
-	char *text;
+	Common::String text;
 	statusBar *next;
 };
 
@@ -40,14 +42,14 @@ struct statusStuff {
 
 void initStatusBar();
 
-void setStatusBar(char *txt);
+void setStatusBar(Common::String &txt);
 void clearStatusBar();
 void addStatusBar();
 void killLastStatus();
 void statusBarColour(byte r, byte g, byte b);
 void statusBarLitColour(byte r, byte g, byte b);
 void setLitStatus(int i);
-const char *statusBarText();
+const Common::String &statusBarText();
 void positionStatus(int, int);
 void drawStatusBar();
 
diff --git a/engines/sludge/stringy.cpp b/engines/sludge/stringy.cpp
deleted file mode 100644
index 484f014..0000000
--- a/engines/sludge/stringy.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-#include "sludge/allfiles.h"
-#include "sludge/newfatal.h"
-
-#ifndef SLUDGE_STRINGY_H
-#define SLUDGE_STRINGY_H
-
-namespace Sludge {
-
-char *copyString(const char *copyMe) {
-	char *newString = new char[strlen(copyMe) + 1];
-	if (!checkNew(newString))
-		return NULL;
-	strcpy(newString, copyMe);
-	return newString;
-}
-
-char *joinStrings(const char *s1, const char *s2) {
-	char *newString = new char[strlen(s1) + strlen(s2) + 1];
-	if (!checkNew(newString))
-		return NULL;
-	sprintf(newString, "%s%s", s1, s2);
-	return newString;
-}
-
-} // End of namespace Sludge
-
-#endif
diff --git a/engines/sludge/stringy.h b/engines/sludge/stringy.h
deleted file mode 100644
index 7c6f9ed..0000000
--- a/engines/sludge/stringy.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-#ifndef SLUDGE_STRINGY_H
-#define SLUDGE_STRINGY_H
-
-namespace Sludge {
-
-char *copyString(const char *copyMe);
-char *joinStrings(const char *s1, const char *s2);
-
-} // End of namespace Sludge
-
-#endif
diff --git a/engines/sludge/talk.cpp b/engines/sludge/talk.cpp
index d72db2c..a1f51bb 100644
--- a/engines/sludge/talk.cpp
+++ b/engines/sludge/talk.cpp
@@ -32,7 +32,6 @@
 #include "sludge/sound.h"
 #include "sludge/fonttext.h"
 #include "sludge/newfatal.h"
-#include "sludge/stringy.h"
 #include "sludge/moreio.h"
 
 namespace Sludge {
@@ -70,7 +69,6 @@ void killAllSpeech() {
 	while (speech->allSpeech) {
 		killMe = speech->allSpeech;
 		speech->allSpeech = speech->allSpeech->next;
-		delete[] killMe->textLine;
 		delete killMe;
 	}
 }
@@ -79,7 +77,7 @@ inline void setObjFontColour(objectType *t) {
 	setFontColour(speech->talkCol, t->r, t->g, t->b);
 }
 
-void addSpeechLine(char *theLine, int x, int &offset) {
+void addSpeechLine(const Common::String &theLine, int x, int &offset) {
 	int halfWidth = (stringWidth(theLine) >> 1) / cameraZoom;
 	int xx1 = x - (halfWidth);
 	int xx2 = x + (halfWidth);
@@ -87,7 +85,8 @@ void addSpeechLine(char *theLine, int x, int &offset) {
 	checkNew(newLine);
 
 	newLine->next = speech->allSpeech;
-	newLine->textLine = copyString(theLine);
+	newLine->textLine.clear();
+	newLine->textLine = theLine;
 	newLine->x = xx1;
 	speech->allSpeech = newLine;
 	if ((xx1 < 5) && (offset < (5 - xx1))) {
@@ -102,12 +101,12 @@ int isThereAnySpeechGoingOn() {
 	return speech->allSpeech ? speech->lookWhosTalking : -1;
 }
 
-int wrapSpeechXY(char *theText, int x, int y, int wrap, int sampleFile) {
+int wrapSpeechXY(const Common::String &theText, int x, int y, int wrap, int sampleFile) {
 	int a, offset = 0;
 
 	killAllSpeech();
 
-	int speechTime = (strlen(theText) + 20) * speechSpeed;
+	int speechTime = (theText.size() + 20) * speechSpeed;
 	if (speechTime < 1)
 		speechTime = 1;
 	if (sampleFile != -1) {
@@ -123,23 +122,26 @@ int wrapSpeechXY(char *theText, int x, int y, int wrap, int sampleFile) {
 	}
 	speech->speechY = y;
 
-	while (strlen(theText) > wrap) {
+	char *tmp, *txt;
+	tmp = txt = createCString(theText);
+	while ((int)strlen(txt) > wrap) {
 		a = wrap;
-		while (theText[a] != ' ') {
+		while (txt[a] != ' ') {
 			a--;
 			if (a == 0) {
 				a = wrap;
 				break;
 			}
 		}
-		theText[a] = 0;
-		addSpeechLine(theText, x, offset);
-		theText[a] = ' ';
-		theText += a + 1;
+		txt[a] = 0;
+		addSpeechLine(txt, x, offset);
+		txt[a] = ' ';
+		txt += a + 1;
 		y -= fontHeight / cameraZoom;
 	}
-	addSpeechLine(theText, x, offset);
+	addSpeechLine(txt, x, offset);
 	y -= fontHeight / cameraZoom;
+	delete []tmp;
 
 	if (y < 0)
 		speech->speechY -= y;
@@ -158,7 +160,7 @@ int wrapSpeechXY(char *theText, int x, int y, int wrap, int sampleFile) {
 	return speechTime;
 }
 
-int wrapSpeechPerson(char *theText, onScreenPerson &thePerson, int sampleFile,
+int wrapSpeechPerson(const Common::String &theText, onScreenPerson &thePerson, int sampleFile,
 		bool animPerson) {
 	int i = wrapSpeechXY(theText, thePerson.x - cameraX,
 			thePerson.y - cameraY
@@ -172,7 +174,7 @@ int wrapSpeechPerson(char *theText, onScreenPerson &thePerson, int sampleFile,
 	return i;
 }
 
-int wrapSpeech(char *theText, int objT, int sampleFile, bool animPerson) {
+int wrapSpeech(const Common::String &theText, int objT, int sampleFile, bool animPerson) {
 	int i;
 
 	speech->lookWhosTalking = objT;
diff --git a/engines/sludge/talk.h b/engines/sludge/talk.h
index 4f344fb..fe966ca 100644
--- a/engines/sludge/talk.h
+++ b/engines/sludge/talk.h
@@ -27,7 +27,7 @@
 namespace Sludge {
 
 struct speechLine {
-	char *textLine;
+	Common::String textLine;
 	speechLine *next;
 	int x;
 };
@@ -39,7 +39,7 @@ struct speechStruct {
 	spritePalette talkCol;
 };
 
-int wrapSpeech(char *theText, int objT, int sampleFile, bool);
+int wrapSpeech(const Common::String &theText, int objT, int sampleFile, bool);
 void viewSpeech();
 void killAllSpeech();
 int isThereAnySpeechGoingOn();
diff --git a/engines/sludge/thumbnail.cpp b/engines/sludge/thumbnail.cpp
index f28035b..8044ee6 100644
--- a/engines/sludge/thumbnail.cpp
+++ b/engines/sludge/thumbnail.cpp
@@ -129,7 +129,7 @@ bool saveThumbnail(Common::WriteStream *stream) {
 	return true;
 }
 
-void showThumbnail(char *filename, int atX, int atY) {
+void showThumbnail(const Common::String &filename, int atX, int atY) {
 #if 0
 	GLubyte *thumbnailTexture = NULL;
 	GLuint thumbnailTextureName = 0;
diff --git a/engines/sludge/thumbnail.h b/engines/sludge/thumbnail.h
index 4452dca..5b58ecb 100644
--- a/engines/sludge/thumbnail.h
+++ b/engines/sludge/thumbnail.h
@@ -27,7 +27,7 @@ namespace Sludge {
 bool saveThumbnail(Common::WriteStream *stream);
 bool skipThumbnail(Common::SeekableReadStream *stream);
 
-void showThumbnail(char *filename, int x, int y);
+void showThumbnail(const Common::String &filename, int x, int y);
 
 } // End of namespace Sludge
 
diff --git a/engines/sludge/variable.cpp b/engines/sludge/variable.cpp
index eee9d07..7d4ab0c 100644
--- a/engines/sludge/variable.cpp
+++ b/engines/sludge/variable.cpp
@@ -26,7 +26,6 @@
 #include "sludge/variable.h"
 #include "sludge/moreio.h"
 #include "sludge/newfatal.h"
-#include "sludge/stringy.h"
 #include "sludge/objtypes.h"
 #include "sludge/people.h"
 #include "sludge/fileset.h"
@@ -43,7 +42,7 @@ extern char *outputDir;
 void unlinkVar(variable &thisVar) {
 	switch (thisVar.varType) {
 		case SVT_STRING:
-			delete[] thisVar.varData.theString;
+			delete []thisVar.varData.theString;
 			thisVar.varData.theString = NULL;
 			break;
 
@@ -143,10 +142,9 @@ int stackSize(const stackHandler *me) {
 	return r;
 }
 
-bool getSavedGamesStack(stackHandler *sH, char *ext) {
-	char *pattern = joinStrings("*", ext);
-	if (!pattern)
-		return false;
+bool getSavedGamesStack(stackHandler *sH, const Common::String &ext) {
+	Common::String pattern = "*";
+	pattern += ext;
 
 	variable newName;
 	newName.varType = SVT_NULL;
@@ -173,8 +171,6 @@ bool getSavedGamesStack(stackHandler *sH, char *ext) {
 
 	closedir(dir);
 #endif
-	delete[] pattern;
-	pattern = NULL;
 	return true;
 }
 
@@ -238,14 +234,12 @@ void addVariablesInSecond(variable &var1, variable &var2) {
 	if (var1.varType == SVT_INT && var2.varType == SVT_INT) {
 		var2.varData.intValue += var1.varData.intValue;
 	} else {
-		char *string1 = getTextFromAnyVar(var1);
-		char *string2 = getTextFromAnyVar(var2);
+		Common::String string1 = getTextFromAnyVar(var1);
+		Common::String string2 = getTextFromAnyVar(var2);
 
 		unlinkVar(var2);
-		var2.varData.theString = joinStrings(string1, string2);
+		var2.varData.theString = createCString(string1 + string2);
 		var2.varType = SVT_STRING;
-		delete[] string1;
-		delete[] string2;
 	}
 }
 
@@ -285,65 +279,59 @@ void compareVariablesInSecond(const variable &var1, variable &var2) {
 	setVariable(var2, SVT_INT, compareVars(var1, var2));
 }
 
-void makeTextVar(variable &thisVar, const char *txt) {
+char *createCString(const Common::String &s) {
+	uint n = s.size() + 1;
+	char *res = new char[n];
+	if (!checkNew(res)) {
+		fatal("createCString : Unable to copy String");
+		return NULL;
+	}
+	memcpy(res, s.c_str(), n);
+	return res;
+}
+
+void makeTextVar(variable &thisVar, const Common::String &txt) {
 	unlinkVar(thisVar);
 	thisVar.varType = SVT_STRING;
-	thisVar.varData.theString = copyString(txt);
+	thisVar.varData.theString = createCString(txt);
 }
 
 bool loadStringToVar(variable &thisVar, int value) {
-
 	makeTextVar(thisVar, getNumberedString(value));
 	return (bool)(thisVar.varData.theString != NULL);
 }
 
-char *getTextFromAnyVar(const variable &from) {
+Common::String getTextFromAnyVar(const variable &from) {
 	switch (from.varType) {
 		case SVT_STRING:
-			return copyString(from.varData.theString);
+			return from.varData.theString;
 
 		case SVT_FASTARRAY: {
-			char *builder = copyString("FAST:");
-			char *builder2;
-			char *grabText;
+			Common::String builder = "FAST:";
+			Common::String builder2 = "";
+			Common::String grabText = "";
 
 			for (int i = 0; i < from.varData.fastArray->size; i++) {
-				builder2 = joinStrings(builder, " ");
-				if (!builder2)
-					return NULL;
-				delete builder;
+				builder2 = builder + " ";
 				grabText = getTextFromAnyVar(from.varData.fastArray->fastVariables[i]);
-				builder = joinStrings(builder2, grabText);
-				if (!builder)
-					return NULL;
-				delete grabText;
-				grabText = NULL;
-				delete builder2;
-				builder2 = NULL;
+				builder.clear();
+				builder = builder2 + grabText;
 			}
 			return builder;
 		}
 
 		case SVT_STACK: {
-			char *builder = copyString("ARRAY:");
-			char *builder2;
-			char *grabText;
+			Common::String builder = "ARRAY:";
+			Common::String builder2 = "";
+			Common::String grabText = "";
 
 			variableStack *stacky = from.varData.theStack->first;
 
 			while (stacky) {
-				builder2 = joinStrings(builder, " ");
-				if (!builder2)
-					return NULL;
-				delete[] builder;
+				builder2 = builder + " ";
 				grabText = getTextFromAnyVar(stacky->thisVar);
-				builder = joinStrings(builder2, grabText);
-				if (!builder)
-					return NULL;
-				delete[] grabText;
-				grabText = NULL;
-				delete[] builder2;
-				builder2 = NULL;
+				builder.clear();
+				builder = builder2 + grabText;
 				stacky = stacky->next;
 			}
 			return builder;
@@ -351,17 +339,14 @@ char *getTextFromAnyVar(const variable &from) {
 
 		case SVT_INT: {
 			char *buff = new char[10];
-			if (!checkNew(buff))
-				return NULL;
 			sprintf(buff, "%i", from.varData.intValue);
-			return buff;
+			Common::String res = buff;
+			delete []buff;
+			return res;
 		}
 
 		case SVT_FILE: {
-//			char * buff = new char[15];
-//			if (! checkNew (buff)) return NULL;
-//			sprintf (buff, "FILE %i", from.varData.intValue);
-			return joinStrings("", resourceNameFromNum(from.varData.intValue));
+			return resourceNameFromNum(from.varData.intValue);
 		}
 
 			/*      case SVT_ANIM:
@@ -375,14 +360,15 @@ char *getTextFromAnyVar(const variable &from) {
 		case SVT_OBJTYPE: {
 			objectType *thisType = findObjectType(from.varData.intValue);
 			if (thisType)
-				return copyString(thisType->screenName);
+				return thisType->screenName;
+			break;
 		}
 
 		default:
 			break;
 	}
 
-	return copyString(typeName[from.varType]);
+	return typeName[from.varType];
 }
 
 bool getBoolean(const variable &from) {
@@ -425,7 +411,7 @@ bool copyMain(const variable &from, variable &to) {
 			return true;
 
 		case SVT_STRING:
-			to.varData.theString = copyString(from.varData.theString);
+			to.varData.theString = createCString(from.varData.theString);
 			return to.varData.theString ? true : false;
 
 		case SVT_STACK:
diff --git a/engines/sludge/variable.h b/engines/sludge/variable.h
index f36e4e7..3278b8e 100644
--- a/engines/sludge/variable.h
+++ b/engines/sludge/variable.h
@@ -56,7 +56,7 @@ struct stackHandler {
 
 union variableData {
 	signed int intValue;
-	char *theString;
+	const char *theString;
 	stackHandler *theStack;
 	struct personaAnimation *animHandler;
 	struct persona *costumeHandler;
@@ -84,15 +84,16 @@ bool copyVariable(const variable &from, variable &to);
 bool loadStringToVar(variable &thisVar, int value);
 void newAnimationVariable(variable &thisVar, struct personaAnimation *i);
 void newCostumeVariable(variable &thisVar, struct persona *i);
-void makeTextVar(variable &thisVar, const char *txt);
+void makeTextVar(variable &thisVar, const Common::String &txt);
 void addVariablesInSecond(variable &var1, variable &var2);
 void compareVariablesInSecond(const variable &var1, variable &var2);
+char *createCString(const Common::String &s);
 
 // Misc.
 
 void unlinkVar(variable &thisVar);
-char *getNumberedString(int value);
-char *getTextFromAnyVar(const variable &from);
+Common::String getNumberedString(int value);
+Common::String getTextFromAnyVar(const variable &from);
 struct persona *getCostumeFromVar(variable &thisVar);
 struct personaAnimation *getAnimationFromVar(variable &thisVar);
 bool getBoolean(const variable &from);
@@ -110,7 +111,7 @@ bool copyStack(const variable &from, variable &to);
 int stackSize(const stackHandler *me);
 bool stackSetByIndex(variableStack *, uint, const variable &);
 variable *stackGetByIndex(variableStack *, uint);
-bool getSavedGamesStack(stackHandler *sH, char *ext);
+bool getSavedGamesStack(stackHandler *sH, const Common::String &ext);
 
 bool makeFastArrayFromStack(variable &to, const stackHandler *stacky);
 bool makeFastArraySize(variable &to, int size);


Commit: 1cd6de22e409e3cdedbb909c0a71678252bb13ba
    https://github.com/scummvm/scummvm/commit/1cd6de22e409e3cdedbb909c0a71678252bb13ba
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove debug code

Changed paths:
    engines/sludge/loadsave.cpp
    engines/sludge/people.cpp
    engines/sludge/savedata.cpp
    engines/sludge/variable.cpp


diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index ccd22f0..04455bf 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -227,14 +227,6 @@ stackHandler *loadStackRef(Common::SeekableReadStream *stream) {
 // For saving and loading variables...
 //----------------------------------------------------------------------
 bool saveVariable(variable *from, Common::WriteStream *stream) {
-#if DEBUG_STACKINESS
-	{
-		char *str = getTextFromAnyVar(*from);
-		stackDebug((stackfp, "in saveVariable, type %d, %s\n", from->varType, str));
-		delete str;
-	}
-#endif
-
 	stream->writeByte(from->varType);
 	switch (from->varType) {
 		case SVT_INT:
@@ -286,13 +278,6 @@ bool loadVariable(variable *to, Common::SeekableReadStream *stream) {
 
 		case SVT_STACK:
 			to->varData.theStack = loadStackRef(stream);
-#if DEBUG_STACKINESS
-			{
-				char *str = getTextFromAnyVar(*to);
-				stackDebug((stackfp, "just loaded %s\n", str));
-				delete str;
-			}
-#endif
 			return true;
 
 		case SVT_COSTUME:
diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index 9453b21..45e7263 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -1001,21 +1001,7 @@ bool loadAnim(personaAnimation *p, Common::SeekableReadStream *stream) {
 	}
 	return true;
 }
-/*
- void debugCostume (char * message, persona * cossy) {
- FILE * db = fopen ("debuTURN.txt", "at");
- fprintf (db, "  %s costume with %i directions...\n", message, cossy->numDirections);
- for (int a = 0; a < cossy->numDirections * 3; a++) {
- fprintf (db, "      %i frames:", cossy->animation[a]->numFrames);
- for (int b = 0; b < cossy->animation[a]->numFrames; b ++) {
- fprintf (db, " %i", cossy->animation[a]->frames[b]);
- }
- fprintf (db, "\n");
-
- }
- fclose (db);
- }
- */
+
 bool saveCostume(persona *cossy, Common::WriteStream *stream) {
 	int a;
 	stream->writeUint16BE(cossy->numDirections);
diff --git a/engines/sludge/savedata.cpp b/engines/sludge/savedata.cpp
index c4e1915..a315963 100644
--- a/engines/sludge/savedata.cpp
+++ b/engines/sludge/savedata.cpp
@@ -37,25 +37,6 @@ char encode2 = 0;
 
 extern Common::String gamePath;
 
-/*
- void loadSaveDebug (char * com) {
- FILE * ffpp = fopen ("debuggy.txt", "at");
- fprintf (ffpp, "%s\n", com);
- fclose (ffpp);
- }
-
- void loadSaveDebug (char com) {
- FILE * ffpp = fopen ("debuggy.txt", "at");
- fprintf (ffpp, "%c\n", com);
- fclose (ffpp);
- }
-
- void loadSaveDebug (int com) {
- FILE * ffpp = fopen ("debuggy.txt", "at");
- fprintf (ffpp, "%d\n", com);
- fclose (ffpp);
- }
- */
 void writeStringEncoded(const Common::String &s, Common::WriteStream *stream) {
 	int len = s.size();
 
diff --git a/engines/sludge/variable.cpp b/engines/sludge/variable.cpp
index 7d4ab0c..d47e0b4 100644
--- a/engines/sludge/variable.cpp
+++ b/engines/sludge/variable.cpp
@@ -37,8 +37,6 @@ const char *typeName[] = { "undefined", "number", "user function", "string",
 		"built-in function", "file", "stack", "object type", "animation",
 		"costume" };
 
-extern char *outputDir;
-
 void unlinkVar(variable &thisVar) {
 	switch (thisVar.varType) {
 		case SVT_STRING:
@@ -184,43 +182,14 @@ bool copyStack(const variable &from, variable &to) {
 	to.varData.theStack->timesUsed = 1;
 	variableStack *a = from.varData.theStack->first;
 
-#if DEBUG_STACKINESS
-	{
-		char *str = getTextFromAnyVar(from);
-		stackDebug((stackfp, "in copyStack, copying %s\n", str));
-		delete[] str;
-	}
-#endif
-
 	while (a) {
 		addVarToStack(a->thisVar, to.varData.theStack->first);
 		if (to.varData.theStack->last == NULL) {
-#if DEBUG_STACKINESS
-			stackDebug((stackfp, "LAST"));
-#endif
 			to.varData.theStack->last = to.varData.theStack->first;
 		}
-
-#if DEBUG_STACKINESS
-		{
-			char *str = getTextFromAnyVar(a->thisVar);
-			stackDebug((stackfp, "\ta->thisVar = %s (%p)\n", str, to.varData.theStack->first));
-			delete[] str;
-		}
-#endif
-
 		a = a->next;
 	}
 
-#if DEBUG_STACKINESS
-	{
-		char *str = getTextFromAnyVar(to);
-		stackDebug((stackfp, "finished copy, got %s\n", str));
-		delete[] str;
-		stackDebug((stackfp, "first = %p\n", to.varData.theStack->first));
-		stackDebug((stackfp, "last = %p\n", to.varData.theStack->last));
-	}
-#endif
 	return true;
 }
 
@@ -260,7 +229,6 @@ int compareVars(const variable &var1, const variable &var2) {
 				break;
 
 			case SVT_STRING:
-
 				re = (strcmp(var1.varData.theString, var2.varData.theString) == 0);
 				break;
 


Commit: d6308b91769c904421cc6c0470e34c743c903dfc
    https://github.com/scummvm/scummvm/commit/d6308b91769c904421cc6c0470e34c743c903dfc
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: replace utf8 chars by code

Changed paths:
    engines/sludge/savedata.cpp


diff --git a/engines/sludge/savedata.cpp b/engines/sludge/savedata.cpp
index a315963..77328db 100644
--- a/engines/sludge/savedata.cpp
+++ b/engines/sludge/savedata.cpp
@@ -31,6 +31,7 @@
 
 namespace Sludge {
 
+const char UTF8_CHECKER[] = {'U', 'N', -17, -65, -67, 'L', 'O', -17, -65, -67, 'C', 'K', 'E', 'D', '\0'};
 uint16 saveEncoding = false;
 char encode1 = 0;
 char encode2 = 0;
@@ -137,7 +138,7 @@ bool fileToStack(const Common::String &filename, stackHandler *sH) {
 
 	if (saveEncoding) {
 		checker = readStringEncoded(&fd);
-		if (checker == "UN�LO�CKED") {
+		if (checker == UTF8_CHECKER) {
 			fd.close();
 			return fatal(
 			LOAD_ERROR "The current file encoding setting does not match the encoding setting used when this file was created:", filename);
@@ -206,7 +207,7 @@ bool stackToFile(const Common::String &filename, const variable &from) {
 
 	if (saveEncoding) {
 		fprintf(fp, "[Custom data (encoded)]\r\n");
-		writeStringEncoded("UN�LO�CKED", fp);
+		writeStringEncoded(UTF8_CHECKER, fp);
 	} else {
 		fprintf(fp, "[Custom data (ASCII)]\n");
 	}


Commit: 91fcdda2d188602a376f4369d375a74117f93ae7
    https://github.com/scummvm/scummvm/commit/91fcdda2d188602a376f4369d375a74117f93ae7
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: change global Common::String to public var of SludgeEngine

Changed paths:
    engines/sludge/builtin.cpp
    engines/sludge/main_loop.cpp
    engines/sludge/newfatal.cpp
    engines/sludge/savedata.cpp
    engines/sludge/sludge.cpp
    engines/sludge/sludge.h
    engines/sludge/sludger.cpp


diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 6d7ee42..4adbe93 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -54,14 +54,11 @@
 
 namespace Sludge {
 
-extern Common::String gamePath;
-
 int speechMode = 0;
 int cameraX, cameraY;
 float cameraZoom = 1.0;
 spritePalette pastePalette;
 
-Common::String launchMe = NULL;
 variable *launchResult = NULL;
 
 extern int lastFramesPerSecond, thumbWidth, thumbHeight;
@@ -80,7 +77,6 @@ extern char builtInFunctionNames[][25];
 extern Common::String *allUserFunc;
 extern Common::String *allBIFNames;
 extern inputType input;
-extern Common::String loadNow;
 
 #if 0
 extern GLuint backdropTextureName;
@@ -280,15 +276,15 @@ builtIn(saveGame) {
 		fatal("Can't save game state while the engine is frozen");
 	}
 
-	loadNow = getTextFromAnyVar(fun->stack->thisVar);
+	g_sludge->loadNow = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
 
-	Common::String aaaaa = encodeFilename(loadNow);
-	loadNow.clear();
+	Common::String aaaaa = encodeFilename(g_sludge->loadNow);
+	g_sludge->loadNow.clear();
 	if (failSecurityCheck(aaaaa))
 		return BR_ERROR;      // Won't fail if encoded, how cool is that? OK, not very.
 
-	loadNow = ":" + aaaaa;
+	g_sludge->loadNow = ":" + aaaaa;
 
 	setVariable(fun->reg, SVT_INT, 0);
 	saverFunc = fun;
@@ -297,10 +293,10 @@ builtIn(saveGame) {
 
 builtIn(fileExists) {
 	UNUSEDALL
-	loadNow = getTextFromAnyVar(fun->stack->thisVar);
+	g_sludge->loadNow = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
-	Common::String aaaaa = encodeFilename(loadNow);
-	loadNow.clear();
+	Common::String aaaaa = encodeFilename(g_sludge->loadNow);
+	g_sludge->loadNow.clear();
 	if (failSecurityCheck(aaaaa))
 		return BR_ERROR;
 #if 0
@@ -334,22 +330,22 @@ builtIn(loadGame) {
 	UNUSEDALL
 	Common::String aaaaa = getTextFromAnyVar(fun->stack->thisVar);
 	trimStack(fun->stack);
-	loadNow.clear();
-	loadNow = encodeFilename(aaaaa);
+	g_sludge->loadNow.clear();
+	g_sludge->loadNow = encodeFilename(aaaaa);
 
 	if (frozenStuff) {
 		fatal("Can't load a saved game while the engine is frozen");
 	}
-	if (failSecurityCheck(loadNow))
+	if (failSecurityCheck(g_sludge->loadNow))
 		return BR_ERROR;
-	Common::InSaveFile *fp = g_system->getSavefileManager()->openForLoading(loadNow);
+	Common::InSaveFile *fp = g_system->getSavefileManager()->openForLoading(g_sludge->loadNow);
 	if (fp) {
 		delete fp;
 		return BR_KEEP_AND_PAUSE;
 	}
 	debug("not find sav file");
 
-	loadNow.clear();
+	g_sludge->loadNow.clear();
 	return BR_CONTINUE;
 }
 
@@ -961,14 +957,14 @@ builtIn(launch) {
 	if (newTextA[0] == 'h' && newTextA[1] == 't' && newTextA[2] == 't' && newTextA[3] == 'p' && (newTextA[4] == ':' || (newTextA[4] == 's' && newTextA[5] == ':'))) {
 
 		// IT'S A WEBSITE!
-		launchMe.clear();
-		launchMe = newTextA;
+		g_sludge->launchMe.clear();
+		g_sludge->launchMe = newTextA;
 	} else {
-		Common::String gameDir = gamePath;
+		Common::String gameDir = g_sludge->gamePath;
 		gameDir += "/";
-		launchMe.clear();
-		launchMe = gameDir + newText;
-		if (launchMe.empty())
+		g_sludge->launchMe.clear();
+		g_sludge->launchMe = gameDir + newText;
+		if (g_sludge->launchMe.empty())
 			return BR_ERROR;
 	}
 	setGraphicsWindow(false);
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index 04d38f5..d888059 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -70,10 +70,6 @@ Graphics::Surface renderSurface;
 
 int dialogValue = 0;
 
-Common::String gameName = "";
-Common::String gamePath = "";
-Common::String bundleFolder = "";
-
 void setGameFilePath(char *f) {
 	char currentDir[1000];
 #if 0
@@ -295,7 +291,7 @@ int main_loop(const char *filename)
 	initStatusBar();
 	resetRandW();
 
-	gameName = getNumberedString(1);
+	g_sludge->gameName = getNumberedString(1);
 
 #if 0
 	SDL_WM_SetCaption(gameName, gameName);
diff --git a/engines/sludge/newfatal.cpp b/engines/sludge/newfatal.cpp
index e9cd860..0f847bd 100644
--- a/engines/sludge/newfatal.cpp
+++ b/engines/sludge/newfatal.cpp
@@ -33,9 +33,6 @@ namespace Sludge {
 
 const char emergencyMemoryMessage[] = "Out of memory displaying error message!";
 
-static Common::String fatalMessage;
-static Common::String fatalInfo = "Initialisation error! Something went wrong before we even got started!";
-
 extern int numResourceNames /* = 0*/;
 extern Common::String *allResourceNames /*= ""*/;
 
@@ -52,13 +49,13 @@ const Common::String &resourceNameFromNum(int i) {
 }
 
 bool hasFatal() {
-	if (!fatalMessage.empty())
+	if (!g_sludge->fatalMessage.empty())
 		return true;
 	return false;
 }
 
 void displayFatal() {
-	if (!fatalMessage.empty()) {
+	if (!g_sludge->fatalMessage.empty()) {
 #if 0
 		msgBox("SLUDGE v" TEXT_VERSION " fatal error!", fatalMessage);
 #endif
@@ -66,7 +63,7 @@ void displayFatal() {
 }
 
 void registerWindowForFatal() {
-	fatalInfo = "There's an error with this SLUDGE game! If you're designing this game, please turn on verbose error messages in the project manager and recompile. If not, please contact the author saying where and how this problem occured.";
+	g_sludge->fatalInfo = "There's an error with this SLUDGE game! If you're designing this game, please turn on verbose error messages in the project manager and recompile. If not, please contact the author saying where and how this problem occured.";
 }
 
 int inFatal(const Common::String &str) {
@@ -84,8 +81,8 @@ int checkNew(const void *mem) {
 }
 
 void setFatalInfo(const Common::String &userFunc, const Common::String &BIF) {
-	fatalInfo = "Currently in this sub: " + userFunc + "\nCalling: " + BIF;
-	debug(kSludgeDebugFatal, "%s", fatalInfo.c_str());
+	g_sludge->fatalInfo = "Currently in this sub: " + userFunc + "\nCalling: " + BIF;
+	debug(kSludgeDebugFatal, "%s", g_sludge->fatalInfo.c_str());
 }
 
 void setResourceForFatal(int n) {
@@ -95,10 +92,10 @@ void setResourceForFatal(int n) {
 int fatal(const Common::String &str1) {
 	if (numResourceNames && resourceForFatal != -1) {
 		Common::String r = resourceNameFromNum(resourceForFatal);
-		Common::String newStr = fatalInfo + "\nResource: " + r + "\n\n" + str1;
+		Common::String newStr = g_sludge->fatalInfo + "\nResource: " + r + "\n\n" + str1;
 		inFatal(newStr);
 	} else {
-		Common::String newStr = fatalInfo + "\n\n" + str1;
+		Common::String newStr = g_sludge->fatalInfo + "\n\n" + str1;
 		inFatal(newStr);
 	}
 	return 0;
diff --git a/engines/sludge/savedata.cpp b/engines/sludge/savedata.cpp
index 77328db..1757798 100644
--- a/engines/sludge/savedata.cpp
+++ b/engines/sludge/savedata.cpp
@@ -36,8 +36,6 @@ uint16 saveEncoding = false;
 char encode1 = 0;
 char encode2 = 0;
 
-extern Common::String gamePath;
-
 void writeStringEncoded(const Common::String &s, Common::WriteStream *stream) {
 	int len = s.size();
 
diff --git a/engines/sludge/sludge.cpp b/engines/sludge/sludge.cpp
index ab1eb86..e3754a7 100644
--- a/engines/sludge/sludge.cpp
+++ b/engines/sludge/sludge.cpp
@@ -50,6 +50,16 @@ SludgeEngine::SludgeEngine(OSystem *syst, const SludgeGameDescription *gameDesc)
 
 	// check init
 	debug("SludgeEngine::SludgeEngine");
+
+	// Init Strings
+	launchMe = "";
+	loadNow = "";
+	gameName = "";
+	gamePath = "";
+	bundleFolder = "";
+
+	fatalMessage = "";
+	fatalInfo = "Initialisation error! Something went wrong before we even got started!";
 }
 
 SludgeEngine::~SludgeEngine() {
diff --git a/engines/sludge/sludge.h b/engines/sludge/sludge.h
index 03297ff..6ed1380 100644
--- a/engines/sludge/sludge.h
+++ b/engines/sludge/sludge.h
@@ -53,6 +53,15 @@ protected:
 	virtual Common::Error run();
 
 public:
+	// global String variables
+	Common::String launchMe;
+	Common::String loadNow;
+	Common::String gameName;
+	Common::String gamePath;
+	Common::String bundleFolder;
+	Common::String fatalMessage;
+	Common::String fatalInfo;
+
 	SludgeEngine(OSystem *syst, const SludgeGameDescription *gameDesc);
 	virtual ~SludgeEngine();
 
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index bbec72f..c1b9af8 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -57,7 +57,6 @@ extern personaAnimation *mouseCursorAnim;
 extern spritePalette pastePalette;
 extern int dialogValue;
 extern uint sceneWidth, sceneHeight;
-extern Common::String launchMe;
 extern variable *launchResult;
 
 extern bool reallyWantToQuit;
@@ -98,7 +97,6 @@ extern loadedFunction *saverFunc;
 loadedFunction *allRunningFunctions = NULL;
 screenRegion *lastRegion = NULL;
 variableStack *noStack = NULL;
-Common::String loadNow;
 inputType input;
 variable *globalVars;
 int numGlobals;
@@ -1194,15 +1192,15 @@ bool runSludge() {
 		thisFunction = nextFunction;
 	}
 
-	if (!loadNow.empty()) {
-		if (loadNow[0] == ':') {
-			saveGame(loadNow.c_str() + 1);
+	if (!g_sludge->loadNow.empty()) {
+		if (g_sludge->loadNow[0] == ':') {
+			saveGame(g_sludge->loadNow.c_str() + 1);
 			setVariable(saverFunc->reg, SVT_INT, 1);
 		} else {
-			if (!loadGame(loadNow))
+			if (!loadGame(g_sludge->loadNow))
 				return false;
 		}
-		loadNow.clear();
+		g_sludge->loadNow.clear();
 	}
 
 	return true;
@@ -1307,14 +1305,14 @@ bool handleInput() {
 	}
 //	lastFramesPerSecond = theTime.wSecond;
 #endif
-	if (!launchMe.empty()) {
+	if (!g_sludge->launchMe.empty()) {
 		if (l) {
 			// Still paused because of spawned thingy...
 		} else {
 			l = 1;
 
 			setVariable(*launchResult, SVT_INT, 0/*launch(launchMe) > 31*/); //TODO:false value
-			launchMe.clear();
+			g_sludge->launchMe.clear();
 			launchResult = NULL;
 		}
 		return true;


Commit: 8f618e55ae0126512c8845b6eabceb70aa04779e
    https://github.com/scummvm/scummvm/commit/8f618e55ae0126512c8845b6eabceb70aa04779e
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: move namespace to functionlist.h

Changed paths:
    engines/sludge/CommonCode/functionlist.h
    engines/sludge/builtin.cpp


diff --git a/engines/sludge/CommonCode/functionlist.h b/engines/sludge/CommonCode/functionlist.h
index e59fe44..025f80a 100644
--- a/engines/sludge/CommonCode/functionlist.h
+++ b/engines/sludge/CommonCode/functionlist.h
@@ -26,170 +26,181 @@
  in the current version of the engine,
  but that value currently isn't used anywhere
  */
-FUNC(true, say)
-FUNC(true, skipSpeech)
-FUNC(true, statusText)
-FUNC(true, pause)
-FUNC(true, onLeftMouse)
-FUNC(true, onRightMouse)
-FUNC(true, setCursor)
-FUNC(true, addOverlay)
-FUNC(true, addCharacter)
-FUNC(true, playSound)
-FUNC(true, getMouseX)
-FUNC(true, getMouseY)
-FUNC(true, addScreenRegion)
-FUNC(true, onMoveMouse)
-FUNC(true, onFocusChange)
-FUNC(true, getOverObject)
-FUNC(true, blankScreen)
-FUNC(true, moveCharacter)
-FUNC(true, onKeyboard)
-FUNC(true, getObjectX)
-FUNC(true, getObjectY)
-FUNC(true, random)
-FUNC(true, spawnSub)
-FUNC(true, blankArea)
-FUNC(true, hideCharacter)
-FUNC(true, showCharacter)
-FUNC(true, callEvent)
-FUNC(true, removeScreenRegion)
-FUNC(true, animate)
-FUNC(true, turnCharacter)
-FUNC(true, removeAllCharacters)
-FUNC(true, removeAllScreenRegions)
-FUNC(true, setScale)
-FUNC(true, newStack)
-FUNC(true, pushToStack)
-FUNC(true, popFromStack)
-FUNC(true, clearStatus)
-FUNC(true, addStatus)
-FUNC(true, removeLastStatus)
-FUNC(true, lightStatus)
-FUNC(true, getStatusText)
-FUNC(true, setStatusColour)
-FUNC(true, deleteFromStack)
-FUNC(true, freeze)
-FUNC(true, unfreeze)
-FUNC(true, pasteImage)
-FUNC(true, copyStack)
-FUNC(true, completeTimers)
-FUNC(true, setCharacterDrawMode)
-FUNC(true, anim)
-FUNC(true, costume)
-FUNC(true, pickOne)
-FUNC(true, setCostume)
-FUNC(true, wait)
-FUNC(true, somethingSpeaking)
-FUNC(true, substring)
-FUNC(true, stringLength)
-FUNC(true, darkBackground)
-FUNC(true, saveGame)
-FUNC(true, loadGame)
-FUNC(true, quitGame)
-FUNC(true, rename)
-FUNC(true, stackSize)
-FUNC(true, pasteString)
-FUNC(true, startMusic)
-FUNC(true, setDefaultMusicVolume)
-FUNC(true, setMusicVolume)
-FUNC(true, stopMusic)
-FUNC(true, stopSound)
-FUNC(true, setFont)
-FUNC(true, alignStatus)
-FUNC(true, showFloor)
-FUNC(true, showBoxes)
-FUNC(true, positionStatus)
-FUNC(true, setFloor)
-FUNC(true, forceCharacter)
-FUNC(true, jumpCharacter)
-FUNC(true, peekStart)
-FUNC(true, peekEnd)
-FUNC(true, enqueue)
-FUNC(true, setZBuffer)
-FUNC(true, getMatchingFiles)
-FUNC(true, inFont)
-FUNC(true, onLeftMouseUp)
-FUNC(true, onRightMouseUp)
-FUNC(true, loopSound)
-FUNC(true, removeCharacter)
-FUNC(true, stopCharacter)
-FUNC(true, launch)
-FUNC(true, howFrozen)
-FUNC(true, setPasteColour)
-FUNC(true, setLitStatusColour)
-FUNC(true, fileExists)
-FUNC(true, floatCharacter)
-FUNC(true, cancelSub)
-FUNC(true, setCharacterWalkSpeed)
-FUNC(true, deleteAllFromStack)
-FUNC(true, setCharacterExtra)
-FUNC(true, mixOverlay)
-FUNC(true, pasteCharacter)
-FUNC(true, setSceneDimensions)
-FUNC(true, aimCamera)
-FUNC(true, getMouseScreenX)
-FUNC(true, getMouseScreenY)
-FUNC(true, setDefaultSoundVolume)
-FUNC(true, setSoundVolume)
-FUNC(true, setSoundLoopPoints)
-FUNC(true, setSpeechMode)
-FUNC(true, setLightMap)
-FUNC(true, think)
-FUNC(true, getCharacterDirection)
-FUNC(true, isCharacter)
-FUNC(true, isScreenRegion)
-FUNC(true, isMoving)
-FUNC(true, deleteFile)
-FUNC(true, renameFile)
-FUNC(true, hardScroll)
-FUNC(true, stringWidth)
-FUNC(true, setSpeechSpeed)
-FUNC(true, normalCharacter)
-FUNC(true, fetchEvent)
-FUNC(true, transitionLevel)
-FUNC(true, spinCharacter)
-FUNC(true, setFontSpacing)
-FUNC(true, burnString)
-FUNC(true, captureAllKeys)
-FUNC(true, cacheSound)
-FUNC(true, setCharacterSpinSpeed)
-FUNC(true, transitionMode)
-FUNC(false, _rem_movieStart)
-FUNC(false, _rem_movieAbort)
-FUNC(false, _rem_moviePlaying)
-FUNC(false, _rem_updateDisplay)
-FUNC(true, getSoundCache)
-FUNC(true, saveCustomData)
-FUNC(true, loadCustomData)
-FUNC(true, setCustomEncoding)
-FUNC(true, freeSound)
-FUNC(true, parallaxAdd)
-FUNC(true, parallaxClear)
-FUNC(true, setBlankColour)
-FUNC(true, setBurnColour)
-FUNC(true, getPixelColour)
-FUNC(true, makeFastArray)
-FUNC(true, getCharacterScale)
-FUNC(true, getLanguageID)
-FUNC(false, _rem_launchWith)
-FUNC(true, getFramesPerSecond)
-FUNC(true, showThumbnail)
-FUNC(true, setThumbnailSize)
-FUNC(true, hasFlag)
-FUNC(true, snapshotGrab)
-FUNC(true, snapshotClear)
-FUNC(true, bodgeFilenames)
-FUNC(false, _rem_registryGetString)
-FUNC(true, quitWithFatalError)
-FUNC(true, _rem_setCharacterAA)
-FUNC(true, _rem_setMaximumAA)
-FUNC(true, setBackgroundEffect)
-FUNC(true, doBackgroundEffect)
-FUNC(true, setCharacterAngleOffset)
-FUNC(true, setCharacterTransparency)
-FUNC(true, setCharacterColourise)
-FUNC(true, zoomCamera)
-FUNC(true, playMovie)
-FUNC(true, stopMovie)
-FUNC(true, pauseMovie)
+
+namespace Sludge {
+
+#define FUNC(special,name)      {builtIn_ ## name},
+static builtInFunctionData builtInFunctionArray[] = {
+	FUNC(true, say)
+	FUNC(true, skipSpeech)
+	FUNC(true, statusText)
+	FUNC(true, pause)
+	FUNC(true, onLeftMouse)
+	FUNC(true, onRightMouse)
+	FUNC(true, setCursor)
+	FUNC(true, addOverlay)
+	FUNC(true, addCharacter)
+	FUNC(true, playSound)
+	FUNC(true, getMouseX)
+	FUNC(true, getMouseY)
+	FUNC(true, addScreenRegion)
+	FUNC(true, onMoveMouse)
+	FUNC(true, onFocusChange)
+	FUNC(true, getOverObject)
+	FUNC(true, blankScreen)
+	FUNC(true, moveCharacter)
+	FUNC(true, onKeyboard)
+	FUNC(true, getObjectX)
+	FUNC(true, getObjectY)
+	FUNC(true, random)
+	FUNC(true, spawnSub)
+	FUNC(true, blankArea)
+	FUNC(true, hideCharacter)
+	FUNC(true, showCharacter)
+	FUNC(true, callEvent)
+	FUNC(true, removeScreenRegion)
+	FUNC(true, animate)
+	FUNC(true, turnCharacter)
+	FUNC(true, removeAllCharacters)
+	FUNC(true, removeAllScreenRegions)
+	FUNC(true, setScale)
+	FUNC(true, newStack)
+	FUNC(true, pushToStack)
+	FUNC(true, popFromStack)
+	FUNC(true, clearStatus)
+	FUNC(true, addStatus)
+	FUNC(true, removeLastStatus)
+	FUNC(true, lightStatus)
+	FUNC(true, getStatusText)
+	FUNC(true, setStatusColour)
+	FUNC(true, deleteFromStack)
+	FUNC(true, freeze)
+	FUNC(true, unfreeze)
+	FUNC(true, pasteImage)
+	FUNC(true, copyStack)
+	FUNC(true, completeTimers)
+	FUNC(true, setCharacterDrawMode)
+	FUNC(true, anim)
+	FUNC(true, costume)
+	FUNC(true, pickOne)
+	FUNC(true, setCostume)
+	FUNC(true, wait)
+	FUNC(true, somethingSpeaking)
+	FUNC(true, substring)
+	FUNC(true, stringLength)
+	FUNC(true, darkBackground)
+	FUNC(true, saveGame)
+	FUNC(true, loadGame)
+	FUNC(true, quitGame)
+	FUNC(true, rename)
+	FUNC(true, stackSize)
+	FUNC(true, pasteString)
+	FUNC(true, startMusic)
+	FUNC(true, setDefaultMusicVolume)
+	FUNC(true, setMusicVolume)
+	FUNC(true, stopMusic)
+	FUNC(true, stopSound)
+	FUNC(true, setFont)
+	FUNC(true, alignStatus)
+	FUNC(true, showFloor)
+	FUNC(true, showBoxes)
+	FUNC(true, positionStatus)
+	FUNC(true, setFloor)
+	FUNC(true, forceCharacter)
+	FUNC(true, jumpCharacter)
+	FUNC(true, peekStart)
+	FUNC(true, peekEnd)
+	FUNC(true, enqueue)
+	FUNC(true, setZBuffer)
+	FUNC(true, getMatchingFiles)
+	FUNC(true, inFont)
+	FUNC(true, onLeftMouseUp)
+	FUNC(true, onRightMouseUp)
+	FUNC(true, loopSound)
+	FUNC(true, removeCharacter)
+	FUNC(true, stopCharacter)
+	FUNC(true, launch)
+	FUNC(true, howFrozen)
+	FUNC(true, setPasteColour)
+	FUNC(true, setLitStatusColour)
+	FUNC(true, fileExists)
+	FUNC(true, floatCharacter)
+	FUNC(true, cancelSub)
+	FUNC(true, setCharacterWalkSpeed)
+	FUNC(true, deleteAllFromStack)
+	FUNC(true, setCharacterExtra)
+	FUNC(true, mixOverlay)
+	FUNC(true, pasteCharacter)
+	FUNC(true, setSceneDimensions)
+	FUNC(true, aimCamera)
+	FUNC(true, getMouseScreenX)
+	FUNC(true, getMouseScreenY)
+	FUNC(true, setDefaultSoundVolume)
+	FUNC(true, setSoundVolume)
+	FUNC(true, setSoundLoopPoints)
+	FUNC(true, setSpeechMode)
+	FUNC(true, setLightMap)
+	FUNC(true, think)
+	FUNC(true, getCharacterDirection)
+	FUNC(true, isCharacter)
+	FUNC(true, isScreenRegion)
+	FUNC(true, isMoving)
+	FUNC(true, deleteFile)
+	FUNC(true, renameFile)
+	FUNC(true, hardScroll)
+	FUNC(true, stringWidth)
+	FUNC(true, setSpeechSpeed)
+	FUNC(true, normalCharacter)
+	FUNC(true, fetchEvent)
+	FUNC(true, transitionLevel)
+	FUNC(true, spinCharacter)
+	FUNC(true, setFontSpacing)
+	FUNC(true, burnString)
+	FUNC(true, captureAllKeys)
+	FUNC(true, cacheSound)
+	FUNC(true, setCharacterSpinSpeed)
+	FUNC(true, transitionMode)
+	FUNC(false, _rem_movieStart)
+	FUNC(false, _rem_movieAbort)
+	FUNC(false, _rem_moviePlaying)
+	FUNC(false, _rem_updateDisplay)
+	FUNC(true, getSoundCache)
+	FUNC(true, saveCustomData)
+	FUNC(true, loadCustomData)
+	FUNC(true, setCustomEncoding)
+	FUNC(true, freeSound)
+	FUNC(true, parallaxAdd)
+	FUNC(true, parallaxClear)
+	FUNC(true, setBlankColour)
+	FUNC(true, setBurnColour)
+	FUNC(true, getPixelColour)
+	FUNC(true, makeFastArray)
+	FUNC(true, getCharacterScale)
+	FUNC(true, getLanguageID)
+	FUNC(false, _rem_launchWith)
+	FUNC(true, getFramesPerSecond)
+	FUNC(true, showThumbnail)
+	FUNC(true, setThumbnailSize)
+	FUNC(true, hasFlag)
+	FUNC(true, snapshotGrab)
+	FUNC(true, snapshotClear)
+	FUNC(true, bodgeFilenames)
+	FUNC(false, _rem_registryGetString)
+	FUNC(true, quitWithFatalError)
+	FUNC(true, _rem_setCharacterAA)
+	FUNC(true, _rem_setMaximumAA)
+	FUNC(true, setBackgroundEffect)
+	FUNC(true, doBackgroundEffect)
+	FUNC(true, setCharacterAngleOffset)
+	FUNC(true, setCharacterTransparency)
+	FUNC(true, setCharacterColourise)
+	FUNC(true, zoomCamera)
+	FUNC(true, playMovie)
+	FUNC(true, stopMovie)
+	FUNC(true, pauseMovie)
+};
+#undef FUNC
+
+int NUM_FUNCS = (sizeof (builtInFunctionArray) / sizeof (builtInFunctionArray[0]));
+
+} // End of namespace Sludge
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 4adbe93..6340ad0 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -2612,19 +2612,11 @@ builtIn(doBackgroundEffect) {
 
 //-------------------------------------
 
-#define FUNC(special,name)      {builtIn_ ## name},
-static builtInFunctionData builtInFunctionArray[] = {
-#include "CommonCode/functionlist.h"
-		};
-#undef FUNC
+} // End of namespace Sludge
 
-#define FUNC(special,name)      {#name},
-char builtInFunctionNames[][25] = {
 #include "CommonCode/functionlist.h"
-		};
-#undef FUNC
 
-#define NUM_FUNCS           (sizeof (builtInFunctionArray) / sizeof (builtInFunctionArray[0]))
+namespace Sludge {
 
 builtReturn callBuiltIn(int whichFunc, int numParams, loadedFunction *fun) {
 	if (numBIFNames) {


Commit: 3c84965724e246da984b2521a17ab23b5f55f4ec
    https://github.com/scummvm/scummvm/commit/3c84965724e246da984b2521a17ab23b5f55f4ec
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: delete a game that doesn't exist any more

Changed paths:
    engines/sludge/detection.cpp
    engines/sludge/detection_tables.h


diff --git a/engines/sludge/detection.cpp b/engines/sludge/detection.cpp
index 6dc7c12..e884d17 100644
--- a/engines/sludge/detection.cpp
+++ b/engines/sludge/detection.cpp
@@ -47,7 +47,6 @@ const char *SludgeEngine::getGameFile() const {
 static const PlainGameDescriptor sludgeGames[] = {
 	{ "sludge", "Sludge Game" },
 	{ "welcome", "Welcome Example" },
-	{ "welcomeloop", "Welcome Loop Test" },
 	{ "verbcoin", "Verb Coin" },
 	{ "robinsrescue", "Robin's Rescue" },
 	{ 0, 0 }
diff --git a/engines/sludge/detection_tables.h b/engines/sludge/detection_tables.h
index a64bdab..e67d238 100644
--- a/engines/sludge/detection_tables.h
+++ b/engines/sludge/detection_tables.h
@@ -49,18 +49,6 @@ static const SludgeGameDescription gameDescriptions[] = {
 		0
 	},
 
-	{
-		{
-			"welcomeloop",
-			"",
-			AD_ENTRY1s("WelcomeLoop.slg", "89c67f14f88cfb54989847ef0cbb0d3b", 36947),
-			Common::EN_ANY,
-			Common::kPlatformUnknown,
-			ADGF_NO_FLAGS,
-			GUIO0()
-		},
-		0
-	},
 
 	{
 		{


Commit: 6b794d3da775726930f096493bcc9bfbef71d198
    https://github.com/scummvm/scummvm/commit/6b794d3da775726930f096493bcc9bfbef71d198
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove game settings from Sludge code

Changed paths:
    engines/sludge/language.cpp
    engines/sludge/language.h


diff --git a/engines/sludge/language.cpp b/engines/sludge/language.cpp
index 2f37eb3..5b7adee 100644
--- a/engines/sludge/language.cpp
+++ b/engines/sludge/language.cpp
@@ -20,6 +20,8 @@
  *
  */
 
+#include "common/debug.h"
+
 #include "sludge/allfiles.h"
 #include "sludge/newfatal.h"
 #include "sludge/moreio.h"
@@ -27,126 +29,12 @@
 #include "sludge/sludge.h"
 #include "sludge/CommonCode/version.h"
 
-#include "common/debug.h"
-
 namespace Sludge {
 
 int *languageTable;
 Common::String *languageName;
 settingsStruct gameSettings;
 
-Common::String getPrefsFilename(Common::String filename) {
-	// Yes, this trashes the original string, but
-	// we also free it at the end (warning!)...
-
-	int n = filename.size();
-
-	if (n > 4 && filename[n - 4] == '.') {
-		filename.setChar(0, n - 4);
-	}
-
-	// get file name from dir
-	int pos = 0;
-	for (int i = 0; i < n; i++) {
-		if (filename[i] == '/')
-			pos = i + 1;
-	}
-
-	Common::String f = filename.c_str() + pos;
-	Common::String joined = f + ".ini";
-
-	return joined;
-}
-
-void readIniFile(const Common::String &filename) {
-
-	Common::String langName = getPrefsFilename(filename);
-
-	Common::File fd;
-	if (!fd.open(langName)) {
-		debug(kSludgeDebugDataLoad, "Fail to open language file : %s", langName.c_str());
-		return;
-	}
-
-	gameSettings.languageID = 0;
-	gameSettings.userFullScreen = false; //defaultUserFullScreen(); TODO: false value
-	gameSettings.refreshRate = 0;
-	gameSettings.antiAlias = 1;
-	gameSettings.fixedPixels = false;
-	gameSettings.noStartWindow = false;
-	gameSettings.debugMode = false;
-
-	Common::String lineSoFar = "";
-	Common::String secondSoFar = "";
-	char readChar = ' ';
-	bool keepGoing = true;
-	bool doingSecond = false;
-
-	do {
-		readChar = fd.readByte();
-		if (fd.eos()) {
-			readChar = '\n';
-			keepGoing = false;
-		}
-		switch (readChar) {
-			case '\n':
-			case '\r':
-				if (doingSecond) {
-					if (lineSoFar == "LANGUAGE") {
-						gameSettings.languageID = (uint)secondSoFar.asUint64();
-					} else if (lineSoFar == "WINDOW") {
-						gameSettings.userFullScreen = !secondSoFar.asUint64();
-					} else if (lineSoFar == "REFRESH") {
-						gameSettings.refreshRate = (uint)secondSoFar.asUint64();
-					} else if (lineSoFar == "ANTIALIAS") {
-						gameSettings.antiAlias = (int)secondSoFar.asUint64();
-					} else if (lineSoFar == "FIXEDPIXELS") {
-						gameSettings.fixedPixels = secondSoFar.asUint64();
-					} else if (lineSoFar == "NOSTARTWINDOW") {
-						gameSettings.noStartWindow = secondSoFar.asUint64();
-					} else if (lineSoFar == "DEBUGMODE") {
-						gameSettings.debugMode = secondSoFar.asUint64();
-					}
-				}
-				doingSecond = false;
-				lineSoFar.clear();
-				secondSoFar.clear();
-				break;
-
-			case '=':
-				doingSecond = true;
-				break;
-
-			default:
-				if (doingSecond) {
-					secondSoFar += readChar;
-				} else {
-					lineSoFar += readChar;
-				}
-				break;
-		}
-	} while (keepGoing);
-
-	fd.close();
-}
-
-void saveIniFile(const Common::String &filename) {
-#if 0
-	char *langName = getPrefsFilename(copyString(filename));
-	FILE *fp = fopen(langName, "wt");
-	delete langName;
-
-	fprintf(fp, "LANGUAGE=%d\n", gameSettings.languageID);
-	fprintf(fp, "WINDOW=%d\n", ! gameSettings.userFullScreen);
-	fprintf(fp, "ANTIALIAS=%d\n", gameSettings.antiAlias);
-	fprintf(fp, "FIXEDPIXELS=%d\n", gameSettings.fixedPixels);
-	fprintf(fp, "NOSTARTWINDOW=%d\n", gameSettings.noStartWindow);
-	fprintf(fp, "DEBUGMODE=%d\n", gameSettings.debugMode);
-
-	fclose(fp);
-#endif
-}
-
 void makeLanguageTable(Common::File *table) {
 	languageTable = new int[gameSettings.numLanguages + 1];
 	if (!checkNew(languageTable))
diff --git a/engines/sludge/language.h b/engines/sludge/language.h
index 5c2774f..2f8d6c0 100644
--- a/engines/sludge/language.h
+++ b/engines/sludge/language.h
@@ -31,18 +31,10 @@ namespace Sludge {
 struct settingsStruct {
 	uint languageID;
 	uint numLanguages;
-	bool userFullScreen;
-	uint refreshRate;
-	int antiAlias;
-	bool fixedPixels;
-	bool noStartWindow;
-	bool debugMode;
 };
 
 extern settingsStruct gameSettings;
 
-void readIniFile(const Common::String &filename);
-void saveIniFile(const Common::String &filename);
 int getLanguageForFileB();
 
 void makeLanguageTable(Common::File *table);


Commit: ef5e8091f60ffe8f031e26c4c669b60ba11e0cfc
    https://github.com/scummvm/scummvm/commit/ef5e8091f60ffe8f031e26c4c669b60ba11e0cfc
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: use multiple entries for language selection

Changed paths:
    engines/sludge/detection.cpp
    engines/sludge/detection_tables.h
    engines/sludge/language.cpp
    engines/sludge/sludge.h
    engines/sludge/sludger.cpp


diff --git a/engines/sludge/detection.cpp b/engines/sludge/detection.cpp
index e884d17..b0c3ef2 100644
--- a/engines/sludge/detection.cpp
+++ b/engines/sludge/detection.cpp
@@ -30,11 +30,10 @@ namespace Sludge {
 
 struct SludgeGameDescription {
 	ADGameDescription desc;
-
-	int gameType;
+	uint languageID;
 };
 
-int SludgeEngine::getGameType() const { return _gameDescription->gameType; }
+uint SludgeEngine::getLanguageID() const { return _gameDescription->languageID; }
 const char *SludgeEngine::getGameId() const { return _gameDescription->desc.gameId;}
 uint32 SludgeEngine::getFeatures() const { return _gameDescription->desc.flags; }
 Common::Language SludgeEngine::getLanguage() const { return _gameDescription->desc.language; }
diff --git a/engines/sludge/detection_tables.h b/engines/sludge/detection_tables.h
index e67d238..b162533 100644
--- a/engines/sludge/detection_tables.h
+++ b/engines/sludge/detection_tables.h
@@ -49,6 +49,18 @@ static const SludgeGameDescription gameDescriptions[] = {
 		0
 	},
 
+	{
+		{
+			"verbcoin",
+			"",
+			AD_ENTRY1s("Verb Coin.slg", "e39ec315dcbf3a1137481f0a5fe1617d", 980270),
+			Common::DE_DEU,
+			Common::kPlatformUnknown,
+			ADGF_NO_FLAGS,
+			GUIO0()
+		},
+		1
+	},
 
 	{
 		{
diff --git a/engines/sludge/language.cpp b/engines/sludge/language.cpp
index 5b7adee..06f2a08 100644
--- a/engines/sludge/language.cpp
+++ b/engines/sludge/language.cpp
@@ -31,12 +31,12 @@
 
 namespace Sludge {
 
-int *languageTable;
+uint *languageTable;
 Common::String *languageName;
 settingsStruct gameSettings;
 
 void makeLanguageTable(Common::File *table) {
-	languageTable = new int[gameSettings.numLanguages + 1];
+	languageTable = new uint[gameSettings.numLanguages + 1];
 	if (!checkNew(languageTable))
 		return;
 
@@ -64,7 +64,6 @@ int getLanguageForFileB() {
 		if (languageTable[i] == gameSettings.languageID)
 			indexNum = i;
 	}
-
 	return indexNum;
 }
 
diff --git a/engines/sludge/sludge.h b/engines/sludge/sludge.h
index 6ed1380..cb3d524 100644
--- a/engines/sludge/sludge.h
+++ b/engines/sludge/sludge.h
@@ -65,7 +65,7 @@ public:
 	SludgeEngine(OSystem *syst, const SludgeGameDescription *gameDesc);
 	virtual ~SludgeEngine();
 
-	int getGameType() const;
+	uint getLanguageID() const;
 	const char *getGameId() const;
 	uint32 getFeatures() const;
 	Common::Language getLanguage() const;
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index c1b9af8..620d50d 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -511,14 +511,9 @@ bool initSludge(const Common::String &filename) {
 	if (chdir(gameName)) return fatal("This game's preference folder is inaccessible!\nI can't access the following directory (maybe there's a file with the same name, or maybe it's read-protected):", gameName);
 #endif
 
-	// Get user settings
-	readIniFile(filename);
+	// Get language selected by user
+	gameSettings.languageID = g_sludge->getLanguageID();
 
-	// There's no startup window on Linux and respecting this
-	// option from the ini file would disable commandline options.
-	saveIniFile(filename);
-
-	
 	// Now set file indices properly to the chosen language.
 	languageNum = getLanguageForFileB();
 	if (languageNum < 0)


Commit: 94ddf526f43068925ca914f60934cf5ad53371cf
    https://github.com/scummvm/scummvm/commit/94ddf526f43068925ca914f60934cf5ad53371cf
Author: yinsimei (roseline.yin at gmail.com)
Date: 2017-07-13T18:27:45+02:00

Commit Message:
SLUDGE: remove CommonCode directory to have a flat structure

Changed paths:
  A engines/sludge/functionlist.h
  A engines/sludge/specialsettings.h
  A engines/sludge/version.h
  R engines/sludge/CommonCode/functionlist.h
  R engines/sludge/CommonCode/specialsettings.h
  R engines/sludge/CommonCode/version.h
    engines/sludge/builtin.cpp
    engines/sludge/fileset.cpp
    engines/sludge/graphics.cpp
    engines/sludge/language.cpp
    engines/sludge/loadsave.cpp
    engines/sludge/main_loop.cpp
    engines/sludge/movie.cpp
    engines/sludge/newfatal.cpp
    engines/sludge/objtypes.cpp
    engines/sludge/people.cpp
    engines/sludge/sludger.cpp
    engines/sludge/thumbnail.cpp


diff --git a/engines/sludge/CommonCode/functionlist.h b/engines/sludge/CommonCode/functionlist.h
deleted file mode 100644
index 025f80a..0000000
--- a/engines/sludge/CommonCode/functionlist.h
+++ /dev/null
@@ -1,206 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-/*
- This is the list of the built in functions
-
- true or false states if it's a used function
- in the current version of the engine,
- but that value currently isn't used anywhere
- */
-
-namespace Sludge {
-
-#define FUNC(special,name)      {builtIn_ ## name},
-static builtInFunctionData builtInFunctionArray[] = {
-	FUNC(true, say)
-	FUNC(true, skipSpeech)
-	FUNC(true, statusText)
-	FUNC(true, pause)
-	FUNC(true, onLeftMouse)
-	FUNC(true, onRightMouse)
-	FUNC(true, setCursor)
-	FUNC(true, addOverlay)
-	FUNC(true, addCharacter)
-	FUNC(true, playSound)
-	FUNC(true, getMouseX)
-	FUNC(true, getMouseY)
-	FUNC(true, addScreenRegion)
-	FUNC(true, onMoveMouse)
-	FUNC(true, onFocusChange)
-	FUNC(true, getOverObject)
-	FUNC(true, blankScreen)
-	FUNC(true, moveCharacter)
-	FUNC(true, onKeyboard)
-	FUNC(true, getObjectX)
-	FUNC(true, getObjectY)
-	FUNC(true, random)
-	FUNC(true, spawnSub)
-	FUNC(true, blankArea)
-	FUNC(true, hideCharacter)
-	FUNC(true, showCharacter)
-	FUNC(true, callEvent)
-	FUNC(true, removeScreenRegion)
-	FUNC(true, animate)
-	FUNC(true, turnCharacter)
-	FUNC(true, removeAllCharacters)
-	FUNC(true, removeAllScreenRegions)
-	FUNC(true, setScale)
-	FUNC(true, newStack)
-	FUNC(true, pushToStack)
-	FUNC(true, popFromStack)
-	FUNC(true, clearStatus)
-	FUNC(true, addStatus)
-	FUNC(true, removeLastStatus)
-	FUNC(true, lightStatus)
-	FUNC(true, getStatusText)
-	FUNC(true, setStatusColour)
-	FUNC(true, deleteFromStack)
-	FUNC(true, freeze)
-	FUNC(true, unfreeze)
-	FUNC(true, pasteImage)
-	FUNC(true, copyStack)
-	FUNC(true, completeTimers)
-	FUNC(true, setCharacterDrawMode)
-	FUNC(true, anim)
-	FUNC(true, costume)
-	FUNC(true, pickOne)
-	FUNC(true, setCostume)
-	FUNC(true, wait)
-	FUNC(true, somethingSpeaking)
-	FUNC(true, substring)
-	FUNC(true, stringLength)
-	FUNC(true, darkBackground)
-	FUNC(true, saveGame)
-	FUNC(true, loadGame)
-	FUNC(true, quitGame)
-	FUNC(true, rename)
-	FUNC(true, stackSize)
-	FUNC(true, pasteString)
-	FUNC(true, startMusic)
-	FUNC(true, setDefaultMusicVolume)
-	FUNC(true, setMusicVolume)
-	FUNC(true, stopMusic)
-	FUNC(true, stopSound)
-	FUNC(true, setFont)
-	FUNC(true, alignStatus)
-	FUNC(true, showFloor)
-	FUNC(true, showBoxes)
-	FUNC(true, positionStatus)
-	FUNC(true, setFloor)
-	FUNC(true, forceCharacter)
-	FUNC(true, jumpCharacter)
-	FUNC(true, peekStart)
-	FUNC(true, peekEnd)
-	FUNC(true, enqueue)
-	FUNC(true, setZBuffer)
-	FUNC(true, getMatchingFiles)
-	FUNC(true, inFont)
-	FUNC(true, onLeftMouseUp)
-	FUNC(true, onRightMouseUp)
-	FUNC(true, loopSound)
-	FUNC(true, removeCharacter)
-	FUNC(true, stopCharacter)
-	FUNC(true, launch)
-	FUNC(true, howFrozen)
-	FUNC(true, setPasteColour)
-	FUNC(true, setLitStatusColour)
-	FUNC(true, fileExists)
-	FUNC(true, floatCharacter)
-	FUNC(true, cancelSub)
-	FUNC(true, setCharacterWalkSpeed)
-	FUNC(true, deleteAllFromStack)
-	FUNC(true, setCharacterExtra)
-	FUNC(true, mixOverlay)
-	FUNC(true, pasteCharacter)
-	FUNC(true, setSceneDimensions)
-	FUNC(true, aimCamera)
-	FUNC(true, getMouseScreenX)
-	FUNC(true, getMouseScreenY)
-	FUNC(true, setDefaultSoundVolume)
-	FUNC(true, setSoundVolume)
-	FUNC(true, setSoundLoopPoints)
-	FUNC(true, setSpeechMode)
-	FUNC(true, setLightMap)
-	FUNC(true, think)
-	FUNC(true, getCharacterDirection)
-	FUNC(true, isCharacter)
-	FUNC(true, isScreenRegion)
-	FUNC(true, isMoving)
-	FUNC(true, deleteFile)
-	FUNC(true, renameFile)
-	FUNC(true, hardScroll)
-	FUNC(true, stringWidth)
-	FUNC(true, setSpeechSpeed)
-	FUNC(true, normalCharacter)
-	FUNC(true, fetchEvent)
-	FUNC(true, transitionLevel)
-	FUNC(true, spinCharacter)
-	FUNC(true, setFontSpacing)
-	FUNC(true, burnString)
-	FUNC(true, captureAllKeys)
-	FUNC(true, cacheSound)
-	FUNC(true, setCharacterSpinSpeed)
-	FUNC(true, transitionMode)
-	FUNC(false, _rem_movieStart)
-	FUNC(false, _rem_movieAbort)
-	FUNC(false, _rem_moviePlaying)
-	FUNC(false, _rem_updateDisplay)
-	FUNC(true, getSoundCache)
-	FUNC(true, saveCustomData)
-	FUNC(true, loadCustomData)
-	FUNC(true, setCustomEncoding)
-	FUNC(true, freeSound)
-	FUNC(true, parallaxAdd)
-	FUNC(true, parallaxClear)
-	FUNC(true, setBlankColour)
-	FUNC(true, setBurnColour)
-	FUNC(true, getPixelColour)
-	FUNC(true, makeFastArray)
-	FUNC(true, getCharacterScale)
-	FUNC(true, getLanguageID)
-	FUNC(false, _rem_launchWith)
-	FUNC(true, getFramesPerSecond)
-	FUNC(true, showThumbnail)
-	FUNC(true, setThumbnailSize)
-	FUNC(true, hasFlag)
-	FUNC(true, snapshotGrab)
-	FUNC(true, snapshotClear)
-	FUNC(true, bodgeFilenames)
-	FUNC(false, _rem_registryGetString)
-	FUNC(true, quitWithFatalError)
-	FUNC(true, _rem_setCharacterAA)
-	FUNC(true, _rem_setMaximumAA)
-	FUNC(true, setBackgroundEffect)
-	FUNC(true, doBackgroundEffect)
-	FUNC(true, setCharacterAngleOffset)
-	FUNC(true, setCharacterTransparency)
-	FUNC(true, setCharacterColourise)
-	FUNC(true, zoomCamera)
-	FUNC(true, playMovie)
-	FUNC(true, stopMovie)
-	FUNC(true, pauseMovie)
-};
-#undef FUNC
-
-int NUM_FUNCS = (sizeof (builtInFunctionArray) / sizeof (builtInFunctionArray[0]));
-
-} // End of namespace Sludge
diff --git a/engines/sludge/CommonCode/specialsettings.h b/engines/sludge/CommonCode/specialsettings.h
deleted file mode 100644
index 0aa4786..0000000
--- a/engines/sludge/CommonCode/specialsettings.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-#define SPECIAL_REGISTERED      1
-#define SPECIAL_FULLSCREEN      2
-#define SPECIAL_MOUSE_1         4
-#define SPECIAL_SILENT          8
-#define SPECIAL_MOUSE_2         16
-#define SPECIAL_INVISIBLE       32
-#define SPECIAL_HIDELOGO        64
-#define SPECIAL_HIDELOADING     128
diff --git a/engines/sludge/CommonCode/version.h b/engines/sludge/CommonCode/version.h
deleted file mode 100644
index f984b0e..0000000
--- a/engines/sludge/CommonCode/version.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-#define MAJOR_VERSION 2
-#define MINOR_VERSION 2
-#define RELEASE_VERSION 1
-#define BUILD_VERSION 208
-#define TEXT_VERSION "2.2.1"
-#define WHOLE_VERSION (MAJOR_VERSION * 256 + MINOR_VERSION) // This version
-#define MINIM_VERSION (1             * 256 + 2)             // Earliest version of games the engine can run
-
-#define COPYRIGHT_TEXT "\251 Hungry Software and contributors 2000-2014"
-
-#define VERSION(a,b)    (a * 256 + b)
-
-namespace Sludge {
-
-extern int gameVersion;
-
-} // End of namespace Sludge
diff --git a/engines/sludge/builtin.cpp b/engines/sludge/builtin.cpp
index 6340ad0..e2ebb1f 100644
--- a/engines/sludge/builtin.cpp
+++ b/engines/sludge/builtin.cpp
@@ -2614,7 +2614,7 @@ builtIn(doBackgroundEffect) {
 
 } // End of namespace Sludge
 
-#include "CommonCode/functionlist.h"
+#include "functionlist.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/fileset.cpp b/engines/sludge/fileset.cpp
index a019f82..f0731fe 100644
--- a/engines/sludge/fileset.cpp
+++ b/engines/sludge/fileset.cpp
@@ -27,7 +27,7 @@
 #include "sludge/moreio.h"
 #include "sludge/newfatal.h"
 #include "sludge/sludge.h"
-#include "sludge/CommonCode/version.h"
+#include "sludge/version.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/functionlist.h b/engines/sludge/functionlist.h
new file mode 100644
index 0000000..025f80a
--- /dev/null
+++ b/engines/sludge/functionlist.h
@@ -0,0 +1,206 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+/*
+ This is the list of the built in functions
+
+ true or false states if it's a used function
+ in the current version of the engine,
+ but that value currently isn't used anywhere
+ */
+
+namespace Sludge {
+
+#define FUNC(special,name)      {builtIn_ ## name},
+static builtInFunctionData builtInFunctionArray[] = {
+	FUNC(true, say)
+	FUNC(true, skipSpeech)
+	FUNC(true, statusText)
+	FUNC(true, pause)
+	FUNC(true, onLeftMouse)
+	FUNC(true, onRightMouse)
+	FUNC(true, setCursor)
+	FUNC(true, addOverlay)
+	FUNC(true, addCharacter)
+	FUNC(true, playSound)
+	FUNC(true, getMouseX)
+	FUNC(true, getMouseY)
+	FUNC(true, addScreenRegion)
+	FUNC(true, onMoveMouse)
+	FUNC(true, onFocusChange)
+	FUNC(true, getOverObject)
+	FUNC(true, blankScreen)
+	FUNC(true, moveCharacter)
+	FUNC(true, onKeyboard)
+	FUNC(true, getObjectX)
+	FUNC(true, getObjectY)
+	FUNC(true, random)
+	FUNC(true, spawnSub)
+	FUNC(true, blankArea)
+	FUNC(true, hideCharacter)
+	FUNC(true, showCharacter)
+	FUNC(true, callEvent)
+	FUNC(true, removeScreenRegion)
+	FUNC(true, animate)
+	FUNC(true, turnCharacter)
+	FUNC(true, removeAllCharacters)
+	FUNC(true, removeAllScreenRegions)
+	FUNC(true, setScale)
+	FUNC(true, newStack)
+	FUNC(true, pushToStack)
+	FUNC(true, popFromStack)
+	FUNC(true, clearStatus)
+	FUNC(true, addStatus)
+	FUNC(true, removeLastStatus)
+	FUNC(true, lightStatus)
+	FUNC(true, getStatusText)
+	FUNC(true, setStatusColour)
+	FUNC(true, deleteFromStack)
+	FUNC(true, freeze)
+	FUNC(true, unfreeze)
+	FUNC(true, pasteImage)
+	FUNC(true, copyStack)
+	FUNC(true, completeTimers)
+	FUNC(true, setCharacterDrawMode)
+	FUNC(true, anim)
+	FUNC(true, costume)
+	FUNC(true, pickOne)
+	FUNC(true, setCostume)
+	FUNC(true, wait)
+	FUNC(true, somethingSpeaking)
+	FUNC(true, substring)
+	FUNC(true, stringLength)
+	FUNC(true, darkBackground)
+	FUNC(true, saveGame)
+	FUNC(true, loadGame)
+	FUNC(true, quitGame)
+	FUNC(true, rename)
+	FUNC(true, stackSize)
+	FUNC(true, pasteString)
+	FUNC(true, startMusic)
+	FUNC(true, setDefaultMusicVolume)
+	FUNC(true, setMusicVolume)
+	FUNC(true, stopMusic)
+	FUNC(true, stopSound)
+	FUNC(true, setFont)
+	FUNC(true, alignStatus)
+	FUNC(true, showFloor)
+	FUNC(true, showBoxes)
+	FUNC(true, positionStatus)
+	FUNC(true, setFloor)
+	FUNC(true, forceCharacter)
+	FUNC(true, jumpCharacter)
+	FUNC(true, peekStart)
+	FUNC(true, peekEnd)
+	FUNC(true, enqueue)
+	FUNC(true, setZBuffer)
+	FUNC(true, getMatchingFiles)
+	FUNC(true, inFont)
+	FUNC(true, onLeftMouseUp)
+	FUNC(true, onRightMouseUp)
+	FUNC(true, loopSound)
+	FUNC(true, removeCharacter)
+	FUNC(true, stopCharacter)
+	FUNC(true, launch)
+	FUNC(true, howFrozen)
+	FUNC(true, setPasteColour)
+	FUNC(true, setLitStatusColour)
+	FUNC(true, fileExists)
+	FUNC(true, floatCharacter)
+	FUNC(true, cancelSub)
+	FUNC(true, setCharacterWalkSpeed)
+	FUNC(true, deleteAllFromStack)
+	FUNC(true, setCharacterExtra)
+	FUNC(true, mixOverlay)
+	FUNC(true, pasteCharacter)
+	FUNC(true, setSceneDimensions)
+	FUNC(true, aimCamera)
+	FUNC(true, getMouseScreenX)
+	FUNC(true, getMouseScreenY)
+	FUNC(true, setDefaultSoundVolume)
+	FUNC(true, setSoundVolume)
+	FUNC(true, setSoundLoopPoints)
+	FUNC(true, setSpeechMode)
+	FUNC(true, setLightMap)
+	FUNC(true, think)
+	FUNC(true, getCharacterDirection)
+	FUNC(true, isCharacter)
+	FUNC(true, isScreenRegion)
+	FUNC(true, isMoving)
+	FUNC(true, deleteFile)
+	FUNC(true, renameFile)
+	FUNC(true, hardScroll)
+	FUNC(true, stringWidth)
+	FUNC(true, setSpeechSpeed)
+	FUNC(true, normalCharacter)
+	FUNC(true, fetchEvent)
+	FUNC(true, transitionLevel)
+	FUNC(true, spinCharacter)
+	FUNC(true, setFontSpacing)
+	FUNC(true, burnString)
+	FUNC(true, captureAllKeys)
+	FUNC(true, cacheSound)
+	FUNC(true, setCharacterSpinSpeed)
+	FUNC(true, transitionMode)
+	FUNC(false, _rem_movieStart)
+	FUNC(false, _rem_movieAbort)
+	FUNC(false, _rem_moviePlaying)
+	FUNC(false, _rem_updateDisplay)
+	FUNC(true, getSoundCache)
+	FUNC(true, saveCustomData)
+	FUNC(true, loadCustomData)
+	FUNC(true, setCustomEncoding)
+	FUNC(true, freeSound)
+	FUNC(true, parallaxAdd)
+	FUNC(true, parallaxClear)
+	FUNC(true, setBlankColour)
+	FUNC(true, setBurnColour)
+	FUNC(true, getPixelColour)
+	FUNC(true, makeFastArray)
+	FUNC(true, getCharacterScale)
+	FUNC(true, getLanguageID)
+	FUNC(false, _rem_launchWith)
+	FUNC(true, getFramesPerSecond)
+	FUNC(true, showThumbnail)
+	FUNC(true, setThumbnailSize)
+	FUNC(true, hasFlag)
+	FUNC(true, snapshotGrab)
+	FUNC(true, snapshotClear)
+	FUNC(true, bodgeFilenames)
+	FUNC(false, _rem_registryGetString)
+	FUNC(true, quitWithFatalError)
+	FUNC(true, _rem_setCharacterAA)
+	FUNC(true, _rem_setMaximumAA)
+	FUNC(true, setBackgroundEffect)
+	FUNC(true, doBackgroundEffect)
+	FUNC(true, setCharacterAngleOffset)
+	FUNC(true, setCharacterTransparency)
+	FUNC(true, setCharacterColourise)
+	FUNC(true, zoomCamera)
+	FUNC(true, playMovie)
+	FUNC(true, stopMovie)
+	FUNC(true, pauseMovie)
+};
+#undef FUNC
+
+int NUM_FUNCS = (sizeof (builtInFunctionArray) / sizeof (builtInFunctionArray[0]));
+
+} // End of namespace Sludge
diff --git a/engines/sludge/graphics.cpp b/engines/sludge/graphics.cpp
index 3c7cdbf..4a6d9b8 100644
--- a/engines/sludge/graphics.cpp
+++ b/engines/sludge/graphics.cpp
@@ -28,7 +28,6 @@
 #include "sludge/zbuffer.h"
 #include "sludge/backdrop.h"
 #include "sludge/movie.h"
-#include "sludge/CommonCode/specialsettings.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/language.cpp b/engines/sludge/language.cpp
index 06f2a08..c1917ad 100644
--- a/engines/sludge/language.cpp
+++ b/engines/sludge/language.cpp
@@ -27,7 +27,7 @@
 #include "sludge/moreio.h"
 #include "sludge/language.h"
 #include "sludge/sludge.h"
-#include "sludge/CommonCode/version.h"
+#include "sludge/version.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/loadsave.cpp b/engines/sludge/loadsave.cpp
index 04455bf..eb2cc61 100644
--- a/engines/sludge/loadsave.cpp
+++ b/engines/sludge/loadsave.cpp
@@ -45,7 +45,7 @@
 #include "sludge/bg_effects.h"
 #include "sludge/thumbnail.h"
 #include "sludge/utf8.h"
-#include "sludge/CommonCode/version.h"
+#include "sludge/version.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/main_loop.cpp b/engines/sludge/main_loop.cpp
index d888059..3676a3b 100644
--- a/engines/sludge/main_loop.cpp
+++ b/engines/sludge/main_loop.cpp
@@ -46,7 +46,7 @@
 #include "sludge/graphics.h"
 #include "sludge/helpers.h"
 #include "sludge/sludge.h"
-#include "sludge/CommonCode/specialsettings.h"
+#include "sludge/specialsettings.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/movie.cpp b/engines/sludge/movie.cpp
index 06defc4..c569fb4 100644
--- a/engines/sludge/movie.cpp
+++ b/engines/sludge/movie.cpp
@@ -35,7 +35,7 @@
 #include "AL/alure.h"
 #endif
 
-#include "sludge/CommonCode/specialsettings.h"
+#include "sludge/specialsettings.h"
 
 #include "sludge/newfatal.h"
 #include "sludge/timing.h"
diff --git a/engines/sludge/newfatal.cpp b/engines/sludge/newfatal.cpp
index 0f847bd..6501f82 100644
--- a/engines/sludge/newfatal.cpp
+++ b/engines/sludge/newfatal.cpp
@@ -27,7 +27,7 @@
 #include "sludge/errors.h"
 #include "sludge/graphics.h"
 #include "sludge/sludge.h"
-#include "sludge/CommonCode/version.h"
+#include "sludge/version.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/objtypes.cpp b/engines/sludge/objtypes.cpp
index bb9d707..e0fae1b 100644
--- a/engines/sludge/objtypes.cpp
+++ b/engines/sludge/objtypes.cpp
@@ -26,7 +26,7 @@
 #include "sludge/newfatal.h"
 #include "sludge/moreio.h"
 #include "sludge/fileset.h"
-#include "sludge/CommonCode/version.h"
+#include "sludge/version.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/people.cpp b/engines/sludge/people.cpp
index 45e7263..afc34cb 100644
--- a/engines/sludge/people.cpp
+++ b/engines/sludge/people.cpp
@@ -35,7 +35,7 @@
 #include "sludge/floor.h"
 #include "sludge/zbuffer.h"
 #include "sludge/sound.h"
-#include "sludge/CommonCode/version.h"
+#include "sludge/version.h"
 
 #define ANGLEFIX (180.0 / 3.14157)
 #define ANI_STAND 0
diff --git a/engines/sludge/sludger.cpp b/engines/sludge/sludger.cpp
index 620d50d..6f502f3 100644
--- a/engines/sludge/sludger.cpp
+++ b/engines/sludge/sludger.cpp
@@ -48,8 +48,8 @@
 #include "sludge/graphics.h"
 #include "sludge/variable.h"
 #include "sludge/sludge.h"
-#include "sludge/CommonCode/specialsettings.h"
-#include "sludge/CommonCode/version.h"
+#include "sludge/specialsettings.h"
+#include "sludge/version.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/specialsettings.h b/engines/sludge/specialsettings.h
new file mode 100644
index 0000000..0aa4786
--- /dev/null
+++ b/engines/sludge/specialsettings.h
@@ -0,0 +1,29 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#define SPECIAL_REGISTERED      1
+#define SPECIAL_FULLSCREEN      2
+#define SPECIAL_MOUSE_1         4
+#define SPECIAL_SILENT          8
+#define SPECIAL_MOUSE_2         16
+#define SPECIAL_INVISIBLE       32
+#define SPECIAL_HIDELOGO        64
+#define SPECIAL_HIDELOADING     128
diff --git a/engines/sludge/thumbnail.cpp b/engines/sludge/thumbnail.cpp
index 8044ee6..eb026b7 100644
--- a/engines/sludge/thumbnail.cpp
+++ b/engines/sludge/thumbnail.cpp
@@ -27,7 +27,7 @@
 #include "sludge/backdrop.h"
 #include "sludge/graphics.h"
 #include "sludge/newfatal.h"
-#include "sludge/CommonCode/version.h"
+#include "sludge/version.h"
 
 namespace Sludge {
 
diff --git a/engines/sludge/version.h b/engines/sludge/version.h
new file mode 100644
index 0000000..f984b0e
--- /dev/null
+++ b/engines/sludge/version.h
@@ -0,0 +1,38 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+#define MAJOR_VERSION 2
+#define MINOR_VERSION 2
+#define RELEASE_VERSION 1
+#define BUILD_VERSION 208
+#define TEXT_VERSION "2.2.1"
+#define WHOLE_VERSION (MAJOR_VERSION * 256 + MINOR_VERSION) // This version
+#define MINIM_VERSION (1             * 256 + 2)             // Earliest version of games the engine can run
+
+#define COPYRIGHT_TEXT "\251 Hungry Software and contributors 2000-2014"
+
+#define VERSION(a,b)    (a * 256 + b)
+
+namespace Sludge {
+
+extern int gameVersion;
+
+} // End of namespace Sludge





More information about the Scummvm-git-logs mailing list